注意:此解决方案包含 Jasmine v2.0 之前版本的语法。有关自定义匹配器的更多信息,请参阅:https ://jasmine.github.io/2.0/custom_matcher.html
Matchers.js 仅适用于单个“结果修饰符” - 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;
核心/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;
}
}
}
所以看起来你确实需要编写自己的匹配器(从 abefore
或it
bloc 中表示正确this
)。例如:
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;
}
});