Ste*_*h M 6 mocking debouncing lodash jestjs
寻找一些关于如何模拟的建议.cancel
在 lodash 的反跳中模拟该方法的建议。
我有一个正在调用的函数debounce
,然后利用返回的去抖值来调用debouncedThing.cancel()
.
我能够debounce
在测试中很好地模拟,除了调用我的函数时.cancel()
。
在我目前正在做的单元测试的顶部:
jest.mock('lodash/debounce', () => fn => fn));
除了我打电话的地方之外,上面的模拟工作得很好debouncedThing.cancel()
。在那些测试中,我收到一个错误debouncedThing.cancel()
在这些测试中,我收到一个不是函数的
我使用 debounce 的伪代码如下所示:
const debouncedThing = debounce(
(myFunc, data) => myFunc(data),
DEBOUNCE_DELAY_TIME,
);
const otherFunc = () => {
/* omitted */
debouncedThing.cancel();
}
Run Code Online (Sandbox Code Playgroud)
您只需将该cancel
功能添加到fn
:
jest.mock('lodash/debounce', () => fn => {
fn.cancel = jest.fn();
return fn;
});
Run Code Online (Sandbox Code Playgroud)
使用中的示例:
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!
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6673 次 |
最近记录: |