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:
import { screen } from '@testing-library/react';
screen.getByText('Submit').closest('button'); // chaining with Testing Library methods
import { screen } from '@testing-library/react';
const buttons = screen.getAllByRole('button');
expect(buttons[1].lastChild).toBeInTheDocument();
import { screen } from '@testing-library/react';
const buttonText = screen.getByText('Submit');
const button = buttonText.closest('button');
Examples of correct code for this rule:
import { screen } from '@testing-library/react';
const button = screen.getByRole('button');
expect(button).toHaveTextContent('submit');
import { render, within } from '@testing-library/react';
const { getByLabelText } = render(<MyComponent />);
const signinModal = getByLabelText('Sign In');
within(signinModal).getByPlaceholderText('Username');
// If is not importing a testing-library package
document.getElementById('submit-btn').closest('button');