Prefer toHaveTextContent over checking element.textContent (jest-dom/prefer-to-have-text-content)

November 8, 2022 ยท View on GitHub

๐Ÿ’ผ This rule is enabled in the โœ… recommended config.

๐Ÿ”ง This rule is automatically fixable by the --fix CLI option.

Please describe the origin of the rule here.

Rule Details

This rule aims to prevent checking of the textContent DOM node attribute in tests and prefer toHaveTextContent instead.

Examples of incorrect code for this rule:

expect(element.textContent).toBe("foo");
expect(container.firstChild.textContent).toBe("foo");
expect(getByText("foo").textContent).toBe("foo");
expect(screen.getByText("foo").textContent).toBe("foo");
expect(element.textContent).toEqual("foo");
expect(element.textContent).toContain("foo");
expect(element.textContent).not.toBe("foo");
expect(element.textContent).not.toContain("foo");

Examples of correct code for this rule:

expect(string).toBe("foo");
expect(element).toHaveTextContent("foo");
expect(container.lastNode).toBe("foo");

When Not To Use It

Don't use this rule if you don't care about the added readability and improvements that toHaveTextContent offers to your expects.

Further Reading