Using .env and .env.test from React component tests

Gleb Bahmutov
1 min readJun 22, 2020

--

When you write React component tests using cypress-react-unit-test you can take advantage of react-scripts support for .env and other environment files. For example, you might write theREACT_APP_* test values into the .env.test file; these values will overwrite the production value set in the .env file.

// App.jsx
<span id="env-var">{process.env.REACT_APP_NOT_SECRET_CODE}</span>
// .env
REACT_APP_NOT_SECRET_CODE=Hello App!

During component tests let’s use a different value. We can place it in .env.test file.

// .env.test
REACT_APP_NOT_SECRET_CODE=Hello Tests!

The test can mount the component and assert the expected text appears

import App from './App'import { mount } from 'cypress-react-unit-test'it('uses .env.test value', () => {  mount(<App />)  cy.contains('#env-var', 'Hello Tests!')})

See React .env docs for file precedence, and you can find a full example in react-scripts example folder.

Caution: the environment variables object process.env is inserted using Webpack.DefinePlugin that does “simple” text substitution. Thus process.env is NOT a real object. It is just a placeholder that will contain a stringified value set at compile time.

// App.jsx
// when you use
console.log(process.env.REACT_APP_NOT_SECRET_CODE)
// the bundle will have
console.log("Hello Tests!")

Thus the tests cannot change the env properties inside a test — these values are set once during bundling.

For more Cypress tips & tricks check out

--

--

Gleb Bahmutov

JavaScript ninja, image processing expert, software quality fanatic