How can I trick window.document to test DOM-oriented JavaScript?

I'm trying to write some tests that call window.document, and I want to mock the actual calls, so I can run them headless. The following code will not 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 ideas how to mock this?

I use Jasmine and jasmine-maven-plugin if that matters.

+4
source share
4 answers

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

 with ({window: {}}) { ... } 
+6
source

What if you changed your code to use the win window everywhere. Then you can use var win = window; when not testing, and var win = {"document": ""}; when testing.

+1
source

If you do this in some browser, you cannot write through the window. Can you run your tests using a custom variable, not a window?

0
source

If you can put all your code in a single file (for example, with a shell script that calls "cat"), this might 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 global variables will not be true global, but the "window" can be accessed from anywhere inside and will be your own version. Please note that this will violate some designs and make access to things β€œfrom outside” more difficult .... but in many cases it may just work without changing your code.

Edit: add an example of how to access something from an external closing function block

0
source

All Articles