首页 > 解决方案 > 如果我的 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 块?

标签: reactjsjestjsreact-testing-library

解决方案


推荐阅读