Reputation: 41
When I tried to run the below code for testing my axios request using jest, I'm getting the following warning, even though my tests are passing.
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"
});
}
});
}
The function fetchNoteHandler() is called from componentDidUpdate().
it('should ', (done) => {
let fetchSuccess;
const axiosSpy = jest.spyOn(axios, 'get').mockImplementation(() => {
const thenFn = jest.fn().mockImplementationOnce((onfulfilled) => {
fetchSuccess = onfulfilled;
})
return { then: thenFn }
})
const wrapper = setup({ auth: authUpdatedState }, { location: { search: { id: randomNoteId }}})
expect(axiosSpy).toBeCalledTimes(1);
fetchSuccess(sampleResponse);
done();
});
(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.
How can I handle unhandled promises in this case?
Upvotes: 1
Views: 5170
Reputation: 4643
That's because you don't catch errors in your test nor returned a Promise
. Try it like this:
const axiosSpy = jest.spyOn(axios, 'get').mockImplementationOnce(() =>
Promise.resolve(yourMockData)
);
Upvotes: 2