如何将自定义消息添加到Jest期望? [英] How to add custom message to Jest expect?

查看:56
本文介绍了如何将自定义消息添加到Jest期望?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

测试案例后的图片:

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

有可能在笑话中吗?

在Chai中,可以使用第二个参数(例如expect(value, 'custom fail message').to.be...),而在Jasmine中,似乎是通过.because子句完成的.但是无法在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
      };
    }
  }
});

然后您可以像这样使用它:

And then you use it like this:

expect(mail).toBeValid(isValid);

注意:toBeValid会返回两种情况(成功和失败)的消息,因为它允许您使用

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆