0

My tests were running fine first, I am now using environmental variables based on the window object like:

{window._env_.REACT_APP_URL}

But when I run my test: it shows as TypeError: Cannot read property 'REACT_APP_URL' of undefined

Do I need to do something different in my test files to accept this type of variable, when I change to {process.env.REACT_APP_URL} everything works as expected?

Any idea's?

1 Answer 1

1

The _env_ property does not exist on the window object out of the box, hence TypeScript is complaining that you are assigning a value to an undefined property.

Best way to solve your issue is to reassign the window variable to a custom one that combines the current window types with your own custom EnvironmentVariables interface and use that in your tests instead:

interface EnvironmentVariables {
  '_env_': {
    'REACT_APP_URL': string
  }
}

const customWindow = window as Window & typeof globalThis & EnvironmentVariables;

// set the _env_ object with values
customWindow._env_ = {
  'REACT_APP_URL': 'url here'
}

// access REACT_APP_URL
customWindow._env_.REACT_APP_URL
Sign up to request clarification or add additional context in comments.

2 Comments

What if the url comes from a .env file? as in where would you declare this code? in the component, different file etc?
That's a good question. The window variable should exist throughout the runtime of all tests, so if you place the code above within the suite that is going to be using REACT_APP_URL, they should run as expected. In regards to how you retrieve and assign the value for the environment variable is up to the setup of your application. If you are using .env files, it will likely be like this customWindow._env_ = { 'REACT_APP_URL': process.env.REACT_APP_URL }, but that is up to your application setup and out of scope of the original question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.