Redux 测试:操作必须是普通对象。使用自定义中间件进行异步操作

Redux testing: Actions must be plain objects. Use custom middleware for async actions

我有一个 Redux 应用程序,它运行完美,没有任何错误。现在我尝试用 EnzymeJestSinon:

来测试它
  it('calls constructor', () => {
    sinon.spy(SavedVariantsComponent.prototype, 'constructor')
    const store = configureStore()(STATE1)
    wrapper = mount(<SavedVariantsComponent store={store} match={{ params: {} }} />)
    expect(SavedVariantsComponent.prototype.constructor).toHaveProperty('callCount', 1)
  })

SavedVariantsComponent 我有 mapDispatchToProps:

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    onSubmit: (updates) => {
      dispatch(updateSavedVariantTable(updates))
      const { match, analysisGroup } = ownProps
      const { familyGuid, variantGuid, tagArray, gene } = match.params
      const familyGuids = familyGuid ? [familyGuid] : (analysisGroup || {}).familyGuids
      const combineVariants = /combined_variants/.test(match.url)
      dispatch(loadSavedVariants(combineVariants, familyGuids, variantGuid, tagArray, gene))
    },  
    loadSavedVariants: (...args) => dispatch(loadSavedVariants(...args)),
  }
}

loadSavedVariants 看起来像这样:

export const loadSavedVariants = (combineVariants, familyGuids, variantGuid, tagArray, gene = '') => {
  return (dispatch, getState) => {
...
...

运行 jest 时的错误是:

Actions must be plain objects. Use custom middleware for async actions.

这使得 HTTP Request 在当前情况下可能不起作用。如何修复此错误?我需要测试构造函数是否被调用,但稍后还需要查看内部 Components 是如何呈现的,因此需要 mount 在那里。我想我在测试中做错了,而不是在实际代码中,因为后者没有任何错误、警告或问题。

您可能需要配置模拟商店以使用 redux-thunk。参见:https://github.com/dmitry-zaets/redux-mock-store#asynchronous-actions

import configureStore from 'redux-mock-store'
import thunk from 'redux-thunk'

const middlewares = [thunk] // add your middlewares like `redux-thunk`
const mockStore = configureStore(middlewares)