测试一个 redux 动作
Posted
技术标签:
【中文标题】测试一个 redux 动作【英文标题】:Testing a redux action 【发布时间】:2019-07-07 17:21:01 【问题描述】:我正在尝试用我们的 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);
);
);
);
【问题讨论】:
【参考方案1】:您尚未模拟 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);
);
);
);
【讨论】:
以上是关于测试一个 redux 动作的主要内容,如果未能解决你的问题,请参考以下文章
在 Redux 中测试动作创建者时如何模拟 Firebase SDK?
我的减速机应该处理@@ redux-saga-test-plan / INIT动作吗?