我有一个函数,它调用debounce,然后利用返回的去反弹值来调用debouncedThing.cancel()。
除了当我的函数被称为.cancel()时,我可以在我的测试中很好地模拟debounce。
在我的单元测试的顶端,我目前正在做:
jest.mock('lodash/debounce', () => fn => fn));
Psuedo代码的地方,我正在使用debounce如下所示:
const debouncedThing = debounce(
(myFunc, data) => myFunc(data),
DEBOUNCE_DELAY_TIME,
);
const otherFunc = () => {
/* omitted */
debouncedThing.cancel();
}发布于 2019-03-26 05:53:10
您只需要向fn添加cancel函数
jest.mock('lodash/debounce', () => fn => {
fn.cancel = jest.fn();
return fn;
});使用中的示例:
const debounce = require('lodash/debounce');
test('debouncedThing', () => {
const thing = jest.fn();
const debouncedThing = debounce(thing, 1000);
debouncedThing('an arg');
expect(thing).toHaveBeenCalledWith('an arg'); // Success!
debouncedThing.cancel(); // no error
expect(debouncedThing.cancel).toHaveBeenCalled(); // Success!
});https://stackoverflow.com/questions/55345281
复制相似问题