2

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.

Bharati
  • 21
  • 1
  • 3

1 Answers1

4

You're running into a warning from the eslint-plugin-jest library. According to that library's documentation for no-conditional-expect, it looks like you will want to use a finally block, maybe something like this:

it(
    "Should reject with with message, User already exists with same email",
    async () => {
        let err;
        try {
            await signupService(userSignupData);
        } catch (e) {
            err = e;
        } finally {
            expect(err).toContain("User already exists");
        }
    }
);
Matthew Souther
  • 876
  • 8
  • 13