Search code examples
unit-testingimportjestjs

How to mock an import with jest


I have a small redux middleware like so

import { hashHistory } from 'react-router'
import { REDIRECT_TO_LOGIN_REDIRECT_URL } from '../actions/login-redirect';
    
export default store => next => action => {
    
  if (action.type === REDIRECT_TO_LOGIN_REDIRECT_URL) {
    hashHistory.push(store.getState().loginRedirectUrl);
  }

  return next(action)
}

Which I want to test now. As you can see in line 1 I am importing hashHistory and use it later on. This I want to test (the call to hashHistory). To do that I would have to mock hashHistory, but I don't know how. I am using jest:

import { REDIRECT_TO_LOGIN_REDIRECT_URL } from '../actions/login-redirect';
import redirectMiddleware from './redirect-after-login';

describe('redirect after login middleware', () => {
    
  function setup() {
    const store = {
      subscribe: () => {},
      dispatch: () => {},
      getState: () => ({})
    };
    const next = jest.fn();
    const action = { type: REDIRECT_TO_LOGIN_REDIRECT_URL };
    return { store, next, action };
  }
        
  it('should push the redirect URL to the hashHistory', () => {
    // How to test it?
  })
    
});

Solution

  • You can mock the react-router module like this:

    import { hashHistory } from 'react-router'
    import { REDIRECT_TO_LOGIN_REDIRECT_URL } from '../actions/login-redirect';
    import redirectMiddleware from './redirect-after-login';
        
    jest.mock('react-router', () => ({hashHistory: { push: jest.fn()}}))
    
    describe('redirect after login middleware', () => {  
      function setup() {
        const store = {
          subscribe: () => {},
          dispatch: () => {},
          getState: () => ({loginRedirectUrl: 'someLoginRedirectUrl'})
        };
        const next = jest.fn();
        const action = { type: REDIRECT_TO_LOGIN_REDIRECT_URL };
        return { store, next, action };
      }
    
      it('should push the redirect URL to the hashHistory', () => {
        const { store, next, action } = setup()
        redirectMiddleware(store)(next)(action)
    
        expect(hashHistory.push).toHaveBeenCalledWith('someLoginRedirectUrl')
      })
    });