可观察的史诗没有运行服务调用

时间:2018-04-19 17:24:45

标签: rxjs rxjs5 redux-observable

我尝试按照文档中的示例来测试史诗:

史诗

import { ofType } from 'redux-observable';
import { combineEpics } from 'redux-observable';
import 'rxjs/add/operator/takeUntil';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { switchMap } from 'rxjs/add/operator/switchMap';
import { from } from 'rxjs/observable/from';
import { of } from 'rxjs/observable/of';
import { fromPromise } from 'rxjs/observable/fromPromise';

import { 
  getTopStories
} from '../../../utils/service-helper';

import { type, actions } from './action';

export const getHackernewsStoryEpic = (action$, store) => 
  action$.ofType(type.GET_HACKERNEWS_STORIES_REQUEST)
          .switchMap(
            action =>  { 
              return from(getTopStories())
                        .takeUntil(action$.ofType(type.GET_HACKERNEWS_STORIES_REQUEST_CANCEL))
                        .map(result => actions.getHackernewsStoriesRequestSuccess(result))
                        .catch((error) => actions.getHackernewsStoriesRequestFailure(error))
            }
        );

export default combineEpics(
  getHackernewsStoryEpic
);

获取 getTopStories 是与hackernews API对话的服务电话:

export const getTopStories = async () => await getRequest('/topstories.json');

我的测试看起来像这样:

describe('Hackernews stories epic', () => {
  describe('getHackernewsStoryEpic', () => {
    let store;

    beforeEach(() => {
      store = mockStore();
    });

    afterEach(() => {
      nock.cleanAll();
      epicMiddleware.replaceEpic(storiesEpic);
    });
    it('should return success on request success', async () => {
      store.dispatch({ type: type.GET_HACKERNEWS_STORIES_REQUEST });
      expect(store.getActions()).toEqual([
        { type: type.GET_HACKERNEWS_STORIES_REQUEST },
        { type: type.GET_HACKERNEWS_STORIES_SUCCESS }
      ]);
    });
  });
});

查看测试失败,因为一个动作是触发器, getTopStories()永远不会触发(nock不抱怨没有模拟)并且没有得到下一个动作。我想我错过了应该运行异步调用的东西吗?

1 个答案:

答案 0 :(得分:0)

 it('should return success on request success',  async () => {
      const mock = require('../../../../data/hackernews/topstories.json');

      nock(__ROOT_API__)
        .defaultReplyHeaders({ 'access-control-allow-origin': '*' })
        .get('/topstories.json')
        .reply(200, mock);

        const action$ = ActionsObservable.of(
          {type: type.GET_HACKERNEWS_STORIES_REQUEST}
        );
        const expectedAction = [actions.getHackernewsStoriesRequestSuccess(mock)]
        await getHackernewsStoryEpic(action$)
          .toArray()
          .toPromise()
          .then(actualOutputActions => {
             expect(actualOutputActions).toEqual(expectedAction)
        });
    });