Home > Net >  CRA - window object is undefined - jest/react
CRA - window object is undefined - jest/react

Time:05-16

I have an issue in my tests that flag up a window variable as undefined. But I don't know where in the setupTests.tsx, I would need to define it. So far the variable is used as so:

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <script src="%PUBLIC_URL%/config.js"></script>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

config.js

window._env_ = {
  REACT_APP_URL: "https://apiurl.com"
}

how it is used in the app:

declare const window: Window &
    typeof globalThis & {
        _env_: any
    }

const url = window._env_.REACT_APP_URL;
export const apiUrl = url;

setupTests.tsx I did try adding it here but it's still not working

import '@testing-library/jest-dom';
import { setLogger } from 'react-query'
import { server } from './mocks/server'
declare const window: Window &

typeof globalThis & {
    _env_: any
}

window._env_.REACT_APP_URL = "https://wwww.xxxxx.com"

beforeAll(() => server.listen())
// Reset any request handlers that we may add during the tests,
// so they don't affect other tests.


afterEach(() => server.resetHandlers())

// Clean up after the tests are finished.
afterAll(() => server.close())

The error that stops the tests:

  ● Test suite failed to run

    TypeError: Cannot read properties of undefined (reading 'REACT_APP_URL')

      4 |     }
      5 |
    > 6 | const url = window._env_.REACT_APP_URL;
        |                          ^
      7 | export const apiUrl = url;
      8 |
      9 |

Any idea's for use with Create React App setup?

CodePudding user response:

Since you don't have the environment variable defined in development (since the config.js file is used only in production), you can simply fallback to a hardcoded url, as shown below.

declare const window: Window &
  typeof globalThis & {
    _env_: any
  }

const url = window._env_.REACT_APP_URL || "https://wwww.xxxxx.com";
export const apiUrl = url;

So, in environments where the REACT_APP_URL environment variable is defined it will use that and if it's not defined it will pick up the hardcoded value.

And, now you can remove all the additional code from setupTests.tsx.

  • Related