【问题标题】:Cannot spyOn on a primitive value; undefined given无法窥探原始值;给定的未定义
【发布时间】:2021-11-02 02:57:46
【问题描述】:

我正在尝试使用 jest 和 nest 编写单元测试用例,但出现以下错误: 在测试用例中,我尝试使用 spyon 函数调用 create credentials 方法,但 spyon 本身给了我一个错误。

 DeviceSecretService › should call createCredentials method with expected parms

    Cannot spyOn on a primitive value; undefined given

      23 |   // });
      24 |   it('should call createCredentials method with expected parms', async () => {
    > 25 |     const createCredentialsSpy = jest.spyOn(service, 'createCredentials');
         |                                       ^
      26 |     const deviceId = 'deviceId';
      27 |     const dci = new DeviceCommunicationInterface();
      at Object.<anonymous> (device/services/device-secret/device-secret.service.spec.ts:25:39)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        20.61 s, estimated 76 s
Ran all test suites matching /device-secret.service.spec.ts/i.
npm ERR! Test failed.  See above for more details.

下面是spec.ts文件的代码


  it('should call createCredentials method with expected parms', async () => {
    const createCredentialsSpy = jest.spyOn(service, 'createCredentials');
    const deviceId = 'deviceId';
    const dci = new DeviceCommunicationInterface();
    service.createCredentials(deviceId,dci);
    expect(createCredentialsSpy).toHaveBeenCalledWith(deviceId,dci);
  });
});

我都试过了,请给点建议

【问题讨论】:

  • 该错误意味着serviceundefined。你确定module.get&lt;DeviceSecretService&gt;(DeviceSecretService); 返回一个值吗?
  • 实际上,我不确定它是否返回一个值。我看过一些视频,他们使用 spyon 函数来检查该方法是否被调用。
  • 即使您的代码正常工作,它也没有正确测试。您的测试代码调用服务方法,然后期望它已被调用。它总会过去的,因为你刚刚调用了它。相反,您需要测试该方法的副作用和结果,例如检查它是否调用了 secretManager.createSecret,以及 — 等等,您的函数在哪里返回 catch 之外的任何内容?
  • 是的,我的函数在 catch 块之外返回。我已经更新了 .ts 文件

标签: typescript unit-testing jestjs nestjs spyon


【解决方案1】:

您没有为SecretManagerServiceClient 提供模拟值,因此Nest 将无法创建DeviceSecretService,这意味着您最终会将undefined 传递给jest.spyOn 方法。您需要提供某种custom provider 作为注入服务的模拟。可能是这样的

{
  provide: SecretManagerServiceClient,
  useValue: {
    getProjectId: jest.fn(),
    createSecret: jest.fn(),
  }
}

您显然希望提供更好的定义,但这应该是继续前进的起点。

【讨论】:

    猜你喜欢
    • 2020-10-30
    • 2020-12-06
    • 2020-02-24
    • 2021-07-05
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    相关资源
    最近更新 更多