2017-05-24 69 views
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? 
    }) 

}); 

回答

4

你可以嘲笑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') 
    }) 

}); 
+0

完美的答案!謝謝! – Lukas