Set location.hash and location.href using JSDom

I configure some tests using JSDom , where I need the global variables window and document , and also need to pass different URL / href for each test. How to set location.hash and location.href properties?

 global.document = jsdom({url: 'http://localhost?something=not#test', 'html': ''}); global.window = document.defaultView; console.log(window.location.href); // returns 'about:blank' console.log(window.location.hash); // returns no value 

I tried to assign values ​​directly to window.location.hash with the same result.

+5
source share
3 answers

You can set location.hash by entering the line immediately after # in the url. Refer to the following code.

 var jsdom = require("jsdom"); jsdom.env({ url: 'http://localhost?something=not#hash', 'html': '', onload: function( window ) { console.log(window.location.href); // http://localhost/?something=not#hash console.log(window.location.hash); // #hash } }); 
+1
source

I also ran into this problem, but I had problems with the jsdom.env(...) solution. I ended up with a recommendation here and used the jsdom changeURL function. My test device setup looked something like this:

 beforeEach(function() { // snip... jsdom.changeURL(window, 'http://foo/bar') // snip... }) 
+5
source

This worked for me.

 Object.defineProperty(window.location, 'href', { writable: true, value: 'some url' }); 
0
source

Source: https://habr.com/ru/post/1236822/


All Articles