【问题标题】:How do you mock lodash debounce.cancel with jest?你如何用玩笑来模拟 lodash debounce.cancel?
【发布时间】:2019-03-25 19:40:56
【问题描述】:

寻找一些关于如何在 lodash 的 debounce 中模拟 .cancel 方法的建议。

我有一个函数调用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();
}

【问题讨论】:

    标签: mocking jestjs lodash debounce


    【解决方案1】:

    您只需将cancel 函数添加到fn

    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!
    });
    

    【讨论】:

    • ...另外,根据您的代码和您要测试的内容,您可能可以通过使用 Timer Mocks 来避免模拟 debounce
    猜你喜欢
    • 1970-01-01
    • 2022-12-15
    • 1970-01-01
    • 2021-01-01
    • 2020-04-05
    • 2021-01-06
    • 2020-02-08
    • 1970-01-01
    • 2022-10-06
    相关资源
    最近更新 更多