我有一个形式的传奇:
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 文档有点不透明,我做错了什么?