Stubbing/patching `window.location.href` in JSDom 8?
See original GitHub issueWe’ve got some code in use in tests that worked in jsdom 7 but appears not to work in jsdom 8.
Our JSDom setup:
const doc = jsdom.jsdom('<html><body></body></html>', {
referrer: 'https://example.com/baz',
url: 'https://example.com/foo'
});
global.document = doc;
global.window = doc.defaultView;
And the test itself:
window.location.href = 'https://newurl.com/foo';
// some assertions that depend on window.location
Adding some logging immediately after setting window.location.href
shows that the value wasn’t actually updated or changed, and other means overriding (e.g. stubbing with sinon
) don’t seem to work either since it’s implemented via getters/setters rather than an actual property. What’s the best way to override this value?
It looks like setting is supposed to do something based on https://github.com/tmpvar/jsdom/blob/master/lib/jsdom/living/window/Location-impl.js#L46 but I can’t figure out what the final effect of that is supposed to be.
Issue Analytics
- State:
- Created 8 years ago
- Reactions:6
- Comments:16 (12 by maintainers)
Top Results From Across the Web
mocking window.location.href in Javascript - Stack Overflow
The best way to do this is to create a helper function somewhere and then mock that: var mynamespace = mynamespace || {};...
Read more >location.href - Web APIs | MDN
The href property of the Location interface is a stringifier that returns a string containing the whole URL, and allows the href to...
Read more >jest-environment-jsdom-global - npm
Jest environment for a globally-exposed JSDOM ... test('use jsdom and set the URL in this test file', () => { expect(window.location.href).
Read more >Jest: How to Mock window.location.href - Wild Wild Wolf
In a recent project, I needed to write a test for a React component which performed a redirect. Something like this: useEffect((): void...
Read more >How to use the jsdom.changeURL function in jsdom - Snyk
test('browser.hash sets the current URL hash', (t) => { jsdom.changeURL(window, 'https://google.com'); browser.hash('hash'); t.equal(window.location.href, ...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I’ve just noticed that content on the link @domenic posted above possibly lives on this one now
https://github.com/tmpvar/jsdom#reconfiguring-the-jsdom-with-reconfiguresettings
Yes, this was implemented recently: https://github.com/tmpvar/jsdom#changing-the-url-of-an-existing-jsdom-window-instance