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?
CodePudding user response:
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