Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

219
Views
React/Jest use either mock window value or resolve error

My app uses the window object to inject environmental variables at runtime for docker, however my tests are coming back with the error below:

url config:

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

export const url = window._env_.REACT_APP_API_URL;
export const baseUrl = url;

error in tests as the handlers use the baseUrl, but even if I change the handlers to hardcoded values the below error comes:

● Test suite failed to run TypeError: Cannot read properties of undefined (reading 'REACT_APP_API_URL')

      4 |     }
      5 |
    > 6 | export const url = window._env_.REACT_APP_API_URL;
        |                                 ^
      7 | export const baseUrl = url;

setupTests.tsx

// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
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_API_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())

// silence react-query errors
setLogger({
    log: console.log,
    warn: console.warn,
    error: () => {},
})

Any idea's? So where ever there is an api call I get this error in the tests for jest/React.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

you can mock the global window var

test/setup.js

window.env. REACT_APP_API_URL = 'something';

then you need to add in package.json file

"jest": {
    "setupFiles": [
      "./test/setup.js"
    ],

OR

you can define global var in CLI like this

npm run jest -- --globals='{"window": "someUrl", "value": "someValue"}'
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!