首页 > 解决方案 > 开玩笑,匹配正则表达式

问题描述

目前我有这个测试:

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

什么toHoursMinutes是接收一个 Date 对象并像这样转换它:

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

如果我与 比较,我的本地时间偏移量是-4我的测试通过,但我想在任何地方运行测试,所以我更喜欢将输出与像这样的正则表达式进行比较,检查格式:23:5919:59toHoursMinutes()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)
  );
});

但我得到一个:

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

标签: javascriptdatejestjs

解决方案


有一个toMatch功能expect()可以做到这一点。

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

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

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

expect({
  name: 'Peter Parker',
}).toHaveProperty('name', expect.stringMatching(/peter/i))

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


推荐阅读