javascript - 开玩笑,匹配正则表达式
问题描述
目前我有这个测试:
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
推荐阅读
- python - 美丽的汤 get_text() 适用于 jupyter notebook 和 cmd 但不适用于 Pycharm/Heroku?
- visual-studio - Visual Studio 2019:由于单击“运行”按钮而发生构建时未触发构建后事件
- python - deamon celery 无法启动“未找到模块 blah”或“ImportError:尝试相对导入而没有已知的父包”
- java - 由于行分隔符,Java 测试用例失败
- ios - 从 Assets.xcassets 文件夹调用资产
- scala - 我们如何组合来自相同 data_type 的数据帧的两列的值并获取每个元素的计数?
- python-3.x - 错误 cp: cannot stat 'ssh': No such file or directory
- mysql - 将数据推送到 mysql 后,列类型(在 DB 中)变为默认值
- python - 检查 Ansible 版本(ansible --version)但出现以下错误
- javascript - Firebase 云消息传递前台通知在 Vue 中不起作用