Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[no-conditional-expect] how to catch errors for testing #866

Closed
dankolesnikov opened this issue Jul 25, 2021 · 2 comments
Closed

[no-conditional-expect] how to catch errors for testing #866

dankolesnikov opened this issue Jul 25, 2021 · 2 comments

Comments

@dankolesnikov
Copy link

Hi everyone,

When I was implementing testing with Jest for Axios, I've noticed that this is regarded as anti pattern:

    try {
      await axios(url);
    } catch (error) {
      expect(error.response.status).toBe(404);
    }

Why is that? We need that because this is the only way to capture the entire error object. And assert on objects within.
Current functionality of Jest for capturing error only allows to see the message of the exception not the entire error object.

@G-Rath
Copy link
Collaborator

G-Rath commented Jul 25, 2021

This is laid out in the docs for no-conditional-expect: It's because Jest only considers a test to have failed if it throws an error.

For example with your code, if await axios(url) is successful, the test will be marked as passing despite having not called expect.
The quickest way to fix the underlying error would be to add a throw in the try:

try {
  await axios(url);
  throw new Error('unexpected success');
} catch(error) {
  expect(error.response.status).toBe(404);
}

However that is still considered a conditional by our rule, which wants you to get the expect out of the catch all together - I outlined a good way of doing this with a wrapper here, which I've distilled into a PR adding this to the docs for no-conditional-expect :)

@G-Rath G-Rath changed the title no-conditional-expect is not correct [no-conditional-expect] how to catch errors for testing Jul 25, 2021
@G-Rath G-Rath closed this as completed Sep 25, 2021
@vitaly-zdanevich
Copy link

@G-Rath If I have throw new Error('unexpected success') like in your example - it must be a valid case, because

  1. It works
  2. Otherwise - more complicated with your wrapper

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants