我无法在使用 jest 的测试中对函数的第二次和第三次调用进行间谍操作
我尝试按照文档这样做:
it("should succeed after retry on first attempt failure", async () => {
jest.spyOn(nukiService, "lockDoors")
.mockResolvedValueOnce(Promise.resolve({ status: 503 }))
.mockResolvedValueOnce(Promise.resolve({ status: 200 }));
expect((await nukiService.lockDoorsWithRetry()).status)
.toBe(200);
});
it("should fail after 3 retries", async () => {
jest.spyOn(nukiService, "lockDoors")
.mockResolvedValueOnce(Promise.resolve({ status: 503 }))
.mockResolvedValueOnce(Promise.resolve({ status: 503 }))
.mockResolvedValueOnce(Promise.resolve({ status: 503 }));
expect((await nukiService.lockDoorsWithRetry()).status)
.toBe(424);
});
我的测试由于超时而失败,所以我认为问题来自间谍On,它不起作用:
● NukiService › handle doors › should succeed after retry on first attempt failure
thrown: "Exceeded timeout of 5000 ms for a test.
Add a timeout value to this test to increase the timeout, if this is a long-running test. See https://jestjs.io/docs/api#testname-fn-timeout."
85 | });
86 |
> 87 | it("should succeed after retry on first attempt failure", async () => {
| ^
88 | jest.spyOn(nukiService, "lockDoors")
89 | .mockResolvedValueOnce(Promise.resolve({ status: 503 }))
90 | .mockResolvedValueOnce(Promise.resolve({ status: 200 }));
at services/nuki.service.spec.ts:87:5
at services/nuki.service.spec.ts:18:3
at Object.<anonymous> (services/nuki.service.spec.ts:5:1)
测试抛出超时。它表示
nukiService.lockDoorsWithRetry()
所花费的时间比为测试超时设置的值要长。
尝试在
nukiService.lockDoorsWithRetry()
内部进行调试,看看内部代码的行为是什么以及是否是您所期望的。