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

use*_*307 12 unit-testing reactjs redux enzyme

我知道“动作必须是普通对象。对异步动作使用自定义中间件。” 已被问过很多次,但我找不到解决方案。

问题只发生在酶测试中。

这是我的 componentDidMount,它记录响应:

componentDidMount () {
  this.props.dispatch(fetchUsers())
    .then(response => console.log(response))
}
Run Code Online (Sandbox Code Playgroud)

日志响应:用户:(27) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, { …}、{…}、{…}、{…}、{…}、{…}、{…}、{…}、{…}、{…}、{…}、{…}、{…} , {...}, {...}, {...}, {...}] 类型:“GET_USERS_SUCCESS”

这是我的行动

export const fetchUsers = () => (dispatch) => {
  dispatch(fetchUSersRequest())
  const request = axios({
    method: 'GET',
    url: `${BASE_URL}users.json`,
    headers: []
  })
  return request.then(
    response => dispatch(fetchUsersSuccess(response.data)),
    err => dispatch(fetchUsersError(err))
  )
}
Run Code Online (Sandbox Code Playgroud)

该组件是连接组件。这是测试

import React from 'react'
import configureMockStore from 'redux-mock-store'
import { shallow } from 'enzyme'

import Users from './'
import * as mocks from '../../mocks/users'

const mockStore = configureMockStore();

describe('it works', () => {
  const store = mockStore({});
  const wrapper = shallow(<Users store={store} users={mocks.getUsersMock} filters={mocks.getFiltersMock} />).dive().dive()
  console.log(wrapper.debug())
  it("renders a div", () => {
    expect(wrapper.find('div').length).toBe(1)
  })
});
Run Code Online (Sandbox Code Playgroud)

然后错误在单元测试输出中

? 它有效 › 遇到声明异常

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

  21 |
  22 |   componentDidMount () {
> 23 |     this.props.dispatch(fetchUsers())
     |                ^
  24 |   }
Run Code Online (Sandbox Code Playgroud)

我已经在使用 redux-thunk

Ale*_*sky 26

尝试redux-thunk向您注册中间件,redux-mock-store以便测试知道您在实际商店中使用的异步中间件正在使用:

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

const middlewares = [thunk]
const mockStore = configureMockStore(middlewares)
Run Code Online (Sandbox Code Playgroud)

希望这有帮助!

  • 哦!非常感谢!那行得通,我花了几个小时在这上面......真是松了一口气:) (2认同)
  • 你不是我要求的英雄,但肯定是我需要的英雄。谢谢你! (2认同)
  • @tim.rohrer,您可能希望将其设为导出函数,以便您可以创建此模拟存储的实例并传递给需要存储的组件。您是否有一个测试根组件,它采用包装测试元素的存储?这实际上取决于您正在进行的测试。 (2认同)