用玩笑和酵素测试已调度动作返回的Promise.all

时间:2018-11-21 10:11:51

标签: redux jestjs enzyme redux-thunk

在了解如何测试异步操作创建者方面我遇到了一个很大的问题。 动作是将数据获取到github api,后者将获取用户信息并获取他的存储库,我将它们存储到Promise.all()中以将它们解析为1许诺,但我没有发现任何线索来测试模拟fetchData的正确方法

这是动作:

import fetch from 'isomorphic-fetch';
import apikey from '../../apikey';
import {
  fetchUserBegin,
  fetchUserInfoSucces,
  fetchUserError,
  fetchUserReposSuccess,
  fetchUserLoadingEnd,
} from './index';

const apkey = process.env.NODE_ENV === 'production' ? '' : apikey;

export function fetchData(url) {
  return (
    fetch(url)
      .then(result => result.json())
  );
}


export default function takeUserNameAndFetchData(name) {
  const userInfoUrl = `https://api.github.com/users/${name}${apkey}`;
  const userRepoUrl = `https://api.github.com/users/${name}/repos${apkey}`;

  return (dispatch) => {
    dispatch(fetchUserBegin());
    return Promise.all([
      fetchData(userInfoUrl),
      fetchData(userRepoUrl),
    ])
      .then(([info, repos]) => {
        console.log(info, repos);
        dispatch(fetchUserInfoSucces(info));
        dispatch(fetchUserReposSuccess(repos));
        dispatch(fetchUserLoadingEnd());
      })
      .catch((err) => {
        dispatch(fetchUserError(err));
      });
  };
}

这是我的测试:

import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import fetchMock from 'fetch-mock';
import * as types from '../../src/actions/types';
import takeUserNameAndFetchData from '../../src/actions/fetchData';

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

describe('testing fetchData actions', () => {
  afterEach(() => {
    fetchMock.restore();
  });
  test('should pass user name and fetch data', () => {
    fetchMock.getOnce('*', {
      body: [
        { userInfo: {} },
        { userRepos: [] },
      ],
    });

    const expectedActions = [
      { type: types.FETCH_USER_BEGIN },
      { type: types.FETCH_USER_INFO_SUCCESS, payload: { body: { userInfo: {} } } },
      { type: types.FETCH_USER_REPOS_SUCCESS, payload: { body: { userRepos: [] } } },
      { type: types.FETCH_USER_LOADING_END },
    ];
    const store = mockStore({ userInfo: {}, userRepos: [] });
    return store.dispatch(takeUserNameAndFetchData())
      .then(() => {
        const actualActions = store.getActions().map(action => action.type);
        expect(actualActions).toEqual(expectedActions);
      });
  });
});

我真的很困惑要用开玩笑/酵素正确地测试它。

0 个答案:

没有答案