eslint-plugin-jest-dom icon indicating copy to clipboard operation
eslint-plugin-jest-dom copied to clipboard

Potentially wrong linting suggestion in jest-dom/prefer-in-document

Open alessandrocapra opened this issue 2 years ago • 1 comments

  • "eslint-plugin-jest-dom": "^4.0.1",
  • node version: 14.18.0
  • npm version: 8.5.2

Relevant code or config

// Here I know the notification should not be in the document. I tried to use `findByLabelText` and it throws an error,
// so I thought about using `queryByLabelText` to assert that it's correctly null
let notification = screen.queryByLabelText("notification address copied");

// Using expect.toBeDefined() throws an error, despite being suggested by eslint as better solution 
// expect(notification).toBeDefined();

// Need to disable the line to avoid linting errors
expect(notification).toBeNull(); // eslint-disable-line jest-dom/prefer-in-document

What you did:

  • check code and comments above

What happened:

  • I got a linting error suggesting to use toBeInTheDocument to assert existence of a node, but in this case I am using queryByLabelText and therefore I cannot use toBeInTheDocument to assert a null value.

Problem description:

  • Check "What happened" section above

Suggested solution:

  • Do not suggest to use toBeInTheDocument if user is querying with queryBy*

alessandrocapra avatar Mar 17 '22 08:03 alessandrocapra

I think the suggestion is to use toBeInTheDocument with the negation property .not

expect(screen.queryByLabelText("notification address copied")).not.toBeInTheDocument()

Which personally, it reads better than expect(screen.queryByLabelText("notification address copied")).toBeNull()

ricardozv28 avatar Apr 23 '22 05:04 ricardozv28

I just ran into this issue as well and will need to turn this rule off. It doesn't make sense to be asserting that null is not within the document.

expect(null).not.toBeInTheDocument()

twdrake-ap avatar Mar 08 '23 16:03 twdrake-ap

@twdrake-ap sure but the code you've given doesn't make sense anyway - why would you assert that a literal null is not present in the document?

This situation is specifically called out by the docs as when you should use not.toBeInTheDocument, using screen.queryByLabelText.

G-Rath avatar Mar 08 '23 18:03 G-Rath

@G-Rath That is my point, the code snippet is what OP's example would evaluate to if he used this package's default lint rules. Why does it make sense to assert that a query result, that we are expecting to return null, not be in the document instead of asserting that is IS null?

twdrake-ap avatar Mar 08 '23 19:03 twdrake-ap