How can I mock window.document for testing DOM-centric JavaScript?
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 t开发者_如何学Pythonhem headless. Bu the following code won't work:
window = {"document": ""};
document = window.document;
document.cookie = "";
document.location = {"hostname": "test.myserver.com"}
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.
If 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
精彩评论