有没有办法在 Jasmine expect()
失败时打印自定义错误消息?
Is there a way to print a custom error message when a Jasmine expect()
fails?
例如,对于端到端测试,我有一组网页,我使用一个测试转到每个 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 团队后来提供的信息是,expect 中有一个未记录的功能 - 您可以包含自定义失败消息并且它可以正常工作:
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() 断言失败时打印消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!