【问题标题】:How to Test a lodash's debounce function using Jest in react native?如何在本机反应中使用 Jest 测试 lodash 的去抖动功能?
【发布时间】:2020-01-07 23:50:01
【问题描述】:

我无法在我的 react 本机组件中使用 jest 测试包含去抖动功能的方法。有人可以帮我解决这个问题吗?

下面的代码是我试图开玩笑地测试我的 debounce 功能,但它不起作用。

jest.mock('lodash/debounce', () => jest.fn(fn => fn));

  it('should test debounce function', () => {
    debounce.mockClear();
    expect(debounce).toHaveBeenCalledTimes(1);
  });

下面的 sn-p 是我的方法,其中包含我正在尝试测试的 lodash 的去抖动功能。

import { debounce } from 'lodash';

  private getSearchConnections = debounce(() => {
    this.props.searchConnections(this.state.query, 1, false);
    }, 100
  );

【问题讨论】:

    标签: javascript typescript react-native jestjs lodash


    【解决方案1】:

    debounce 有一个 flush 方法,您可以调用它来立即调用它 https://lodash.com/docs/4.17.15#debounce

    getSearchConnections();
    getSearchConnections.flush();
    
    expect(searchConnections).toHaveBeenCalledTimes(1);
    

    【讨论】:

      【解决方案2】:

      有 2 种方法,第一种是您尝试执行的方法,用于测试委派。 你可以做更多的断言,比如

      expect(debounce).toHaveBeenCallWith(yourFn);
      

      您可以尝试的第二种方法是使用假计时器。

      it('msg', () => {
        jest.useFakeTimer();
      
        try {
          getSearchConnections();
          getSearchCOnnections();
      
          jest.advanceTimerByTime(100);
      
          expect(searchConnections).toHaveBeenCalledTimes(1);
        } finally {
          jest.useRealTimer();
        }
      }); 
      

      一些小细节,通常在消息中,我们只是描述类应该如何表现而不是测试应该如何测试,例如it should delegate to debounceit should debounce call to some API

      【讨论】:

      • 它对我不起作用。 debounced 函数中的任何代码都没有被执行
      • 请提供更多细节,最好是可重现的回购/代码,或至少一些伪代码。
      猜你喜欢
      • 2019-06-16
      • 2019-02-12
      • 1970-01-01
      • 1970-01-01
      • 2014-12-27
      • 2021-07-16
      • 1970-01-01
      • 2020-11-28
      • 2017-05-03
      相关资源
      最近更新 更多