如何在 Jest 测试中匹配包含“/”并给出语法错误的字符串

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

在我的 React 应用程序中,我正在编写一个 Jest 测试来测试我是否在屏幕上获得了特定的日期、时间和时区。

测试看起来是这样

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();
});

测试失败,出现语法错误

 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 |

我不知道如何让它与“/”一起工作,因为它认为是正则表达式部分,但实际上,它是包含在时区字符串中的斜杠。

您需要使用反斜杠(即 \)对正则表达式中的特殊字符(即 /())进行转义。

改为:

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

可以找到转义特殊字符的体面解释 here. The regex can be seen in action here