reactjs - 如果我的 Fetch 成功,为什么会触发捕获?
问题描述
我正在使用组件进行安装的组件测试,它从 api 获取一些数据,
我嘲笑响应是成功的,但仍然触发了 catch 块,我认为它不应该。
我得到这个错误:
TypeError: Network request failed
at XMLHttpRequest.xhr.onerror (C:\Users\jorge\Documents\testingreact\React-Testing-For-Beginners\node_modules\whatwg-fetch\fetch.js:436:16)
这是我的组件:
class MoviesList extends PureComponent {
state = {
movies: [],
};
async componentDidMount() {
try {
const res = await fetch(
'https://api.themoviedb.org/3/discover/movie?api_key=APIKEY&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1',
)
const movies = await res.json();
if (movies.success) {
this.setState({
movies: movies.results,
})
}
} catch (e) {
console.log(e);
}
}
render() {
...stuff
}
然后在我的测试中,我正在模拟结果,并在响应上设置一个属性,调用success
为 true
因此,不应触发 catch 错误,但是正在记录 catch 块中的 console.log。
这是测试:
global.fetch = require('jest-fetch-mock')
afterEach(() => {
cleanup
})
const movies = {
success: true,
results: [
{
id: 'hi1',
title: 'title1',
poster_path: 'gfdsftg'
},
{
id: 'hi2',
title: 'title2',
poster_path: 'gfdsftg'
}
]
}
const movie = movies.results[0]
test('<MoviesList />', async () => {
fetch.mockResponseOnce(JSON.stringify(movies))
const {getByTestId, queryByTestId, getAllByTestId} = render(<MoviesList />)
...some assertions here that all pass
})
为什么会触发 catch 块?
解决方案
推荐阅读
- c++ - 将用户输入传递给类函数的参数的更快方法是什么?
- .htaccess - .htaccess 将地址重定向到没有域后缀的地址
- django - 为什么 Django 的 AuthenticationForm 在错误消息中返回奇怪的 str
- github - Github Copilot 停止工作,解析 extraData 时出错:服务不可用
- c# - 如何在 WPF MVVM 页面中导航
- html - bootstrap 5的导航栏项目alingment
- ruby-on-rails - 如何在 ActiveAdmin 中获取集合的路径
- nginx - 仅当域名具有关键字时,如何从 nginx 提供一组文件
- c++ - 将自定义结构转换为另一个模板类型
- python - 比较第一列的值后乘以不同大小的数据帧