2014-05-06 34 views
4

我在Jasmine(1.3,但該問題也適用於2.0)中編寫了自定義匹配器,它擴展了內置匹配器的功能。我怎樣才能調用內置匹配器與另一個實際值?我試過只做expect(otherActual).toEqual(expected),但是這返回undefined。Jasmine:我如何在我的自定義匹配器中重用其他匹配器

實際的代碼,我已經試過:

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

的匹配是一個特定的骨幹,速記功能來檢查模型的屬性。我註釋掉的兩個返回行返回未定義。第三個返回工作,但是複製粘貼代碼,並使用茉莉花內部,所以很容易打破。

回答

0

至少在Jasmine 2.x中,每個註冊匹配器的工廠函數都可以在全局對象jasmine.matchers上找到。

要使用的背後toEqual的功能,你可以寫

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

,並在result這種情況下,此值會;

{ 
    pass: false 
} 

因爲"foo"不等於"bar"

相關問題