【发布时间】:2013-02-19 00:29:00
【问题描述】:
在我使用的所有测试框架中,都有一个可选参数来指定您自己的自定义错误消息。
这可能非常有用,我找不到开箱即用的 jasmine 方法。
我有 3 位其他开发人员向我询问了这个确切的功能,而谈到 jasmine,我不知道该告诉他们什么。
是否可以在每个断言上指定您自己的自定义错误消息?
【问题讨论】:
标签: javascript unit-testing jasmine
在我使用的所有测试框架中,都有一个可选参数来指定您自己的自定义错误消息。
这可能非常有用,我找不到开箱即用的 jasmine 方法。
我有 3 位其他开发人员向我询问了这个确切的功能,而谈到 jasmine,我不知道该告诉他们什么。
是否可以在每个断言上指定您自己的自定义错误消息?
【问题讨论】:
标签: javascript unit-testing jasmine
Jasmine 已经在所有匹配器(toBe、toContain 等)中支持可选参数,因此您可以使用:
expect(true).toBe(false, 'True should be false').
然后在输出中会如下所示:
Message:
Expected true to be false, 'True should be false'.
提交链接(文档中没有描述): https://github.com/ronanamsterdam/DefinitelyTyped/commit/ff104ed7cc13a3eb2e89f46242c4dbdbbe66665e
【讨论】:
toEqual
如果您查看 jasmine 源代码,您会发现无法从匹配器外部设置消息。例如toBeNaN 匹配器。
/**
* Matcher that compares the actual to NaN.
*/
jasmine.Matchers.prototype.toBeNaN = function() {
this.message = function() {
return [ "Expected " + jasmine.pp(this.actual) + " to be NaN." ];
};
return (this.actual !== this.actual);
};
如您所见,消息被硬编码到匹配器中,并且会在您调用匹配器时设置。我能想到拥有自己的消息的唯一方法是像here 描述的那样编写匹配器
【讨论】:
This issue 正在跟踪使用.because() 机制实现自定义错误消息的兴趣。
与此同时,avrelian 创建了一个不错的库,它使用since() 机制——jasmine-custom-message 实现自定义错误消息。
【讨论】:
是的,可以做到。
您可以在全局范围内定义一个自定义匹配器,覆盖 jasmine 中的错误消息,如下所示:
beforeEach(function () {
jasmine.addMatchers({
toReport: function () {
return {
compare: function (actual, expected, msg) {
var result = {pass: actual == expected};
result.message = msg;
return result;
}
}
}
});
});
【讨论】:
在expect() 之后直接调用withContext()。示例:
expect(myValue)
.withContext("This message will be printed when the expectation doesn't match")
.toEqual({foo: 'bar'});
【讨论】: