如何模拟和测试redux thunk操作?

如何模拟和测试redux thunk操作?,redux,redux-thunk,Redux,Redux Thunk,我找不到一种方法来正确测试异步redux操作,这些操作在其主体中使用其他操作: import {postRequest} from './http' export function saveAnswer (id, answer) { return (dispatch) => { dispatch({type: SAVE_ANSWER}) return dispatch(postRequest(ANSWERS_ENDPOINT, {id, answer})) }

我找不到一种方法来正确测试异步redux操作,这些操作在其主体中使用其他操作:

import {postRequest} from './http'

export function saveAnswer (id, answer) {
  return (dispatch) => {
    dispatch({type: SAVE_ANSWER})

    return dispatch(postRequest(ANSWERS_ENDPOINT, {id, answer}))
  }
}
我想存根postRequest,这样它的逻辑就不会被执行

我已为规范设置:

import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import * as ACTIONS from '../answers'
import * as HTTP_ACTIONS from '../http'

const mockStore = configureMockStore([thunk])
const store = mockStore({})


describe('saveAnswer()', () => {
  it('test', () => {
    sinon.stub(HTTP_ACTIONS, 'postRequest').returns(Promise.resolve({}))

    store.dispatch(ACTIONS.saveAnswer(ID, ANSWER))
  })
})
当我运行spec时,出现以下错误: 错误:操作必须是普通对象。使用自定义中间件进行异步操作

我不明白我做错了什么,但它必须与Stubing postRequest操作有关

如何正确地存根该操作?

如果使用redux thunk,分派的参数必须是函数或普通对象。在您的情况下,postRequest返回的Promise对象既不是普通对象也不是函数;。因此,您可以使用promise对象作为参数调用dispatch。因此,请确保使用参数调用dispatch,该参数可以是函数,也可以是类型属性为的普通操作对象

您可以像这样重写代码,假设postRequest返回promise,然后错误应该消失:

import {postRequest} from './http'

export function saveAnswer (id, answer) {
  return (dispatch) => {
    dispatch({type: SAVE_ANSWER})
    postRequest(ANSWERS_ENDPOINT, {id, answer})
      .then((response) => dispatch({
         type: ANSWER_SAVED,
         data: response
      }));
  };
}
回复评论后的更新:

因此,由于postRequest不返回Promise对象,而是返回函数,所以问题在于如何将其存根。请尝试此存根还应返回函数而不是承诺对象:

const mockFuntion = () => Promise.resolve({}); // here can also  be an spy function if needed
sinon.stub(HTTP_ACTIONS, 'postRequest').returns(mockFuntion);

我不能这样做,因为postRequest内部也使用了dispatch:导出函数postRequest url,body{return dispatch=>{dispatch{type:POST_REQUEST,url,body}}}}}}谢谢,这实际上是缺少的,这就是昨天睡觉前我想到的您是否可以编辑您的答案并将其添加为完整的解决方案?请查看我需要返回承诺:sinon.stubHTTP_ACTIONS,'postRequest'。返回=>promise.resolve{}