测试redux动作

Jim*_*mmy 6 javascript reactjs jestjs redux redux-thunk

我正试图用我们的redux动作实现开玩笑.鉴于以下操作foo并且它正在进行以下测试,以下测试失败,因为store.getActions()它只是按照我[{"type": "ACTION_ONE"}]的意愿返回[{"type": "ACTION_ONE"}, {"type": "ACTION_TWO"}].如何在测试时获得两个调度操作?谢谢!

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);
      });
  });
});
Run Code Online (Sandbox Code Playgroud)

Shu*_*tri 7

您没有模拟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);
      });
  });
});
Run Code Online (Sandbox Code Playgroud)