我用的茉莉,我想測試一個對象是否具有一定的方法還是不行,象下面這樣:茉莉花來測試對象是否具有一定的方法或不
it "should have 'open' method", ->
@xhr = ajax.create()
expect(@xhr).toHaveMethod "open" # I want to test like this!
如何測試?謝謝你的好心。
我用的茉莉,我想測試一個對象是否具有一定的方法還是不行,象下面這樣:茉莉花來測試對象是否具有一定的方法或不
it "should have 'open' method", ->
@xhr = ajax.create()
expect(@xhr).toHaveMethod "open" # I want to test like this!
如何測試?謝謝你的好心。
有沒有內置的方式來做到這一點,但你可以做到這一點,達到預期的效果。
it "should have 'open' method", ->
@xhr = ajax.create()
expect(typeof @xhr.open).toBe("function")
請注意,測試如果它定義爲對方的回答提出了具有一定優勢的情況下它會通過,它不應該。如果你採取以下結構,它會通過,它絕對不是一個功能。
{ open : 1 }
我會嘗試:
it "should have 'open' method", ->
@xhr = ajax.create()
expect(@xhr.open).toBeDefined()
看到這個fiddle。
@david回答正確。 toBeDefined()
可能是你想要的。然而,如果你想驗證它是一個功能,而不是一個屬性,那麼你可以使用toEqual()
與jasmine.any(Function)
。這裏有一個例子:http://jsbin.com/eREYACe/1/edit
我試過這個解決方案,它的工作原理:
spyOn(@xhr,"open")
如果沒有功能打開,它會拋出錯誤,因爲它不能在它
茉莉花啓動spyig允許您編寫自己的「匹配器」。文檔解釋它。 http://jasmine.github.io/2.0/custom_matcher.html
你可以寫那個叫
expect(obj).toHaveMethod("methodName");
個人而言,我會寫一些更通用,檢查值類型非常具體的匹配。這樣我就可以用它來檢查一個方法是否定義在對象/實例上,但是可以存儲一個值。它還使我可以檢查除功能類型之外的類型。
expect(obj.methodName).toBeA(Function);
爲了得到它的工作,你必須確保添加toBeA「匹配器」。
beforeEach(function(){
jasmine.addMatchers({
toBeA: toBeA
});
});
function toBeA() {
return {
compare: function (value, type) {
var result = {pass: val != null && val.constructor === type || val instanceof type};
if (result.pass) {
result.message = 'Expected ' + value + ' to be a ' + type.name
} else {
result.message = 'Expected ' + value + ' to not be a ' + type.name
}
return result;
}
};
}
我是這樣做的。角例如:
beforeEach(inject(function ($injector) {
service = $injector.get("myService");
}));
it("should have myfunction function", function() {
expect(angular.isFunction(service.myfunction)).toBe(true);
});
這種解決方案的問題是,如果預期失敗,消息會像'預期不確定要function',這是不是所有的幫助。像'預期對象'@xhr'有財產'打開'會更好。 – Jorn 2015-07-21 11:19:01