测试 Redux Action

6

我正在尝试将jest与我们的redux actions结合使用。给定以下操作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);
      });
  });
});
1个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接