Won*_*nko 5 javascript jasmine
我正在Jasmine中编写一个自定义匹配器(1.3,但问题也适用于 2.0),它扩展了内置匹配器的功能。如何使用另一个实际值调用内置匹配器?我尝试这样做expect(otherActual).toEqual(expected),但这返回未定义。
我尝试过的实际代码:
var customMatchers = {
toHaveAttributes: function (expected) {
if(!this.actual) {
throw new Error("Test parameter is " + this.actual);
}
if(!(this.actual instanceof Backbone.Model)) {
throw new Error("Test parameter must be a Backbone Model");
}
var notText = this.isNot ? " not" : "";
var actualAttrs = this.actual.attributes;
this.message = function () {
return "Expected model to" + notText + " have attributes " + jasmine.pp(expected) +
", but was " + jasmine.pp(actualAttrs);
};
// return expect(actualAttrs).toEqual(expected); // Returns undefined
// return this.env.currentSpec.expect(actualAttrs).toEqual(expected); // Also returns undefined
return this.env.equals_(actualAttrs, expected); // Works, but copied from jasmine.Matchers.prototype.toEqual
}
}
Run Code Online (Sandbox Code Playgroud)
匹配器是一个特定于 Backbone 的速记函数,用于检查模型的属性。我注释掉的两条返回线返回未定义。第三个返回可以工作,但是是复制粘贴代码并使用 jasmine 内部结构,因此很容易损坏。
至少在 Jasmine 2.x 中,每个注册匹配器的工厂函数都可以在jasmine.matchers全局对象上找到。
要利用背后的功能,toEqual您可以编写
var toEqual = jasmine.matchers.toEqual();
var result = toEqual.compare('foo', 'bar');
Run Code Online (Sandbox Code Playgroud)
在这种情况下,resulthere 的值将是;
{
pass: false
}
Run Code Online (Sandbox Code Playgroud)
因为"foo"不等于"bar"。
| 归档时间: |
|
| 查看次数: |
534 次 |
| 最近记录: |