I'm writing tests for a file(some-file.js) that calls functions from another file(url-manipulator.js). I'm getting an error regarding window.location being undefined. You can see in the error below that I logged window.location right before the error, and it is not undefined. In jest.config.js I have configured the testEnvironment URL to https://www.something.com/ . Any idea why this isn't carrying through when I rewire the urlManipulator file?
Error:
console.log
window.location = https://www.something.com/
TypeError: Cannot read properties of undefined (reading 'location')
1 | const urlManipulator = {
> 2 | sHost: 'https://' + window.location.host,
Here is the start of my test file for some-file.js. It's erroring out on this line const urlManipulatorJS = rewire("../../../head/js/url-manipulator") when it tries to read window.location from the url-manipulator file.
some-file.test.js
const rewire = require("rewire");
const file = rewire("../some-file");
const someFile = file.__get__("someFile");
console.log('window.location = ' +window.location);
const urlManipulatorJS = rewire("../../../head/js/url-manipulator");
const urlManipulator = urlManipulatorJS .__get__("urlManipulator");
file.__set__("urlManipulator", urlManipulator);
start of urlManipulator.js where it's failing
const urlManipulator= {
sHost: 'https://' + window.location.host,
edit: adding jest.config.js settings to show that I'm using jsdom environment.
testEnvironment: "jsdom",
"testEnvironmentOptions": {
"url": "https://www.something.com"
},
Thanks for any feedback!