单元测试React Saga观察者和工人

时间:2017-09-07 09:07:11

标签: reactjs unit-testing mocha react-redux redux-saga

我想使用mocha和chai对以下观察者和工作人员进行单元测试。有人可以在这帮忙吗?

我确实写了一些单元测试用例,但它没有按预期工作

例如

import { expect } from "chai";
import { take, call } from "redux-saga/effects";

import * as actions from "client/actions";
import { watchGetFavorites } from "client/sagas/watchers/favorite-watcher";
import { fetchFavorites } from "client/sagas/workers/favorite-worker";

describe("favorite-watcher saga", () => {
  const generator = watchGetFavorites();
  it("it should execute watchGetFavorites", () => {
    expect(generator.next().value).to.deep.equal(take(actions.GET_FAVORITES));
  });
  it("it should execute watchGetFavorites api", () => {
    const data = {
      "loadAction": {
        type: actions.GET_FAVORITES,
        "payload": {
          "userId": "id"
        }
      }
    };
    const apiCall = generator.next(data);
    expect(apiCall).to.deep.equal(call(fetchFavorites, data));
  });
});

第一个测试用例正在通过,但是第二个测试用例失败了,我也想知道如何测试整个观察者,以便它也可以覆盖工作人员代码。

RootSaga

import {fork} from "redux-saga/effects";
import * as favoriteWatcher from "./watchers/favorite-watcher";

export default function *rootSaga() {
  yield [
    fork(favoriteWatcher.watchGetFavorites)
  ];
}

观察

import {take, call, takeEvery} from "redux-saga/effects";
import * as actions from "../../actions/index";
import * as workers from "../workers/favorite-worker";

export function* watchGetFavorites() {
  const loadAction = yield take(actions.GET_FAVORITES);
  yield call(workers.fetchFavorites, loadAction.payload);
}

export function* watchDeleteFavorites() {
  yield takeEvery(actions.DELETE_FAVORITE, function*(loadAction) {
    yield call(workers.deleteFavorites, loadAction.payload);
  });
}

工人

export function* fetchFavorites(payload) {// eslint-disable-line
  try {
    const response = yield call(fetchForJson, `${config.API.favoritesListURL}/${payload.userId}`); //api call
    yield put({//dispatch
      type: actions.GET_FAVORITES_SUCCESS,
      result: response.result,
      fetching: false
    });
  } catch (error) {
    yield put({
      type: actions.GET_FAVORITES_ERROR,
      result: error,
      fetching: false
    });
  }
}

export function* deleteFavorites(payload) {
  try {
    const response = yield call(deleteJson, `${config.API.deleteFavoriteURL}/${payload.userId}`, payload); //api call
    yield put({//dispatch
      type: actions.DELETE_FAVORITE_SUCCESS,
      result: response.result,
      fetching: false
    });
  } catch (error) {
    yield put({
      type: actions.DELETE_FAVORITE_ERROR,
      result: error,
      fetching: false
    });
  }
}

任何真正有用的帮助。

0 个答案:

没有答案