最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How can I mock window.document for testing DOM-centric JavaScript? - Stack Overflow

programmeradmin1浏览0评论

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 user285879user285879
Add a ment  | 

4 Answers 4

Reset to default 6

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

发布评论

评论列表(0)

  1. 暂无评论