我如何使用配置头为axios编写一个笑话单元测试。
我已将所有api请求调用移至redux中间件,并且现在需要创建单元测试。在使用axios(config)模拟axios请求调用时遇到了问题。有模拟axios请求的正确方法吗?
我的api中间件
const apiMiddleware = ({ dispatch, getState }) => next => action => {
if (action.type !== API) {
return next(action);
}
const {
apiEndPoint,
method,
data,
onSuccess,
onFailure,
label
} = action.payload;
const url = API_URL + apiEndPoint;
const accessToken = getState().user.info.token;
const headers = {};
headers["Content-Type"] = "application/json";
headers["Authorization"] = "Bearer " + accessToken;
dispatch(fetchStarted());
axios({
method,
url,
data,
headers,
responseType: "json",
timeout: 5000
})
.then(response => {
const { isError, message } = response.data;
isError ? onFailure() : onSuccess();
if (message) ToastMessage(message);
dispatch(fetchSuccess(message || ""));
})
.catch(error => {
dispatch(fetchFailed("Error Message"));
ToastMessage(errorMessage);
});
};
export default apiMiddleware;
我的测试
import apiMiddleware from "../api-middleware";
import configureStore from "redux-mock-store";
import axios from 'axios';
import {FETCH_SUCCESS,API} from "../../actions/actionTypes";
jest.mock('axios');
axios.mockResolvedValue();
const mockStore = configureStore([]);
describe("apiMiddleware", () => {
let next,
dispatch,
getState,
middleware,
ToastMessage,
dispatchCalls,
nextCalls,
ToastMessageCalls;
beforeEach(() => {
next = jest.fn();
dispatch = jest.fn();
ToastMessage = jest.fn();
const state = {
user: { info: { token: "dummyToken" } }
};
getState = mockStore(state).getState;
dispatchCalls = dispatch.mock.calls;
nextCalls = next.mock.calls;
ToastMessageCalls = ToastMessage.mock.calls;
middleware = apiMiddleware({ dispatch, getState })(next);
});
it("should dispatch FETCH_SUCCESS", () => {
const method = "POST",
url = "app.json",
data = { "data": "dsa" },
headers = {},
responseType = "json",
timeout = 5000;
return axios({
method,
url,
data,
headers,
responseType,
timeout
}).then(() => {
expect(dispatchCalls[1]).toEqual([{ type: FETCH_SUCCESS }]);
});
});
});