开玩笑,匹配正则表达式

pmi*_*nda 18 javascript date jestjs

目前我有这个测试:

import toHoursMinutes from '../../../app/utils/toHoursMinutes';

describe('app.utils.toHoursMinutes', () => {
  it('should remove 3rd group of a time string from date object', async () => {
    expect(toHoursMinutes(new Date('2020-07-11T23:59:58.000Z'))).toBe('19:59');
  });
});
Run Code Online (Sandbox Code Playgroud)

所做toHoursMinutes的就是接收一个 Date 对象并像这样转换它:

export default (date) => `${('' + date.getHours()).padStart(2, '0')}:${('' + date.getMinutes()).padStart(2, '0')}`;
Run Code Online (Sandbox Code Playgroud)

我的本地时间偏移量是-4这样,如果我23:59与进行比较19:59,我的测试通过就可以了,但我想在任何地方运行测试,所以我更喜欢将 的输出toHoursMinutes()与像这样的正则表达式表达式进行比较,检查hh:mm格式:^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$

但是如何使用正则表达式来比较显式字符串呢?

我试过这个:

const expected = [
  expect.stringMatching(/^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/)
];
it.only('matches even if received contains additional elements', () => {
  expect(['55:56']).toEqual(
    expect.arrayContaining(expected)
  );
});
Run Code Online (Sandbox Code Playgroud)

但我得到一个:

Expected: ArrayContaining [StringMatching /^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/]
Received: ["55:56"]
Run Code Online (Sandbox Code Playgroud)

swi*_*ynx 34

有一个toMatch函数expect()可以做到这一点。

expect('12:59').toMatch(/^\d{1,2}:\d{2}$/); // stripped-down regex
Run Code Online (Sandbox Code Playgroud)

https://jestjs.io/docs/expect#tomatchregexp--string

如果您想匹配其他 jest 函数内的正则表达式,您可以使用expect.stringMatching(/regex/).

expect({
  name: 'Peter Parker',
}).toHaveProperty('name', expect.stringMatching(/peter/i))
Run Code Online (Sandbox Code Playgroud)

https://jestjs.io/docs/expect#expectstringmatchingstring--regexp