在函数中使用 Jest 测试承诺的结果



开玩笑的文档涵盖了给定函数返回 Promise 的情况并演示如何测试它。
但是,如何测试在函数内调用 Promise.then的 void 函数呢?

这是一个关于我如何考虑这样做的例子,但这不起作用。

函数

function dummyFunction(): void {
dummyService.getDummy$().then((dummy: Dummy): void => {
console.log(`Dummy fetched`);
});
}

测试内容

describe(`dummyFunction()`, (): void => {
let dummyServiceGetDummy$Spy: jest.SpyInstance;
let consoleLogSpy: jest.SpyInstance;
beforeEach((): void => {
dummyServiceGetDummy$Spy = jest.spyOn(dummyService, `getDummy$`).mockImplementation();
consoleLogSpy = jest.spyOn(console, `log`).mockImplementation();
});
it(`should fetch dummy`, (): void => {
expect.assertions(2);
dummyFunction();
expect(dummyServiceGetDummy$Spy).toHaveBeenCalledTimes(1);
expect(dummyServiceGetDummy$Spy).toHaveBeenCalledWith();
});
describe(`when dummy was successfully fetched`, (): void => {
beforeEach((): void => {
dummyServiceGetDummy$Spy.mockReturnValue((): Promise<void> => Promise.resolve());
});
it(`should log`, (): void => {
expect.assertions(2);
dummyFunction();
expect(consoleLogSpy).toHaveBeenCalledTimes(1);
expect(consoleLogSpy).toHaveBeenCalledWith(`Dummy fetched`);
});
});
});

依赖

"jest": "26.0.1"
"ts-jest": "26.0.0"

Promise 封装是一种反模式。dummyFunction应该返回对链的承诺,以便正确重用和测试:

function dummyFunction(): void {
return dummyService.getDummy$().then((dummy: Dummy): void => {
console.log(`Dummy fetched`);
});
}

然后可以使用内置的 Jest 承诺支持进行测试:

it(`should fetch dummy`, async () => {
await expect(dummyFunction()).resolves.toBe(undefined);
expect(dummyServiceGetDummy$Spy).toHaveBeenCalledWith();
expect(consoleLogSpy).toHaveBeenCalledWith(`Dummy fetched`);
});

最新更新