Search code examples
reactjstestingenvironment-variablescreate-react-appreact-scripts

Set react-scripts test environment file


We're using react-scripts to run our tests, via the command react-scripts test. Locally we have our own test environments, and use the .env.test file as the environment file (it uses this automatically).

However, in our CircleCI environment we want to run the tests using the development environment, i.e. using .env.development. I can't figure out how to tell react-scripts to use the dev env file, I've tried setting various values before running the command like REACT_APP_ENV and NODE_ENV. I've tried using the env-cmd module to specify it to use the dev env file (e.g. env-cmd .env.development react-scripts test), but it STILL uses the test one.

I know in the CircleCI test command I could just overwrite the test env file with the dev one (something like cp -rf .env.development .env.test && react-scripts test), but I was wondering if there was a cleaner way of doing it (since if I did it that way, if we wanted to test using dev environment locally, it'd overwrite our personal .env.test files)?


Solution

  • The only thing you need to do is to modify the react-scripts test command by adding the following:

    --env=jsdom
    

    So the end result would be

    // package.json
    {
        "scripts": {
            ...
            "test": "react-scripts test --env=jsdom"
            ...
        }
    }
    

    https://serverless-stack.com/chapters/environments-in-create-react-app.html