問題描述
如果滿足兩個期望之一,我需要將測試設置為成功:
I need to set the test to succeed if one of the two expectations is met:
expect(mySpy.mostRecentCall.args[0]).toEqual(jasmine.any(Number));
expect(mySpy.mostRecentCall.args[0]).toEqual(false);
我希望它看起來像這樣:
I expected it to look like this:
expect(mySpy.mostRecentCall.args[0]).toEqual(jasmine.any(Number)).or.toEqual(false);
我在文檔中遺漏了什么還是我必須編寫自己的匹配器?
Is there anything I missed in the docs or do I have to write my own matcher?
推薦答案
注意:此解決方案包含 Jasmine v2.0 之前版本的語法.有關自定義匹配器的更多信息,請參閱:https://jasmine.github.io/2.0/custom_matcher.html
Note: This solution contains syntax for versions prior to Jasmine v2.0. For more information on custom matchers now, see: https://jasmine.github.io/2.0/custom_matcher.html
Matchers.js 僅適用于單個結果修飾符" - not
:
Matchers.js works with a single 'result modifier' only - not
:
核心/Spec.js:
jasmine.Spec.prototype.expect = function(actual) {
var positive = new (this.getMatchersClass_())(this.env, actual, this);
positive.not = new (this.getMatchersClass_())(this.env, actual, this, true);
return positive;
core/Matchers.js:
jasmine.Matchers = function(env, actual, spec, opt_isNot) {
...
this.isNot = opt_isNot || false;
}
...
jasmine.Matchers.matcherFn_ = function(matcherName, matcherFunction) {
return function() {
...
if (this.isNot) {
result = !result;
}
}
}
所以看起來您確實需要編寫自己的匹配器(從 before
或 it
塊中獲取正確的 this
).例如:
So it looks like you indeed need to write your own matcher (from within a before
or it
bloc for correct this
). For example:
this.addMatchers({
toBeAnyOf: function(expecteds) {
var result = false;
for (var i = 0, l = expecteds.length; i < l; i++) {
if (this.actual === expecteds[i]) {
result = true;
break;
}
}
return result;
}
});
這篇關于Jasmine 期望邏輯(期望 A OR B)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!