Home > Software design >  How in Jest testing to match a string which contains a "/" and gives a syntax error
How in Jest testing to match a string which contains a "/" and gives a syntax error

Time:09-16

In my React application, I'm writing a Jest testing to test if on screen I get a specific date, time, and timezone.

The test looks as it is

test('Local date time format - Europe no UK', () => {
  const date = '2021-08-26T08:06:14Z';
  const timezone = 'Europe/Berlin';

  render(
    <DateFormatter
      dateTime={date}
      timeZone={timezone}
      variant="localDateTime"
    />,
  );
  expect(screen.getByText(/26 Aug 2021, 8:06 (Europe/Berlin)/)).toBeVisible();
});

The test fails with a syntax error

 Test suite failed to run

    SyntaxError: /Users/jake/Desktop/Trialbee/admin-frontend/src/components/DateFormatter/DateFormatter.spec.js: Invalid regular expression flag (215:54)

      213 |     />,
      214 |   );
    > 215 |   expect(screen.getByText(/26 Aug 2021, 8:06 (Europe/Berlin)/)).toBeVisible();
          |                                                       ^
      216 | });
      217 |

I don't know how to make it work with the '/' as it is thinking is a regEx part but in reality, is a slash that is contained in the timezone string.

CodePudding user response:

You need to escape the special characters (i.e. /, ( and )) in your regular expression with a backslash.

Change it to:

expect(screen.getByText(/26 Aug 2021, 8:06 \(Europe\/Berlin\)\)).toBeVisible();

A decent explanation of escaping special characters can be found here. The regex can be seen in action here.

  • Related