1

我正在尝试使用 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);
  });
});

我尝试了一切请给一些建议

4

1 回答 1

2

您没有为 提供模拟值SecretManagerServiceClient,因此 Nest 将无法创建DeviceSecretService,这意味着您最终将传递undefined给该jest.spyOn方法。您需要提供某种自定义提供程序作为注入服务的模拟。可能像

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

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

于 2021-09-03T21:26:52.387 回答