Search code examples
node.jsjestjspuppeteerts-jestend-to-end

How to set testEnvironment: 'node' config dynamically


I initially had a bunch of tests written in jest for my NextJS app located in src/tests/components/*.test.tsx. I'm now trying to write my first end-to-end tests under src/tests/end-to-end/*.test.tsx.

I'm having issues running both types of tests together as they require different test environment configurations. For the component tests, I need to use testEnvironment: 'jest-environment-jsdom', but for the end-to-end tests, I need to use testEnvironment: 'node'.

Is there a way for me to set the test environment to node but only when running the E2E tests? What's the best way to set this up?


Solution

  • Yes one idea is to use a node envelope file that can store what env you are in. After installing dotenv with npm i dotenv, you create a .env file at the root of your repo.

    In the file add: ENVIRONMENT=prod

    Then in the file you need to reference your variable, follow as below. ex.

    require("dotenv").config();
    const obj = {
        testEnvironment: process.env.ENVIRONMENT === 'prod' ? 'node' : 'otherSetting'
    }