如何向 Jest 期望添加自定义消息? [英] How to add custom message to Jest expect?
问题描述
测试用例后的图像:
it('valid emails checks', () => {
['abc@y.com', 'a@b.nz'/*, ...*/].map(mail => {
expect(isValid(mail)).toBe(true);
});
});
我想为每封电子邮件添加自动生成的消息,例如 Email 'f@f.com' should be valid
以便很容易找到失败的测试用例.
I would like to add auto-generated message for each email like Email 'f@f.com' should be valid
so that it's easy to find failing test cases.
类似于:
// .map(email =>
expect(isValid(email), `Email ${email} should be valid`).toBe(true);
是否可以在 Jest 中使用?
Is it possible in Jest ?
在 Chai 中可以使用第二个参数,如 expect(value, 'custom fail message').to.be...
而在 Jasmine 中似乎是用 完成的.因为
子句.但是在 Jest 中找不到解决方案.
In Chai it was possible to do with second parameter like expect(value, 'custom fail message').to.be...
and in Jasmine seems like it's done with .because
clause. But cannot find solution in Jest.
推荐答案
我认为提供这样的信息是不可能的.但是您可以定义自己的匹配器.
I don't think it's possible to provide a message like that. But you could define your own matcher.
例如,您可以创建一个 toBeValid(validator)
匹配器:
For example you could create a toBeValid(validator)
matcher:
expect.extend({
toBeValid(received, validator) {
if (validator(received)) {
return {
message: () => `Email ${received} should NOT be valid`,
pass: true
};
} else {
return {
message: () => `Email ${received} should be valid`,
pass: false
};
}
}
});
然后你像这样使用它:
expect(mail).toBeValid(isValid);
注意:toBeValid
为两种情况(成功和失败)返回一条消息,因为它允许您使用 .not
.测试将失败并显示相应的消息,具体取决于您是否希望它通过验证.
Note: toBeValid
returns a message for both cases (success and failure), because it allows you to use .not
. The test will fail with the corresponding message depending on whether you want it to pass the validation.
expect(mail).toBeValid(isValid);
// pass === true: Test passes
// pass === false: Failure: Email ... should be valid
expect(mail).not.toBeValid(isValid);
// pass === true: Failure: Email ... should NOT be valid
// pass === false: Test passes
这篇关于如何向 Jest 期望添加自定义消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!