在我使用的所有测试框架中,都有一个可选参数来指定您自己的自定义错误消息。
这可能非常有用,我找不到开箱即用的茉莉花方法。
我有 3 位其他开发人员向我询问过这个确切的功能,当谈到 jasmine 时,我不知道该告诉他们什么。
是否可以在每个断言上指定您自己的自定义错误消息?
在我使用的所有测试框架中,都有一个可选参数来指定您自己的自定义错误消息。
这可能非常有用,我找不到开箱即用的茉莉花方法。
我有 3 位其他开发人员向我询问过这个确切的功能,当谈到 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
如果您查看 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
这个问题.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;
}
}
}
});
});
在.之后链式调用withContext() expect()
例子:
expect(myValue)
.withContext("This message will be printed when the expectation doesn't match")
.toEqual({foo: 'bar'});