javascript - 处理 http 测试请求中的错误
问题描述
我正在使用 jest 来测试我的代码:
export const getReq = async () => {
let data = '';
await fetch(
'https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits',
)
.then((response) => {
let status = null;
if (response.status === 200) {
status = response.status;
} else {
status = 'error';
}
if (status === 200) {
alert('success');
} else {
data = '';
alert('Error');
}
return response.json();
})
.then((commits) => {
data = commits.map(({ sha }: any) => sha)[0];
});
return data;
};
现在我想测试我的警报中应该出现的情况: alert('Error');
和data = '';
。所以,为此我创建了这个测试:
test('Asynchronous return values error', async() => {
global.alert = jest.fn();
global.fetch = jest.fn().mockResolvedValueOnce({
json: () =>
Promise.reject(new Error('my error')),
status: 401,
});
const result = await getReq();
expect(global.alert).toHaveBeenCalledWith('Error');
expect(global.fetch).toHaveBeenCalledWith(
'https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits',
);
expect(result).toEqual('');
});
但是当我运行测试时,我得到:Error: my error
我的测试不起作用
可能是什么问题以及如何测试我上面描述的东西?
解决方案
推荐阅读
- node.js - Prometheus 不会公开所有收集的指标
- c++ - ListView 的大小调整占用了整个空间,甚至是为状态栏提供的空间
- swift - SPM 缓存不适用于 github 操作,有什么想法吗?
- html - 对齐表格中的左侧项目但在中心
- optimization - 为什么使用不同的方法来优化光流和立体视觉的能量函数?
- python - 从目录中的所有文件中将字符串逐行拆分为变量
- go - How to change redis passwd without downtime
- python - 如果两个列表具有相同的元素,则将这些列表的其他元素相加
- c++ - 矩阵中最有价值的“H”形区域?
- python - 加载保存的模型以恢复训练