如何在redux-saga中测试异步axios请求?

时间:2018-08-19 22:58:35

标签: react-redux axios redux-saga axios-mock-adapter

我有一个形式的传奇:

export function* apiRequest(apiBaseUrl, action) {
  const axiosInst = getAxiosInst(apiBaseUrl);

  try {
    if (!action.serviceName) {
      throw new Error("No service name provided");
    }
    const response = yield call( axiosInst.get, `/${action.serviceName}/foo-api` );

    const data = response.data;

    let resultAction;

    switch (response.status) {
      case 404:
        resultAction = INVALID_ENTITY_REQUESTED;
        break;
      case 200:
        ...
      default:
        throw new Error("Invalid response from server.");
    }
    yield put({ type: resultAction, data });
  } catch (err) {
    yield put({
      type: ERROR,
      error: err.message || "There was an unknown error."
    });
  }
}

export function* watchApiRequest(apiBaseUrl) {
  const boundApiRequest = apiRequest.bind(null, apiBaseUrl);

  yield takeEvery(API_CALL, boundApiRequest);
}

和如下测试:

import { apiRequest } from "../services/apiRequest.js";
import MockAdapter from "axios-mock-adapter";
import { default as axios } from "axios";
import { put } from "redux-saga/effects";
import {
  API_CALL,
  API_SUCCESS
} from "../common/actions.js";

describe("Saga that will run on every api call event", () => {
  const mock = new MockAdapter(axios);

  afterEach(() => {
    mock.reset();
  });

  it("should dispatch the correct event when an API request succeeds", () => {
    mock.onGet().reply(200, { foo: "bar" });

    const generator = apiRequest("", {
      type: API_CALL,
      serviceName: "test"
    });

    generator.next();

    expect(generator.next().value).toMatchObject(
      put({
        type: API_SUCCESS,
        data: { foo: "bar" }
      })
    );
  });
});

这不起作用。我的测试失败,结果如下:

Expected value to match object:
      {"@@redux-saga/IO": true, "PUT": {"action": {"type": "API_SUCCESS"}, "channel": null}}
    Received:
      {"@@redux-saga/IO": true, "PUT": {"action": {"error": "Cannot read property 'data' of undefined", "type": "ERROR"}, "channel": null}}

该代码在实际使用中似乎运行良好,但是当我尝试以这种方式对其进行测试时,似乎无法解决通过Axios异步调用API的承诺。我到处搜索了有关在Axios中测试API调用的一些指导,并看到了一些建议,而不是使用Axios模拟适配器模拟API响应,我应该通过在生成器函数之前调用generator.next({status: 200, data: { foo: "bar" })来响应生成器函数expect(...)子句,但这似乎也不起作用。

我发现关于redux-saga的文档测试有点不透明,我在做什么错了?

1 个答案:

答案 0 :(得分:3)

我想出了答案。这与生成器功能的性质有关。

generator.next()使生成器前进到下一条yield指令;为了进行这样的测试,实际上不需要模拟对API请求的响应,您可以通过将所需的值传递给生成器的next()方法来将响应注入到生成器中。

因此,在上面的测试代码中,有两个对next()的调用。对next()的首次调用将导致传奇提出其API请求。第二个将前进到 next 产量,或者使用put()调度动作,或者在catch块中调度错误。诀窍是,应在对next()

second 调用中提供所需的模拟API响应