user285879
user285879

Reputation:

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 them 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.

Upvotes: 5

Views: 3731

Answers (4)

rob
rob

Reputation: 10119

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

Upvotes: 0

Amnon
Amnon

Reputation: 7772

If you must run the code in a browser, you can wrap your entire code in a with statement:

with ({window: {}}) {
     ...
}

Upvotes: 6

adam0101
adam0101

Reputation: 30995

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.

Upvotes: 1

wajiw
wajiw

Reputation: 12269

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?

Upvotes: 0

Related Questions