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.
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...
})
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With