我正在尝试测试具有api调用的saga函数。但是,我认为我在预期值和接收值不同的地方犯了一个错误或错误。 预期:是数据和正确的操作类型 收到:失败操作类型错误。 请参考我的saga和saga.test的图片和代码。 如果有人可以提供帮助并指导我使用api调用测试传奇的正确方法,我将不胜感激。
Saga.js
import { failure, loadBrowseLocationsSuccess, loadBrowseClassificationsSuccess } from "./actions";
import ApiConstants, * as actionTypes from "./constants";
import { all, put, takeLatest, call } from "redux-saga/effects";
import ApiService from "../../services/api_service";
export default function* rootSalarySaga() {
yield all([
takeLatest(actionTypes.LOAD_BROWSE_LOCATIONS_CLASSIFICATION, loadBrowseLocationsClassificationsData),
]);
}
export function* loadBrowseLocationsClassificationsData() {
const requestUrl = ApiConstants.BROWSE_LOCATIONS_CLASSIFICATIONS_URL;
const res = yield ApiService.Get(requestUrl);
if (res.status === 200) {
yield put(loadBrowseLocationsSuccess(res.data[locations]));
yield put(loadBrowseClassificationsSuccess(res.data[classifications]));
} else {
yield put(failure(res.data));
}
}
Saga.test
import { put, call } from "redux-saga/effects";
import { loadBrowseLocationsClassificationsData } from "../saga";
import ApiService from "../../../services/api_service";
import ApiConstants, * as actionTypes from "../constants";
import { failure, loadBrowseLocationsSuccess, loadBrowseClassificationsSuccess } from "../actions";
describe("saga testing for browse container", () => {
it("should dispatch action LOAD_BROWSE_LOCATIONS_SUCCESS with results from loadBrowseLocationsClassificationsData", () => {
const generator = loadBrowseLocationsClassificationsData();
const requestUrl = ApiConstants.BROWSE_LOCATIONS_CLASSIFICATIONS_URL;
const response = { data: { results: "mockData" } };
expect(generator.next().value).toEqual(ApiService.Get(requestUrl));
expect(generator.next(response).value).toEqual(put(loadBrowseLocationsSuccess("mockData")));
expect(generator.next(response).value).toEqual(put(loadBrowseClassificationsSuccess("mockData")));
expect(generator.next()).toEqual({ done: true, value: undefined });
});
});
对于api_service.get函数来说只是一个axios函数。
import axios from "axios";
class ApiService {
static Get(requestUrl) {
return axios
.get(requestUrl)
.then((response) => {
return response;
})
.catch((error) => {
return error.response;
});
}
}
export default ApiService;