如何在React Native中使用Jest测试lodash的去抖功能?

时间:2019-09-05 06:09:08

标签: javascript typescript react-native jestjs lodash

我无法在我的react native组件中使用jest测试包含反跳功能的方法。有人可以帮我吗?

下面的代码是我试图以开玩笑的方式测试我的去抖动功能的方法,但是它没有用。

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

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

下面的代码段是我的方法,其中包含我要测试的lodash的反跳功能。

import { debounce } from 'lodash';

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

2 个答案:

答案 0 :(得分:1)

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

getSearchConnections();
getSearchConnections.flush();

expect(searchConnections).toHaveBeenCalledTimes(1);

答案 1 :(得分:0)

有2种方法来测试委派,第一种是您要尝试的方法。 您可以做更多断言,例如

movie

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

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 debounce