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

时间:2019-05-23 03:03:44

标签: reactjs unit-testing redux enzyme

我知道“动作必须是简单的对象。对于异步动作,请使用自定义中间件。”已经被问了很多遍了,但是我找不到解决方法。

仅在酶测试中出现问题。

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

componentDidMount () {
  this.props.dispatch(fetchUsers())
    .then(response => console.log(response))
}

日志响应:用户:(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))
  )
}

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

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)
  })
});

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

●有效›遇到声明异常

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

  21 |
  22 |   componentDidMount () {
> 23 |     this.props.dispatch(fetchUsers())
     |                ^
  24 |   }

我已经在使用redux-thunk

1 个答案:

答案 0 :(得分:1)

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

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

const middlewares = [thunk]
const mockStore = configureStore(middlewares)

希望有帮助!