Javascript 茉莉花:我如何在我的自定义匹配器中重用其他匹配器

Javascript 茉莉花:我如何在我的自定义匹配器中重用其他匹配器,javascript,jasmine,Javascript,Jasmine,我正在(1.3,但问题也适用于2.0)中编写一个自定义匹配器,它扩展了内置匹配器的功能。如何使用另一个实际值调用内置匹配器?我试着只做expect(otherActual).toEqual(expected),但这返回未定义 我尝试过的实际代码: var customMatchers = { toHaveAttributes: function (expected) { if(!this.actual) { throw new Error("Test paramete

我正在(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
  }
}

matcher是一个特定于主干网的速记功能,用于检查模型的属性。我注释掉的两个返回行返回未定义。第三个返回有效,但它是复制粘贴代码,并且使用jasmine内部结构,因此容易损坏。

至少在jasmine 2.x中,每个注册匹配器的工厂函数都可以在
jasmine.matchers
全局对象上找到

要利用
toEqual
背后的功能,您可以编写

var toEqual = jasmine.matchers.toEqual();
var result = toEqual.compare('foo', 'bar');
在这种情况下,
result
的值为

{
    pass: false
}
因为
“foo”
不等于
“bar”