【发布时间】: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);
});
});
我都试过了,请给点建议
【问题讨论】:
-
该错误意味着
service是undefined。你确定module.get<DeviceSecretService>(DeviceSecretService);返回一个值吗? -
实际上,我不确定它是否返回一个值。我看过一些视频,他们使用 spyon 函数来检查该方法是否被调用。
-
即使您的代码正常工作,它也没有正确测试。您的测试代码调用服务方法,然后期望它已被调用。它总会过去的,因为你刚刚调用了它。相反,您需要测试该方法的副作用和结果,例如检查它是否调用了 secretManager.createSecret,以及 — 等等,您的函数在哪里返回
catch之外的任何内容? -
是的,我的函数在 catch 块之外返回。我已经更新了 .ts 文件
标签: typescript unit-testing jestjs nestjs spyon