“动作必须是简单的对象”……但是

时间:2018-12-04 16:50:13

标签: reactjs jestjs redux-thunk redux-mock-store

很抱歉,这是一个非常常见的错误,但是在下面的测试中,您不了解有问题的操作storeMgrAnnouncement(result)是不是一个普通的对象。模仿了api调用和thunk操作,但没有冒犯性行为。

home.test.js

/* not showing 3rd party imports */

import Home from '../../components/home';
import {getMgrAnnouncement} from "../../__mocks__/actions";
import {STORE_MGR_ANNOUNCEMENT} from "../../constants";
import {success} from "../../__fixtures__/announcementGet";

const mockStore = configureStore([thunk]);

describe('Home Page', () => {

    var store = null;
    const initialState = {};

    beforeEach(() => {
        store = mockStore(initialState);
        shallow(<Home store={store} />);
    });

    it ('should store manager announcement after retrieving it', async () => {
        await store.dispatch(getMgrAnnouncement());
        expect(store.getActions()).toContainEqual({
            type: STORE_MGR_ANNOUNCEMENT, 
            payload: success
        });
    });

__ mocks __ / actions / index.js

import { storeMgrAnnouncement } from '../../actions';
import { success } from '../../__fixtures__/announcementGet';

/* mock api call */
function announcementGet() {
  return new Promise((resolve, reject) => {
    process.nextTick(() => {
      resolve(success)
    })
  })
}

/* mock thunk action */
export function getMgrAnnouncement() {
  return function(dispatch, getState) {
    return announcementGet()
    .then(result => {
      /*
         ERROR: Actions must be plain objects. Use custom middleware for async actions.
      */
      dispatch(storeMgrAnnouncement(result));
    })
  }
}

actions / index.js

import { STORE_MGR_ANNOUNCEMENT } from '../../constants';

export function storeMgrAnnouncement(result) {
  return {
    type: STORE_MGR_ANNOUNCEMENT,
    payload: result
  }
}

1 个答案:

答案 0 :(得分:0)

您正在调度getMgrAnnouncement()的结果

store.dispatch(getMgrAnnouncement())

但是该函数返回一个函数:

function getMgrAnnouncement() {
  return function(dispatch, getState) {

您必须调度对象,而不是函数。