0

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!

Dustin
  • 3
  • 2

1 Answers1

0

I think you have the wrong test environment. By default, Jest runs in node environment.

Base on the latest Jest Doc, you can use the annotation to change it to jsdom, which should allow you to use window

/**
 * @jest-environment jsdom
 */

test('use jsdom in this test file', () => {
  const element = document.createElement('div');
  expect(element).not.toBeNull();
});

Alternatively, you can add the test environment to jest.config.js

Andrew Zheng
  • 2,612
  • 1
  • 20
  • 25
  • I am using the jsdom test environment, which is set in jest.config.js testEnvironment: "jsdom", "testEnvironmentOptions": { "url": "https://www.something.com" }, – Dustin Oct 25 '22 at 14:16