【问题标题】:Redux testing: Actions must be plain objects. Use custom middleware for async actionsRedux 测试:操作必须是普通对象。使用自定义中间件进行异步操作
【发布时间】:2020-02-05 03:59:41
【问题描述】:

我有一个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时的错误是:

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

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

【问题讨论】:

  • configureStore 是什么样的?它是否设置了 thunk 中间件?
  • 只是:import configureStore from 'redux-mock-store'
  • 这可能就是原因。您需要设置 thunk 才能使用 thunk 中间件。
  • 你的意思是在测试中?在实际代码中,一切正常,没有警告,没有错误......如果在测试中,你会如何正确地做到这一点?
  • 我留下了如何作为答案

标签: redux jestjs enzyme sinon


【解决方案1】:

您可能需要配置模拟商店以使用 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-30
    • 2020-11-05
    • 2019-12-26
    • 2017-11-16
    • 1970-01-01
    • 2017-05-01
    • 2021-11-04
    相关资源
    最近更新 更多