Jasmine:如何在我的自定义匹配器中重用其他匹配器

时间:2014-05-06 12:16:26

标签: javascript jasmine

我在Jasmine中编写自定义匹配器(1.3,但问题也适用于2.0),这扩展了内置匹配器的功能。如何使用其他实际值调用内置匹配器?我试图做expect(otherActual).toEqual(expected),但这会返回undefined。

我尝试过的实际代码:

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
  }
}

匹配器是一种特定于Backbone的速记函数,用于检查模型的属性。我注释掉的两条返回行返回undefined。第三个返回工作,但是复制粘贴代码并使用茉莉内部因此容易破坏。

1 个答案:

答案 0 :(得分:0)

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

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

var toEqual = jasmine.matchers.toEqual();
var result = toEqual.compare('foo', 'bar');

在这种情况下,result的值将是;

{
    pass: false
}

因为"foo"不等于"bar"