0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

fetch-mock-jestを使用したreduxのテスト

Posted at

以下のドキュメントを参考にしつつ
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-fetchisomorphic-fetchに置き換えてテスト可能。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?