Jest.js 无法对基元值进行spyOn;给定的为undefined

blpfk2vs  于 12个月前  发布在  Jest
关注(0)|答案(1)|浏览(161)

我试图使用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);
  });
});


我什么都试过了请给我一些建议

bxgwgixi

bxgwgixi1#

您没有为SecretManagerServiceClient提供模拟值,因此Nest将无法创建DeviceSecretService,因此您将undefined传递给jest.spyOn方法。
要解决这个问题,您需要提供某种custom provider作为注入服务的mock。

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

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

相关问题