如何测试调用API的redux传奇?

时间:2019-10-04 15:25:24

标签: reactjs redux react-redux

我想测试执行API调用的redux传奇,我听说我可以使用generator.next()值,但它似乎不返回api结果:

saga.ts

import API from 'utils/api';
import {
  all, call, fork, put, takeEvery,
} from 'redux-saga/effects';
import { PeopleActionTypes } from './types';
import { fetchError, fetchSuccess } from './action';

function* handleFetch() {
  try {
    const res = yield call(API.getRequest, 'https://randomuser.me/api/?results=5&inc=gender,email&noinfo');

    if (res.error) {
      yield put(fetchError(res.error));
    } else {
      yield put(fetchSuccess(res));
    }
  } catch (err) {
    if (err instanceof Error && err.stack) {
      yield put(fetchError(err.stack));
    } else {
      yield put(fetchError('An unknown error occured.'));
    }
  }
}

function* watchFetchRequest() {
  yield takeEvery(PeopleActionTypes.FETCH_REQUEST, handleFetch);
}

function* peopleSaga() {
  yield all([fork(watchFetchRequest)]);
}

export default peopleSaga;

saga.test.ts

import peopleSaga from '../../../store/people/saga';

describe('People saga test', () => {
  it('Should fetch a good result', () => {
    const generator = peopleSaga();
    expect(generator.next()).toEqual('ok');
  });
});

我打印确定只是为了看到接收到的结果,它使我得到了这个:

Expected: "ok"
Received: {"done": false, "value": {"@@redux-saga/IO": true, "combinator": true, "payload": [{"@@redux-saga/IO": true, "combinator": false, "payload": {"args": [], "context": null, "fn": [Function watchFetchRequest]}, "type": "FORK"}], "type": "ALL"}}

  4 |   it('Should fetch a good result', () => {
  5 |     const generator = peopleSaga();
> 6 |     expect(generator.next()).toEqual('ok');
    |                              ^
  7 |   });
  8 | });

缺少什么?

0 个答案:

没有答案