Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 626
cyberwombat Avatar asked Nov 25 '15 16:11

cyberwombat


2 Answers

I ran into this issue too, but was having trouble getting the jsdom.env(...) solution to work. I ended up following the recommendation here, and using jsdom's changeURL function. My test fixture setup looked something like this:

beforeEach(function() {
  // snip...
  jsdom.changeURL(window, 'http://foo/bar')
  // snip...
})
like image 163
killthrush Avatar answered Oct 07 '22 14:10

killthrush


A lot of these answers are old. Newer jsdom versions don't allow you to overwrite things like before. What you're looking for is probably the reconfigure function.

import { JSDOM } from 'jsdom';

const jsdom = new JSDOM();

// ...
jsdom.reconfigure({
  url: 'https://www.test.com/whatever/url/you/want',
});
// ...

Documentation for reconfigure() can be found here.

Check out this article from 2020 for more information.

like image 30
Jacob Smith Avatar answered Oct 07 '22 16:10

Jacob Smith