使用jest和redux-thunk时如何模拟内部模块功能?

时间:2018-09-11 15:42:35

标签: javascript unit-testing redux jestjs redux-thunk

问题

我有一个操作,该操作基于keyCode按下来调度其他操作或动作。我希望能够测试是否调度了正确的操作,而无需实际调用它。

示例代码

taskOperations.js

const saveTask = () => {
  return (dispatch,getState) => {
    //some AJAX code I don't want to run
  }
}
const dispatchShortcut = (keyCode) => {
  return (dispatch, getState) => {
    switch(keyCode) {
      case 'ctrl+s':
        dispatch(saveTask())
        break
      //...more cases
  }
}
export { saveTask, dispatchShortcut }

taskOperations.spec.js

describe('dispatchShortcut', () => {

  it('dispatches verifyTask on a ctrl+v press', () => {
    const store = mockStore() //using redux-mock-store

    taskOperations.saveTask = jest.fn()
      //this still calls the original saveTask()
      store.dispatch(mockOperations.dispatchShortcut("ctrl+s"))

  })

如何可靠地将saveTask()函数存根?

0 个答案:

没有答案