[英]Jasmine: Testing a function, being called from a different function using jasmine
我在javascript文件中有一種方法。
function foo() {
setTimeout(function() {
bar.getSomeUrl();
},WAIT_FOR_SOMETIME);
}
現在, getSomeUrl()
實現如下。
var bar = {
getSomeUrl : function(){
window.location.href = 'someUrl';
return;
},
anotherProp : function() {
return bar.getSomeUrl();
}
};
我正在嘗試測試在調用foo()
方法時將調用getSomeUrl()
foo()
方法。
我正在使用茉莉進行測試。 我的茉莉花測試如下:
describe('This tests getSomeUrl()', function() {
it('is called when foo() is called', function(){
spyOn(bar,'getSomeUrl').and.callFake(function(){});
window.foo();
expect(bar.getSomeUrl).toHaveBeenCalled();
});
});
我真的不關心測試getSomeUrl()
內部發生的事情,因為我getSomeUrl()
有單獨的測試。
我要測試的是,當我從某處調用foo()時,會調用getSomeUrl()
。
我有以下問題:
someUrl
。 我沒想到會發生這種情況,因為我想,因為我對bar.getSomeUrl()
有所監視,並且正在返回fake method
因此在我調用window.foo()
時實際上不會調用bar.getSomeUrl()
window.foo()
。 所以我想可能是我應該按以下步驟操作:
Expect(window.foo).toHaveBeenCalled();
這沒有任何意義,因為我正在嘗試測試是否正在調用bar.getSomeUrl()
。
但是,當我這樣做時,測試失敗,並且出現以下錯誤:
Error: Expected a spy, but got Function.
我還認為可能是導致問題的setTimeout
函數,並將foo()
函數更改為:
function foo() {
bar.getSomeUrl();
};
沒有任何改變
我僅使用Jasmine和Javascript已有幾天,並且對工作原理有廣泛的了解。
非常感謝任何建議使該測試通過的建議,以及有關我做錯了什么的指針。
首先, bar.getSomeUrl
應該是一個函數,而不是(無效的)對象
var bar = {
getSomeUrl : function() {
window.location.href = 'someUrl';
return;
},
anotherProp : function() {
return bar.getSomeUrl();
}
};
其次,在測試帶有超時的代碼時,請使用Jasmine Clock 。
describe('This tests getSomeUrl()', function() {
beforeEach(function() {
jasmine.clock().install();
});
afterEach(function() {
jasmine.clock().uninstall();
});
it('is called when foo() is called', function(){
spyOn(bar,'getSomeUrl').and.callFake(function(){});
foo();
expect(bar.getSomeUrl).not.toHaveBeenCalled();
jasmine.clock().tick(WAIT_FOR_SOMETIME);
expect(bar.getSomeUrl).toHaveBeenCalled();
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.