1

我有一个容器,其中有一个函数,它使用以下方法发出 API 请求fetch

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从 fetch 中删除它会显示如下消息:

(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.

如何删除它?

4

0 回答 0