【发布时间】:2021-10-02 19:59:21
【问题描述】:
我在一个文件中有一些测试,
我用一些案例检查了我的减速器
我的代码是这样的
my code
import axiosInstance from '~/utils/network';
const fetcher = axiosInstance();
const fetchMiddleware = () => {
switch (type) {
case 'LOGOUT':{
try {
await fetcher.get(API.GET.LOGOUT_OPERATION);
dispatch({ type: 'LOGOUT_SUCCESS' });
} catch (err) {
dispatch({ type: 'LOGOUT_FAIL' });
}
});
}
}
}
my test
import axiosInstance from '../../src/utils/network';
import configureStore from 'redux-mock-store';
const middlewares = [fetchMiddleware, thunk];
const mockStore = configureStore(middlewares);
const store = mockStore(getInitialReducerState());
jest.mock('../../src/utils/network', () => {
const axiosInstance = jest.fn().mockImplementation(() => {
return {
get: jest.fn().mockImplementation(() => {
return {
headers: {},
};
}),
};
}) as any;
axiosInstance.configure = jest.fn();
return axiosInstance;
});
describe('test LOGOUT', () => {
beforeEach(() => {
store.clearActions();
});
it('should test be success', async () => {
await store.dispatch({
type: 'LOGOUT',
payload: { userName: 'testUserName' },
});
expect(store.getActions()).toContainEqual({
type: 'LOGOUT_SUCCESS',
});
});
it('should test be fail', async () => {
(axiosInstance as jest.Mock).mockImplementation(() => {
return {
get: jest.fn().mockImplementation(() => {
throw new Error(' ');
}),
};
});
await store.dispatch({
type: 'LOGOUT',
payload: { userName: 'testUserName' },
});
expect(store.getActions()).toContainEqual({
type: 'LOGOUT_FAIL',
});
});
});
我想测试两个场景:成功和失败,
我模拟了axiosInstance 函数。
但即使我在第二个测试中覆盖了模拟,我也得到了第一个模拟,因为我的代码只加载了一次 axiosInstance。
我能做什么?
【问题讨论】:
-
在评论和答案之间来回切换。确定这绝对是评论。如果您还没有,我强烈建议您使用moxios。减少您自己需要维护的手动模拟代码。好的文档,设置应该很容易。
-
fetchMiddleware是如何使用的?
-
@RazLuvaton 更新了我的代码
标签: javascript reactjs unit-testing testing jestjs