如何用 jest 模拟导入

问题描述 投票:0回答:1

我有一个像这样的小

redux
中间件

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)
}

我现在想测试一下。正如您在第 1 行中看到的,我正在导入

hashHistory
并稍后使用它。我想测试一下(调用
hashHistory
)。为此,我必须嘲笑
hashHistory
,但我不知道如何。我正在使用
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?
  })
    
});
unit-testing import jestjs
1个回答
6
投票

您可以像这样模拟

react-router
模块:

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')
  })
});
© www.soinside.com 2019 - 2024. All rights reserved.