0

In my CRA app, util JS file, there is a method pause which I would like to change depending on the environment it's running.

class CompilationEngine {
  ...
  pause () {
    return new Promise(resolve => emitter.once('next', resolve))
  }
  ...
}

I want pause function to return Promise.resolve() in test environment(when I run npm run start) since some tests are failing due to next event not emitted in console test. So how can I detect the environment and change the code inside pause function.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
Henok Tesfaye
  • 8,287
  • 13
  • 47
  • 84
  • The question isn't clear enough what environment you want to detect. It seems that it's test environment but it's barely mentioned. It's likely XY problem as for testing you can and commonly will mock things that need to behave differently in tests. – Estus Flask Nov 22 '20 at 14:49
  • Use mocks instead – lissettdm Nov 22 '20 at 16:02

2 Answers2

0

I think you're looking for

process.env.NODE_ENV

right?

obasilakis
  • 19
  • 3
0

Quickly answer

In CRA you can use environment variables declaring them before the npm run start

You must create custom environment variables beginning with REACT_APP_. Example:

export REACT_APP_DISABLE_NEXT = true

CRA framework will expose this operative system level variable to a simple javascript variable ready to use in any part of your react code:

process.env.REACT_APP_NOT_SECRET_CODE

source:

Explanation

Environment variables like export FOO=BAR are variables at operative system level. These variables are easy accessed with:

process.env.FOO

React is not a nodejs javascript. React will be converted to vanilla javascript to be able to run in a browser. In this javascript process.env does not exist.

But CRA Framework (which is nodejs), have access to the operative system variables, so it create us an emulation of process.env containing just variables which start with REACT_APP_. Any other variable without REACT_APP_, will be ignored

Advice

  • Expose export REACT_APP_DISABLE_NEXT = true just in dev or test stage, not in prod
JRichardsz
  • 14,356
  • 6
  • 59
  • 94