Create React App - Unable to set window object before test runs

Viewed 1022

Trying to set up some tests for a component in a CRA-generated application.

Having an issue where the test is failing to run due to an imported file relying on a window object which isn't initialised.

Quick overview: In public/index.html there is an object defined on the window called window.config.

<script src="%PUBLIC_URL%/config.js"></script>
<script>
  // THESE PROPERTIES ARE DEFINED IN config.js
  window.config = {
    ENV,
    IDENTITY_URL,
    OIDC_CLIENT_ID,
  };
</script>

There is a file called identity.constants.js which exports an object that uses these window variables.

export const IdentityConfig = {
    authority: window.config.IDENTITY_URL,
    client_id: window.config.OIDC_CLIENT_ID,
    ... etc
};

The component I am trying to test imports another component that relies on identity.constants.js shown above.

The problem is that the test fails to start and throws an error stating window.config is undefined from the identity.constants.js file.

After reading the CRA docs, I have tried adding the following code into src/setupTests.js to set the config object before the test starts but it seems to fail before this code runs.

global.config = {
  ENV: "development",
  IDENTITY_URL: "identityurl.com",
  OIDC_CLIENT_ID: "i-am-a-clientId",
  ... etc
};

I'm looking for a way to set this window variable before the tests run (or a better way to structure the way I'm using window variables) so I can successfully run my tests.

1 Answers

globa.config defines a global variable named config, you'll need to define global.window firstly, then add config as a property of global.window. It seems your test environment is node, if you have jsdom as the devDependencies of your project, try to add below piece of code to your setupTests.js:

import { JSDOM } from 'jsdom';

const jsdom = new JSDOM('<!doctype html><html><body></body></html>');
global.window = jsdom.window;
global.document = jsdom.window.document;

global.window.config = {
  ENV: "development",
  IDENTITY_URL: "identityurl.com",
  OIDC_CLIENT_ID: "i-am-a-clientId",
  ... etc
};

Without jsdom, a simple fix is like below:

global.window = {
  config: {
    ENV: "development",
    IDENTITY_URL: "identityurl.com",
    OIDC_CLIENT_ID: "i-am-a-clientId",
    ... etc
  }
}
Related