This rule raises an issue when a regular expression with the global g flag is used as a matcher in a Testing Library query.

Why is this an issue?

Testing Library queries such as getByText, getByRole, or findByLabelText accept a regular expression as a matcher and test it against the text content or attributes of several candidate DOM nodes while looking for a match.

A regular expression created with the global g flag holds state between calls: it remembers the position of its last match through its lastIndex property. Since Testing Library reuses the same regular expression instance to test multiple nodes, the lastIndex state carries over from one node to the next. Testing Library detects and resets this drift, but only by emitting a warning each time: "To match all elements we had to reset the lastIndex of the RegExp because the global flag is enabled."

The g flag thus produces unnecessary noise with no benefit, since a query only ever needs to know whether the matcher matches a given string once. There is no legitimate reason to keep it on a query matcher, so a flagged case should always be fixed rather than treated as a possible false positive. Remove it and keep any other flags, such as i for case-insensitive matching.

import { screen } from '@testing-library/react';

test('renders a greeting', () => {
  render(<Greeting name="World" />);

  expect(screen.getByText(/hello/gi)).toBeInTheDocument(); // Noncompliant: the "g" flag causes a lastIndex-reset warning on every subsequent match
});
import { screen } from '@testing-library/react';

test('renders a greeting', () => {
  render(<Greeting name="World" />);

  expect(screen.getByText(/hello/i)).toBeInTheDocument();
});

Resources

Documentation