Vscode-jest: How to add ENV variables to the extension?

Created on 13 Aug 2019  路  16Comments  路  Source: jest-community/vscode-jest

Environment

  1. node -v: v12.6.0
  2. npm -v: 6.9.0
  3. npm ls jest or npm ls react-scripts (if you haven鈥檛 ejected): [email protected] & [email protected]
  4. your vscode-jest settings if customized:

    • jest.pathToJest? none
    • jest.pathToConfig? none
    • anything else that you think might be relevant? none
  5. Operating system: Ubuntu 18.04

Prerequisite

  • are you able to run jest test from command line? Yes
  • how do you run your tests from command line? (for example: npm run test or node_modules/.bin/jest) npm run test

Problem

Hi, I'm trying to use the extension, but all my tests fails because there's missing ENV variables required to make my tests work. My test script looks like this dotenv -e .env.test jest and it works fine, but not with the extension. I tried using jest.pathToJest and set it to npm run test --, but I run into the #316 issue, because I'm using ts-jest. Is there another alternative to my problem?

Thank you.

Most helpful comment

You can set environment variables in jest.config.js

ie:

process.env.YOUR_VARIABLE = "here";

module.exports = {
  preset: "ts-jest",
  testEnvironment: "node"
};

I didn't found any direct way to set the env variables directly within the extension.

All 16 comments

I have the same problem. I'm running tests with this command
"test": "env-cmd ./config/test.env jest --watch"
but extension isn't seeing variables

You can set environment variables in jest.config.js

ie:

process.env.YOUR_VARIABLE = "here";

module.exports = {
  preset: "ts-jest",
  testEnvironment: "node"
};

I didn't found any direct way to set the env variables directly within the extension.

@ejose19 are you sure about that? I tried setting the NODE_ICU_DATA env var in jest.config.js instead of in my package.json, but that didn't work.


Ideally this plugin would use VS Code launch configurations, which we could edit to include environment variables.

It would be really nice to have options that work like env or envFile in the launch.json config - those only apply to debugging but not to the test run.

@sanderploegsma , this worked for me at the top of jest.config.js:

process.env.NODE_ICU_DATA = 'node_modules/full-icu'

@sanderploegsma Setting NODE_ICU_DATA in jest.config.js didn't work for me either. I ended up setting up a script in my package.json ("jest": "NODE_ICU_DATA=node_modules/full-icu jest") and pointing the config option _Path To Jest_ to npm run jest --.

@ab-pm @sanderploegsma @thccorni
Setting environment variables in a VSCode configuration is absolutely doable via property env or envFile.
See: https://code.visualstudio.com/docs/nodejs/nodejs-debugging , under env section.

Example:

{
    "type": "node",
    "request": "launch",
    "name": "Jest All",
    "program": "${workspaceFolder}/node_modules/.bin/jest",
    "env": {
        "NODE_ENV": "test",
        "NODE_ICU_DATA": "node_modules/full-icu"
    },
    "args": [ 
        "--runInBand",
        "--config",
        "jest.config.js"
    ],
    "console": "integratedTerminal",
    "internalConsoleOptions": "neverOpen",
    "disableOptimisticBPs": true,
    "windows": {
        "program": "${workspaceFolder}/node_modules/jest/bin/jest",
    }
}

@AlirezaInGitHub Iirc that's exactly what I tried, but that only adds a new "Jest all" launch option, it does not affect the individual test runs that show up in the code lens next to the respective test code.

I had the same problem, when saving the test file it used .env instead of .env.testing, all I did was import the variables from this file before anything in my test file.

require('dotenv').config({
    path: '.env.testing'
})

const request = require('supertest')
const app = require('../src/app')

test('Should sign up a new user', async () => {
    await request(app)
        .post('/users')
        .send({
            name: 'myName',
            email: '[email protected]',
            password: '12345678'
        })
        .expect(201)
})

https://github.com/jest-community/vscode-jest/issues/492#issuecomment-529563968

You can set environment variables in jest.config.js

ie:

process.env.YOUR_VARIABLE = "here";

module.exports = {
  preset: "ts-jest",
  testEnvironment: "node"
};

I didn't found any direct way to set the env variables directly within the extension.

I tried the above-suggested method and it worked.

portal-core_鈥擾jest_config_js

How about configuring vscode-jest to start jest through dotenv like so:
"jest.pathToJest": "node -r dotenv/config node_modules/.bin/jest" (eg. in .vscode/settings.json)
This will load the .env file before executing your tests and without requiring you to touch the jest.conf.js file.

I just solved the same problem, but in a slightly different way.

I launch VSCode from the terminal with the code command. I just ran into this because i opened the project previously by opening the workspace, but that killed my env vars for Jest.

So in a terminal with all of your desired ENV vars already loaded, and in the project directory just run code ..

Works for me on Mac OS. I'd be curious to know if this is the same for everyone.

FYI all, you can do this using Jest's globalSetup config option. In your package.json's jest key (or in your jest.config.js file), add a globalSetup key with the name of a JS file to run before all tests. In that file, export a function that e.g. runs dotenv.config().

It's much easier if you run tests in container with bash. Just add to "script" section in your package.json file: "test": "export $(cat ./build/.env.test) && jest". Change "./build/.env.test" to your directory with .env.

@nubelsondev pointed out to a valid solution. Adding

require('dotenv').config({
  path: '.env.testing',
});

in the test and having specific env variables in a file works. I also tried adding it more globally to my jest tests in the jest.config.js file, and it works too:

// File: config.jest.js

require('dotenv').config({
  path: '.env.testing',
});

module.exports = {
  preset: 'ts-jest',
  roots: ['<rootDir>/src'],
  testMatch: ['**/__tests__/**/*.test.+(ts|tsx|js)'],
  transform: {
    '^.+\\.(ts|tsx)?$': 'ts-jest',
  },
};

What worked for me was to use terminal.integrated.env.os from https://code.visualstudio.com/docs/getstarted/settings.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

connectdotz picture connectdotz  路  37Comments

erikns picture erikns  路  16Comments

therazor picture therazor  路  36Comments

Glutnix picture Glutnix  路  37Comments

luisrudge picture luisrudge  路  27Comments