Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to add ENV variables to the extension? #492

Closed
Drakota opened this issue Aug 13, 2019 · 19 comments · Fixed by #777
Closed

How to add ENV variables to the extension? #492

Drakota opened this issue Aug 13, 2019 · 19 comments · Fixed by #777

Comments

@Drakota
Copy link

Drakota commented Aug 13, 2019

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’t 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.

@abdusamadtv
Copy link

abdusamadtv commented Aug 26, 2019

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

@ejose19
Copy link

ejose19 commented Sep 9, 2019

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.

@sanderploegsma
Copy link

@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.

@ab-pm
Copy link

ab-pm commented Nov 20, 2019

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.

@jbdavid
Copy link

jbdavid commented Nov 22, 2019

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

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

@thccorni
Copy link

thccorni commented Dec 3, 2019

@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 --.

@alireza-mpr
Copy link

alireza-mpr commented Dec 28, 2019

@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",
    }
}

@ab-pm
Copy link

ab-pm commented Jan 7, 2020

@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.

@nublson
Copy link

nublson commented Jan 20, 2020

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)
})

@jspreddy
Copy link

jspreddy commented Jan 29, 2020

#492 (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.

I tried the above-suggested method and it worked.

portal-core_—_jest_config_js

@vic-3pg
Copy link

vic-3pg commented Feb 20, 2020

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.

@counterbeing
Copy link

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.

@jessepinho
Copy link

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().

@BoesesGenie
Copy link

BoesesGenie commented Aug 26, 2020

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.

@HassenIO
Copy link

@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',
  },
};

@rantoniuk
Copy link

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

@yuankui
Copy link

yuankui commented Jan 16, 2023

Here is my solution, without changing jest.config.js.

we know vscode-jest runs by running command jest...,

so open the file node_modules/jest/bin/jest.js

add you custome logic here like(Here I'm using dotenv, you can apply any logic here)

#!/usr/bin/env node
/**
 * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

++ require('dotenv').config({ path: '.env.test' });

const importLocal = require('import-local');

if (!importLocal(__filename)) {
  require('jest-cli/bin/jest');
}

@jmatonrdx
Copy link

Thanks for several posts above.
It was very helpful reading through the discussion, and enabled me to solve my problem as well.

@devgnx
Copy link

devgnx commented Dec 28, 2023

This one solved my problem using VSCode Jest extension (vscode-jest-tests.v2)

# package.json
{
    "scripts" {
        "test": "env-cmd -f ./my-test.env node ./node_modules/.bin/jest"
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.