如何使用特定的window.location.href在Jasmine中测试window.load()? [英] How to test window.load() in Jasmine with a specific window.location.href?
问题描述
我有以下代码:
window.onload= function() {
var requestData = {
bookId:$('.bookId').text()
};
if(window.location.href.indexOf("/viewbook")!=-1){
$.post("check-book", requestData, function (response) {
if(response == "already saved") {
$('.add-btn').attr('disabled', 'disabled');
}
});
}
};
我正在尝试在Jasmine中编写适当的测试。所以,我有以下代码:
And I am trying to write an appropriate test in Jasmine. So, far I have the following code:
describe("should disable button", function () {
it("should check if book exists in list while loading page", function () {
var localContext = {
"window":{
location:{
href:"/viewbook"
}
}
}
with(localContext){
spyOn($, 'post');
window.load();
expect(window.location.href).toBe("/viewbook");
//expect($.post).toHaveBeenCalled();
}
});
});
但是当我运行它时,它会给我一个错误,即对象不知道加载。你知道如何测试它吗?
But when I run it, it gives me an error that load is not know for an Object. Do you have any idea how this can be tested?
谢谢
推荐答案
你已经用变量 localContext $ c $中定义的副本替换了
窗口
global(我认为这有点危险) C>。该变量没有加载
方法,因此调用它会给出上述错误。
You have replaced the window
global (which I would think is kind of dangerous) with the copy defined in the variable localContext
. That variable does not have a load
method, so calling it gives you the above error.
更好的解决方案将创建一个命名函数并测试其内部,并将该函数分配给 window.onload
,而不是尝试测试分配给全局<$ c $的匿名函数c> window 。
A better solution to would be to create a named function and test its internals, and assign that function to window.onload
, rather than trying to test an anonymous function assigned to the global window
.
ie
function checkBook(){
// Do stuff
}
window.onload = checkBook;
然后您可以经常手动运行 checkBook
如你所愿,你的测试。
You can then manually run checkBook
as often as you want in your tests.
这篇关于如何使用特定的window.location.href在Jasmine中测试window.load()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!