简体   繁体   中英

How to Test a lodash's debounce function using Jest in react native?

I'm not able to test a method which contains a debounce function using jest in my react native component. Can someone help me with this?

The below code is what I tried to test my debounce function in jest but it did not work.

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

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

The below snippet is my method which contains lodash's debounce function which I'm trying to test.

import { debounce } from 'lodash';

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

There are 2 approaches, the first one is the one you are trying to do, to test delegation. You could do more assertions like

expect(debounce).toHaveBeenCallWith(yourFn);

The second one you could try is to use fake timer.

it('msg', () => {
  jest.useFakeTimer();

  try {
    getSearchConnections();
    getSearchCOnnections();

    jest.advanceTimerByTime(100);

    expect(searchConnections).toHaveBeenCalledTimes(1);
  } finally {
    jest.useRealTimer();
  }
}); 

Some minor detail, usually in the message, we just describe how the class should behave instead of how the test should test, like it should delegate to debounce or it should debounce call to some API

debounce has a flush method you can call to immediate invoke it https://lodash.com/docs/4.17.15#debounce

getSearchConnections();
getSearchConnections.flush();

expect(searchConnections).toHaveBeenCalledTimes(1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM