测试 redux 动作

Testing a redux action

我正在尝试用我们的 redux 操作来实现笑话。给定以下操作 foo 及其后续测试,以下测试失败,因为 store.getActions() 仅按预期 [{"type": "ACTION_ONE"}, {"type": "ACTION_TWO"}] 返回我 [{"type": "ACTION_ONE"}]。测试时如何获得两个派发的动作?谢谢!

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

export const foo = () => {
  return (dispatch) => {
    dispatch(actionOne());
    return HttpService.get(`api/sampleUrl`)
      .then(json => dispatch(actionTwo(json.data)))
      .catch(error => handleError(error));
  };
};

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

beforeEach(() => {
  store = mockStore({});
});

describe('sample test', () => {
  test('validates foo complex action', () => {
    const expectedActions = [
      {type: actionTypes.ACTION_ONE},
      {type: actionTypes.ACTION_TWO},
    ];

    return store.dispatch(actions.foo())
      .then(() => {
        expect(store.getActions())
          .toEqual(expectedActions);
      });
  });
});

您还没有模拟 API 调用,因为如果没有模拟它就不会成功,所以不会触发 promise 解析时调度的操作。您可以使用 fetchMock 模拟 API 调用。一旦你正确地做到了这一点,你的测试就会成功

import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import fetchMock from 'fetch-mock';
import fetch from 'node-fetch';

export const foo = () => {
  return (dispatch) => {
    dispatch(actionOne());
    return fetch(`api/sampleUrl`)
      .then(r => r.json())
      .then(json => dispatch(actionTwo(json)))
      .catch(error => handleError(error));
  };
};

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

beforeEach(() => {
  store = mockStore({});
  fetchMock.restore()
});

describe('sample test', () => {
  test('validates foo complex action', () => {

    fetchMock.getOnce('api/sampleUrl', {
      body: { sample: ['do something'] }
    })

    const expectedActions = [
      {type: actionTypes.ACTION_ONE},
      {type: actionTypes.ACTION_TWO},
    ];

    return store.dispatch(actions.foo())
      .then(() => {
        expect(store.getActions())
          .toEqual(expectedActions);
      });
  });
});