gpt4 book ai didi

javascript - 在 Jest 中使用正则表达式和 toHaveProperty()

转载 作者:行者123 更新时间:2023-12-03 01:15:02 24 4
gpt4 key购买 nike

我有一个场景,我的 Promise 因 Error 对象而被拒绝。

throw new Error(`${ISSUE}`);

ISSUE 包含一个公共(public)字符串导致此问题。这方面的一些例子可以是:

ISSUE = 'Node is causing this issue', OR
ISSUE = 'Jest is causing this issue'

为了使用 Jest 测试此场景,我使用 toHaveProperty() 就像:

expect(function()).rejects.toHaveProperty('message',/is causing this issue/);

但它给了我错误说

Comparing two different types of values. Expected regexp but received string.

在此处指定确切的字符串时效果非常好。有什么方法可以使用正则表达式来完成这一轮吗?

我已经尝试过了,虽然这似乎有效,但正在寻找一种更清晰和简化的方法。

return function()
.then()
.catch((e) => {
expect(e.message).toMatch(/is causing this issue/);
});

提前致谢!

最佳答案

您可以使用toMatchObject :

expect(function()).rejects.toMatchObject({
message: expect.stringMatching(/is causing this issue/)
});

这将允许任何具有 message 属性的对象,该属性的值是与给定 RegExp 匹配的字符串。

关于javascript - 在 Jest 中使用正则表达式和 toHaveProperty(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52054707/

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