Reactjs 未处理的PromisejectionWarning:jest
当我尝试使用jest运行下面的代码来测试我的axios请求时,我得到了以下警告,即使我的测试通过了Reactjs 未处理的PromisejectionWarning:jest,reactjs,jestjs,axios,enzyme,Reactjs,Jestjs,Axios,Enzyme,当我尝试使用jest运行下面的代码来测试我的axios请求时,我得到了以下警告,即使我的测试通过了 fetchNoteHandler = async () => { const headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + this.props.idToken } return a
fetchNoteHandler = async () => {
const headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + this.props.idToken
}
return axios.get(`${ROOT_URL}/notes/${this.state.noteId}`, {
headers: headers,
cancelToken: this.source.token
})
.then(response => {
this.setState({
noteId: response.data["noteId"],
heading: response.data["noteHeading"],
note: response.data["noteBody"],
lastUpdated: response.data["lastUpdated"],
fetchingNow: false
});
})
.catch((error) => {
if (!axios.isCancel(error)) {
this.setState({
fetchingNow: false,
error: "Failed to fetch note"
});
}
});
}
从componentDidUpdate()调用函数fetchNoteHandler()
在这种情况下,我如何处理未处理的承诺?这是因为您没有捕获测试中的错误,也没有返回
承诺。试着这样做:
const axiosSpy = jest.spyOn(axios, 'get').mockImplementationOnce(() =>
Promise.resolve(yourMockData)
);
您没有正确地模拟Axios,它不会返回承诺,而是返回一些类似承诺的对象,这些对象没有catch
方法。您没有发布您测试的组件,但它似乎使用了您未提供的catch
。此外,测试将变为异步测试,并且应该使用承诺进行测试,而不是完成。我建议不要重新发明轮子,而是使用一些现有的解决方案来模拟Axios,比如Moxios。@Estus Flask我对如何测试上述函数感到非常困惑。你能为这个写一个示例代码吗?
(node:69127) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'catch' of undefined
(Use `node --trace-warnings ...` to show where the warning was created)
(node:69127) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:69127) [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.
const axiosSpy = jest.spyOn(axios, 'get').mockImplementationOnce(() =>
Promise.resolve(yourMockData)
);