Reputation: 819
I have the following code:
loggerManager.js:
export default log(message) {
try {
axios.post(...).catch(error) { console.log(error); }
}catch(error) {
console.log(error);
}
}
loggerManager.test.js:
test('', () => {
jest.spyOn(global.console, 'log');
jest.mock('axios');
axios.post = jest.fn(() => Promise.reject('fail'));
log('message');
expect(console.log).toBeCalledWith('fail'); // The result said it has not been called even once
});
Where am I going wrong?
Upvotes: 0
Views: 1368
Reputation: 1074666
Two issues:
A rejection handler converts rejection into fulfillment if it doesn't throw
or return a promise that is rejected
try
/catch
doesn't catch promise rejections except when the promise is consumed via await
within the try
block
So assuming the normal case, if your axios.post
's promise rejects, the rejection handler runs but the catch
block does not.
In this code:
export default log(message) {
try {
axios.post(...).catch(error) { console.log(error); }
}catch(error) {
console.log(error);
}
}
Execution will only go into the catch
block at the end if:
axios
is an undeclared identifier; oraxios
doesn't have a post
property; oraxios.post
isn't a function; oraxios.post
throws when called; oraxios.post
doesn't return an object with a catch
property; orcatch
property of the object axios.post
returns isn't a function; orcatch
method of the object axios.post
returns throws when calledIt will not be entered if axios.post
returns a promise that is rejected.
You may have wanted this:
export default async log(message) {
// −−−−−−−−−−−−^^^^^
try {
await axios.post(...);
// −^^^^^
}catch(error) {
console.log(error);
}
}
That way, the catch
block will be entered if there was a problem calling axios.post
or if axios.post
returns a promise that is rejected.
Upvotes: 1