如何用Jest测试返回箭头函数的函数?



我有一个这样的函数:

export const myFunc = (a, b ,callBack) => {
const timer = setTimeout(() => {
callBack(a+b);
}, 10);
return () => clearTimeout(timer);
};

我可以通过这样做来测试回调函数:

jest.useFakeTimers();
describe('myFunc', () => {
const callBack = jest.fn();
it('runs myFunc', () => {
myFunc(1, 2, callBack);
jest.runAllTimers();
expect(callBack).toHaveBeenCalledWith(3);
});

然而,最后一行return () => clearTimeout(timer)从来没有被测试过。Jest报告说这条线是function not coveredstatement not covered。谁能告诉我一种方法来覆盖这条线不使用任何其他外部测试库像酶?

该函数未被调用,因此不包含

另一个测试是:

let cleanup = myFunc(1, 2, callBack);
cleanup()
jest.runAllTimers();
expect(callBack).not.toHaveBeenCalled();

最新更新