在expect()断言失败时打印消息 [英] Print message on expect() assert failure

查看:554
本文介绍了在expect()断言失败时打印消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当Jasmine expect()失败时,有没有办法打印自定义错误消息?

Is there a way to print a custom error message when a Jasmine expect() fails?

As例如,对于端到端测试,我有一个网页数组,我使用一个测试来转到每个URL并断言每个页面上存在一个元素。我知道我可以将每个 expect()放入一个单独的测试中,但我宁愿遍历数组并在失败时记录页面URL。

As an example, for end to end testing I have an array of web pages and I use one test to go to each URL and assert an element exists on each page. I know I can put every expect() into a separate test, but I'd rather iterate through the array and log the page URL on failure.

推荐答案

更新

我明白了人们仍然在发现这一点。来自Jasmine团队的后来信息是,期望有一个未记录的功能 - 您可以包含自定义失败消息,它只是有效:

I see people still are finding this. Later information from the Jasmine team is that there is an undocumented feature on the expect - you can include a custom failure message and it just works:

expect( fields[i].element.exists() ).toEqual(true, field[i].name + ' is expected to exist');

这正是我原本想要的。

原始答案如下

我今天一直在寻找这个,并在此发表评论: https://github.com/adobe/brackets/issues/2752

I've been looking for exactly this today, and put a comment here: https://github.com/adobe/brackets/issues/2752

已讨论的语法是Jasmine的扩展,允许添加因为 - 所以你可以写:

The syntax that has been discussed is an extension to Jasmine to permit a because to be added - so you'd be able to write:

expect( fields[i].element.exists() ).toEqual(true).because( field[i].name + 'is expected to exist');

这几年后仍在讨论中,可能无法实现。我发现这样做的另一种方法是创建自定义匹配器。一般来说,我认为我不鼓励自定义匹配器,但不确定你是否覆盖了它的所有基础,但在这种情况下,我们确实检查了一个真/假值,所以匹配器并不太可怕。

That is still being discussed after a few years, and may not come to fruition. Another way that I've found to do this is to create a custom matcher. In general I think I'd discourage a custom matcher without being sure you're covering all the bases with it, but in this case we're really checking a true/false value, so the matcher isn't too scary.

我们可以使用beforeEach创建自定义匹配器:

We can create the custom matcher with a beforeEach:

beforeEach(function() {
  var matchers = {
    toEqualBecause: function( value, message ) {
      this.message = function() {
        return "Expected '" + this.actual + "' to equal '" + value + "' because " + message;  
      };

      return this.actual == value;  
    }
 };

  this.addMatchers(matchers);
});

然后,我们可以使用此匹配器发送包含我们失败的消息:

We can then use this matcher to put a message with our failures as such:

expect( field[i].element.exists() ).toEqualBecause( true, field[i].name );

这将输出一个包括字段名称的失败输出:

Which will give a failure output including the field name as such:

Expected 'false' to equal 'true' because account_name

这篇关于在expect()断言失败时打印消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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