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');
const buttonA = buttons[1]; // getting the element directly from the array
expect(buttonA.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 buttonText = screen.getByRole('button');
expect(buttonText.textContent).toBe('Submit');