The Testing Library already provides methods for querying DOM elements.
This rule aims to disallow DOM traversal using native HTML methods and properties, such as closest
, lastChild
and all that returns another Node element from an HTML tree.
Examples of incorrect code for this rule:
screen.getByText('Submit').closest('button'); // chaining with Testing Library methods
const buttons = screen.getAllByRole('button');
expect(buttons[1].lastChild).toBeInTheDocument();
const buttonText = screen.getByText('Submit');
const button = buttonText.closest('button');
document.getElementById('submit-btn').closest('button');
Examples of correct code for this rule:
const button = screen.getByRole('button');
expect(button).toHaveTextContent('submit');