mocking - 使用 axios 拦截器模拟 axios
问题描述
我正在尝试使用 mockAxios 来测试 axios 拦截器。
export default {
get: jest.fn(() => Promise.resolve({ data: {} }))
}
import axios from 'axios';
export const configurateAxios = () => {
axios.interceptors.response.use(
response => {
return response;
},
error => {
return Promise.reject(error);
}
);
}
当我创建 mockAxios 时:
export default {
get: jest.fn(() => Promise.resolve(data: {}))
}
我的所有测试都失败并显示以下消息:无法读取 axios 拦截器内部未定义的属性响应。发生这种情况是因为模拟 axios 不返回响应。它可以只返回一个普通对象。
那么如何使用 axios 拦截器和 mockAxios 进行测试呢?
解决方案
这就是我实现的方式
拦截器.js
/* Module that I want to test
* Intercepts every axios request and redirects to login on 401
*/
import axios from 'axios';
export default () => {
axios.interceptors.response.use(
response => {
// Return a successful response back to the calling service
return response;
},
error => {
// Return any error which is not due to authentication back to the calling service
if (error.response.status !== 401) {
return new Promise((resolve, reject) => {
reject(error);
});
} else {
window.location.href = '/operator-portal/login';
return false;
}
}
);
};
拦截器.test.js
import axios from 'axios';
import interceptor from '../../src/apis/interceptor';
jest.mock('axios');
describe('interceptor', () => {
it('redirects to login route when response status is 401', () => {
delete global.window.location;
global.window = Object.create(window);
Object.defineProperty(window, 'location', {
value: {
href: 'url'
}
});
axios.interceptors.response.use = jest.fn((successCb, failCb) => {
failCb({
response: {
status: 401
}
});
});
interceptor();
expect(window.location.href).toEqual('/login');
});
it('redirects to login route when success handler is called', () => {
axios.interceptors.response.use = jest.fn(successCb => {
successCb();
});
interceptor();
window.location.href = 'url';
expect(window.location.href).toEqual('url');
});
});
推荐阅读
- node.js - docker-compose up:致命:数据库“样板”不存在(Postgres 节点)
- python - 计算字符串中的空格
- r - 如果“实验室(填充=)”不起作用,如何更改 ggplot2 中的图例标题?
- sql - 字符集和国家字符集oracle之间的区别?
- r - 使用刚刚在 data.table 中创建的变量的值
- react-native - withTheme 不是函数反应本机错误
- android - 如何更改 Gradle 脚本中的名称,上面写着 nestoruk_47554 但我需要用我的来更改它
- redis - 用于检查和打印数字是偶数还是奇数的 Lua 代码
- python - 如何将我的 auto ml python 客户端连接到我的应用程序以进行推理?
- flutter - Flutter for web 有没有办法在滚动时隐藏 ios safari 的 url 栏和底部导航栏