'Jest (unable to set unique href for window.parent.location.href)
I have in my code a check to see if a page is being loaded inside iframe.
App.js
if (window.location !== window.parent.location) {
console.log('App is running inside iframe!');
}
Jest test...
App.spec.js
delete window.location
window.location = new URL(`https://some-fake-url`)
delete window.parent.location
window.parent.location = new URL(`https://parent-fake-url`);
Inside the Jest test both window.location.href
and window.parent.location.href
are both set with the same value.
How can I set each to be unique?
Solution 1:[1]
I believe I was able to resolve this with the following...
global.window = Object.create(window);
delete global.window.parent;
global.window.parent = Object.create(window);
Object.defineProperty(global.window, 'location', {
value: {
href: 'https://my-site'
}
});
Object.defineProperty(global.window.parent, 'location', {
value: {
href: 'https://my-parent-site'
}
});
Solution 2:[2]
This also works if you want to use the URL api:
global.window = Object.create(window);
delete global.window.parent;
global.window.parent = Object.create(window);
window.location = new URL('https://my-site');
window.parent.location = new URL('https://my-parent-site');
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | jremi |
Solution 2 | Duke P |