unit-testing - 如何用 Jest 模拟导入

标签 unit-testing import jestjs

我有一个像这样的小型 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?
  })
    
});

最佳答案

你可以像这样模拟 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')
  })
});

关于unit-testing - 如何用 Jest 模拟导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44154044/

相关文章:

ios - 当且仅当运行时到达代码块内部时才导入类

将 csv 数据文件导入 DB2 的 Linux shell 脚本

react-native - Jest 测试失败 "Cannot find module ' images/myimage.png' from SignInOrRegister.js"with image size class @1x,@2x,@3x,@4x

jestjs - NestJS开 Jest 错误: TypeError: Cannot read properties of undefined (reading '[any variable from required config]' )

javascript - 如何使用 Jest 来监视 prop 内的方法并将其传递给组件?

java - 如何使用 @PathVariable 对 Spring MVC Controller 进行单元测试?

java - 使用mockito进行单元测试时抛出WrongTypeOfReturnValue异常

unit-testing - 如何恢复使用 jest.mock() 创建的模拟?

java - junit 测试套件

python - 是否可以导入已编译的 python 文件?