简体   繁体   中英

mock function with return mock value in jest

I use react-redux to create a middleware and would like to write some test for it. How can I mock the return from helper function checkNumberHistory so I can test the logic that if blocked ?

import {checkNumberHistory} from '@src/helper';

export const middlewareAction = (): AppThunk => {
  return async (dispatch, getState) => {
    const recordededNumber = getState()?.recordedNumber || 0;
    const strNumber = getState()?.strNumber || 0;
    const isNumberChanged = checkNumberHistory(recordededNumber, strNumber);

    if (isNumberChanged) {
      dispatch(setNumber(strNumber));
    }
  };
};

You should be able to use jest.mock to mock the checkNumberHistory import. The following shows using the actual values for other named imports and mocking checkNumberHistory :

jest.mock('@src/helper', () => ({
  ...jest.requireActual('@src/helper'),
  checkNumberHistory: () => 'Some mocked return value',
}));

describe('middleware tests', () => {
  it('does something', () => {
    // test here
  });
});

As mentioned in my comment, I tend to try not to mock helper functions if I don't have to (ie, if they're deterministic).

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