admin 管理员组文章数量: 1086019
I am trying to write some tests that call window.document, and I want to mock out the actual calls themselves, so I can run them headless. Bu the following code won't work:
window = {"document": ""};
document = window.document;
document.cookie = "";
document.location = {"hostname": "test.myserver"}
I get the following error:
TypeError: Cannot set property window that has only a getter. in file:...
Does anyone have any idea how to mock this out?
I am using Jasmine, and the jasmine-maven-plugin if that makes any difference.
I am trying to write some tests that call window.document, and I want to mock out the actual calls themselves, so I can run them headless. Bu the following code won't work:
window = {"document": ""};
document = window.document;
document.cookie = "";
document.location = {"hostname": "test.myserver."}
I get the following error:
TypeError: Cannot set property window that has only a getter. in file:...
Does anyone have any idea how to mock this out?
I am using Jasmine, and the jasmine-maven-plugin if that makes any difference.
Share Improve this question asked Nov 16, 2010 at 21:07 user285879user2858794 Answers
Reset to default 6If you must run the code in a browser, you can wrap your entire code in a with
statement:
with ({window: {}}) {
...
}
What if you changed your code to use win everywhere window is used. Then you could use var win = window;
when not testing and var win = {"document": ""};
when testing.
If you're doing that in something browser-based you won't be able to write over window. Can you do your tests by using a custom variable as opposed to window?
If you can put all your code into a single file (say, with a shell script which calls "cat"), this may work:
window.realWindow = window;
(function(){
var window = {document: {something: "hi!"}};
var document = window.document;
///////////////////////////////////
// your code goes here, for example:
function test (foo) {
alert (document.something + " " + foo);
realWindow.document.title = foo;
}
test("from inside");
// to make the function "test" reachable from the outside
realWindow.global_test = test;
///////////////////////////////////
})();
global_test("from outside");
Now your globals won't be true globals, but "window" can be accessed from anywhere within, and will be your own version. Note that this will break some constructs, and will make it harder to get to things "from the outside"....but in many cases it might just work with no alteration to your code.
Edit: add example of how to access something from outside the enclosing function block
本文标签: How can I mock windowdocument for testing DOMcentric JavaScriptStack Overflow
版权声明:本文标题:How can I mock window.document for testing DOM-centric JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1743986402a2513933.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论