笑话酶|测试组件函数中的Promise通过但抛出错误

时间:2018-11-11 17:58:46

标签: reactjs promise jestjs

我有一个容器,其中有一个函数,该函数使用fetch发出API请求:

updateBooks = books => this.setState({ books });

getBooks = keyword => fetch(`${googleBooksSearchAPI}${keyword}`)
    .then(response => response.json())
    .then(myJson => this.updateBooks(myJson.items))
    .catch(error => console.log('error', error));

我正在尝试使用fetch-mock为此进行测试:

it('getBooks works', () => {
    const wrapper = shallow(<BookContainer />);
    const mockData = { items: bookListObj };
    fetchMock.get(googleBooksSearchAPI, mockData);

    wrapper.instance().getBooks('dun');
    expect(wrapper.state().books).toEqual(bookListObj);

    fetchMock.restore();
});

所有测试均显示为通过,但仍然可以看到此错误:

console.log app/components/BookContainer.js:20
      error FetchError {
        name: 'FetchError',
        message: 'invalid json response body at undefined reason: Unexpected end of JSON input',
        type: 'invalid-json' }

如果我从提取中删除catch,则会显示以下消息:

(node:5094) UnhandledPromiseRejectionWarning: FetchError: invalid json response body at undefined reason: Unexpected end of JSON input
(node:5094) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:5094) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

如何删除它?

0 个答案:

没有答案