vendredi 29 novembre 2019

Dotenv loads envs but Jest doesn't read them

BACKGROUND

I'm using process.env.<ENV NAME> to set variables in some classes. I need to set them in the tests for the class variables to be set otherwise the test fails.

Currently, I'm setting the variables in a beforeAll() hook. However, there are many test files in which I'll have to set these envs. I don't want to replicate this code throughout all these files if I don't have to.

I decided it would be a good idea to set them up prior to each test through a Jest set-up file. In jest.config.js I added setupFiles: ['<rootDir>/jestSetupTest.js']. Inside this file I added require('dotenv').config(). The .env file is in the root directory.

I've got test files in a couple of different directories: ./src/graphql/__tests__ and ./src/utils/__tests__.

PROBLEM

The envs are being set but they are not being read by any of the Jest tests that are running.

ATTEMPTED

I looked into this issue which got me as far as being able to set-up the env vars, but it has nothing about issues using them.

I've added require('dotenv').config() to the test files that use the envs, but that still doesn't work. This surprised me I thought at least this would set the envs.

I set --debug on Jest but that doesn't show whether envs were set or not.

QUESTIONS

Does anyone know what is going on? Or how I can further diagnose this issue?

I get the impression envs can be set and used in Jest tests, as per the SO post above. Why am I not able to use them? Could it be a config issue with the way my files are set-up?

Aucun commentaire:

Enregistrer un commentaire