1

I have this function

import _ from 'underscore';
const configMap = {};
export function someFunctionName(someValue, dispatch, reduxAction) {
  if (!configMap[someValue]) {
    configMap[someValue] = _.debounce(
      (someValue) => dispatch(reduxAction(someValue)),
      1000,
    );
  }
  return configMap[someValue];
}

with jest tests:

const dispatchMock = jest.fn();
const reduxAction = jest.fn().mockReturnValue({});

jest.useFakeTimers();
describe('someFunctionName', () => {
  it('should dispatch reduxAction', async () => {
    someFunctionName('value', dispatchMock, reduxAction);
    jest.runAllTimers();
    expect(reduxAction).toHaveBeenCalled();
  });
});

Test keeps failing and i'm not sure why. I initially thought it could be the debounce method needs a mock, but that doesn't seem to fix it.

Akin
  • 61
  • 7

1 Answers1

0

Lodash's debounce function is asynchronous which means the return statement of someFunctionName is going to execute before debounce comes back with a value. Additionally, the function inside debounce is not going to run until the provided wait time of 1000ms has elapsed.

You'll need to add async logic to wait for the result of debounce within someFunctionName before returning. This SO post may provide further help on how to achieve this.

Sean Anglim
  • 179
  • 10