2017-02-01 40 views
1

我正在嘗試爲redux動作創建者編寫一個測試,以調度在同一個文件中定義的另一個動作。這很難解釋,所以這裏有一個例子:jest redux-thunk測試是否調度了同一個模塊的動作

// actions/timer.js 

export const onClickButton =() => { 
    return dispatch => { 
    // ... do something 
    dispatch(someAction); 
    dispatch(onTimerStart()); // This is the action creator stated below 
    }; 
}; 

export const onTimerStart =() => { 
    return dispatch => { 
    // ... do something 
    dispatch(someAction); 
    }; 
}; 

我用開玩笑,我要確保調用onClickButtononTimerStart動作調度。 (在我的實際代碼,這些行動創造者採取一些參數以及基於這些,onTimerStart應該或不應該派出)

我似乎無法弄清楚如何嘲笑onTimerStart這樣我就可以測試,如果它被稱爲與否。

+0

嗨@Bram:Iam也有類似的問題,你有沒有找到解決你的問題?如果是的話,請分享結果 – Mothy

回答

0
  1. 您可以使用jest.fn()創建一個模擬調度。

  2. 然後,調用動作創建器一次以獲取「thunk」(將調度作爲參數的返回函數)。

  3. 然後,用你的模擬調度作爲參數調用返回的函數。

  4. 您可以使用dispatch.mock.calls看到調用調度。

(1)模擬函數

const dispatch = jest.fn(); 

(2)(3)獲取的thunk並調用它

const thunk = onClickButton(); 
thunk(dispatch); 

(4)檢查,在兩個電話派遣

// indices mean: [the second call] [the first argument of that call] 
dispatch.mock.calls[1][0] 
1

您可以使用「redux-mock-store」並聲明您的預期操作已分派,而不是模擬onTimerStart()。

下面是一個粗略的例子。

import configureMockStore from 'redux-mock-store'; 
import thunk from 'redux-thunk'; 
import * as timerActions from './actions/timerActions'; 
import * as types from './constants/actionTypes'; 
import { InitialAppState } from './reducers/initialState'; 

const createMockStore = configureMockStore([thunk]); 

describe('timerActions',() => { 

    it('successful call should dispatch someAction',() => { 

     // Arrange. 
     const expectedActions = [ 
      { type: types.someAction}, 
     ]; 

     const store = createMockStore(InitialAppState); 

     // Act. 
     store.dispatch(actions.onClickButton()); 

     // Assert. 
     const dispatchedActions = store.getActions(); 
     expect(dispatchedActions).toEqual(expectedActions); 
    }); 

}); 

使用這個例子中,你只需要在正確的位置,你所提到的參數進行添加,並導入你的actionCreators,actionTypes和初始化狀態。

請注意,這個例子是用typescript編寫的。

+0

嗨NIck,謝謝你的例子。如果有一個派遣,您的示例工作。但是,當有多個調度時,斷言總是需要最後一次調度,所以我試圖找出如何在相同的操作中測試多個調度。我不能幹淨地發表評論中的代碼,但爲了給你一個原始問題的例子,第二個動作'onTimerStart'是一個單獨的調度(這是工作),而'onClickButton'有兩個派發和笑話只捕獲第二個。 – andre

+0

@AndriyKulak,這聽起來像你試圖測試異步行爲。請參閱redux文檔瞭解如何執行此操作 - http://redux.js.org/docs/recipes/WritingTests.html#async-action-creators – Nick

相關問題