reactjsreact-testing-libraryreact-test-renderer

React testing library getByLabelText -Label with special characters


it('render the field with label having the special characters', () => {
  expect(screen.getByTestId('foo')).toHaveTextContent('About(En)'); // works
  expect(screen.getByLabelText(/About(En)/u)).toBeInTheDocument(); // not working
}); 

The first expect is true, but the second giving error

 Error: Unable to find a label with the text of: /About(En)/u

I want to use getByLabelText instead of getByTestId, becuase getByTestId needs addtional attribute on each field.


Solution

  • You either have to use quotes instead of the regex, or you have to escape the parenthesis in your regex.

    I created a very simple react-app that shows this working. Check App.js/App.test.js

    You can download and run the code: https://github.com/lviviani/so-69195225-poc

    For example:

    it('render the field with label having the special characters', () => {
      render(<App />);
      expect(screen.getByTestId('foo')).toHaveTextContent('About(En)'); // works
      expect(screen.getByLabelText('About(En)')).toBeInTheDocument();
      expect(screen.getByLabelText(/about\(en\)/i)).toBeInTheDocument();
    });