Jest.js 如何用笑话来模仿进口商品

g6ll5ycj  于 12个月前  发布在  Jest
关注(0)|答案(1)|浏览(128)

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

gcxthw6b

gcxthw6b1#

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

字符串

相关问题