Yashua Yashua - 3 months ago 88
Javascript Question

Set location.hash and location.href with JSDom

I am setting up some tests using JSDom where I need the

window
and
document
globals and also need to pass a different URL/href for each tests. How do I set the
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 have tried assigning values directly to
window.location.hash
with same result.

Answer

You can set location.hash by inputting string just after # in url. Refer to the follow my 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
    }
});
Comments