Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I know " Actions must be plain objects. Use custom middleware for async actions." has been asked many times, but I can't find the solution.

The problem only happens in the enzyme test.

This is my componentDidMount, which logs the response:

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

log response: users: (27) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}] type: "GET_USERS_SUCCESS"

And this is my action

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

The component is a connected component. and here it's test

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

Then the error is in the unit test output

● it works › encountered a declaration exception

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

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

I am already using redux-thunk

like image 955
user3808307 Avatar asked May 23 '19 03:05

user3808307


1 Answers

Try registering redux-thunk middleware with your redux-mock-store so that the tests are aware of the async middleware you are using in your actual store is using:

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

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

Hopefully that helps!

like image 128
Alexander Staroselsky Avatar answered Oct 08 '22 04:10

Alexander Staroselsky