gpt4 book ai didi

javascript - 开 Jest ,匹配正则表达式

转载 作者:行者123 更新时间:2023-12-05 00:30:21 29 4
gpt4 key购买 nike

目前我有这个测试:

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: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)
);
});
但我得到一个:
Expected: ArrayContaining [StringMatching /^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/]
Received: ["55:56"]

最佳答案

有一个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

关于javascript - 开 Jest ,匹配正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62957996/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com