I'm trying to test an async code with a negative case when the response is rejected.
As per the docs, we can use try, catch with async await while trying to implement mock rejection https://jestjs.io/docs/tutorial-async
// Or using async/await.
it('tests error with async/await', async () => {
expect.assertions(1);
try {
await user.getUserName(1);
} catch (e) {
expect(e).toEqual({
error: 'User with 1 not found.',
});
}
});
I tried to do the same by implementing mock rejected value. But, I'm getting the following error: Avoid calling 'expect' conditionally
. I've also added expect.assertions(), and the error remains.
I know that there's an eslintjest/no-conditional-expect that can be enabled, but that's a bad practice I don't want to follow.
My implementation
it("Should reject with with message, User already exists with same email", async () => {
expect.assertions(1);
try {
await signupService(userSignupData);
} catch (e) {
expect(e).toContain("User already exists");
}
});
Any help is appreciated. Thanks!
P.S. I saw a similar question but there was no solution.