jest-location-mock
jest-location-mock copied to clipboard
Workaround for newer jsdom
Credit to ChatGPT for this, a workaround for newer jsdom where they make everything immutable, maybe this can get incorporated into your module
function mockLocation(windowObj) {
const propertyDescriptors = Object.getOwnPropertyDescriptors(windowObj);
for (const key in propertyDescriptors) {
propertyDescriptors[key].configurable = true;
}
const clonedWindow = Object.defineProperties({}, propertyDescriptors);
clonedWindow.Event = windowObj.Event;
let hrefValue = '';
Object.defineProperty(clonedWindow, 'location', {
configurable: true,
value: {
get href() { return hrefValue; },
set href(href) { hrefValue = href; }
}
});
return clonedWindow;
}
...
global.window = mockLocation(window)
...