1

我无法在我的反应原生组件中使用 jest 测试包含去抖动功能的方法。有人可以帮我弄这个吗?

下面的代码是我试图开玩笑地测试我的去抖功能,但它没有工作。

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

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

下面的代码片段是我的方法,其中包含我正在尝试测试的 lodash 的 debounce 函数。

import { debounce } from 'lodash';

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

4

2 回答 2

2

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

getSearchConnections();
getSearchConnections.flush();

expect(searchConnections).toHaveBeenCalledTimes(1);
于 2019-09-08T23:22:32.283 回答
1

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

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

于 2019-09-05T15:09:40.303 回答