以下のドキュメントを参考にしつつ
https://redux.js.org/recipes/writing-tests/#action-creators
http://www.wheresrhys.co.uk/fetch-mock/#usageusage-with-jest
jestの設定ファイルに
jest.mock('node-fetch', () => require('fetch-mock-jest').sandbox());
テストファイルにはfetchMockをセット。
import * as actions from '../fetchActions';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
const fetchMock = require('node-fetch');
it('should create GET_USER_SUCCESS when user fetching is done', function() {
fetchMock.getOnce('path:/user', {
body: { user: { name: 'ABC', id: 123 } },
});
const expectedActions = [
{ type: actionTypes.GET_USER },
{ type: actionTypes.GET_USER_SUCCESS,
data: {
user: { name: 'ABC', id: 123 },
},
status: 200,
}
];
return store.dispatch(actions.getUser()).then(() => {
// return of async actions
expect(store.getActions()).toEqual(expectedActions);
});
});
isomorphic-fetchを使用している場合、上記のnode-fetch
をisomorphic-fetch
に置き換えてテスト可能。