Mushegh Arustamyan
Mushegh Arustamyan

Reputation: 1

Environment not loading correctly while running tests in Node.js with Jest

I'm having an issue with my Node.js project where the environment variables are not loading correctly during my tests.

I made sure the .env file is placed in the root of the project. I’m using the dotenv package to load the environment variables. The issue seems to occur only during the test runs, not when running the server with nodemon. I also tried using cross-env to set NODE_ENV to test, but the environment variables still aren’t being loaded correctly during tests.

Here is a snippet of codes and configs that I set up.

dotenv config:

dotenv.config({ path: `${process.cwd()}/.env`, debug: true });

Failed test:

describe("Ping Route", () => {
  it("Should return 'Pong' with status 200 when GET /ping is called", async () => {
    const server = app.getApp();

    const response = await request(server).get("/ping");

    expect(response.status).toBe(200);
    expect(response.text).toBe("Pong");
  });
});

Jest config file:

module.exports = {
  preset: "ts-jest",
  testEnvironment: "node",
  testMatch: ["**/*.test.ts"],
  globals: {
    "ts-jest": {
      tsconfig: "tsconfig.test.json",
    },
  },`your text`
};

test config file:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "noEmit": true,
    "types": ["jest"],
    "baseUrl": ".",
    "paths": {
      "@src/*": ["src/*"]
    }
  },
  "include": ["tests/**/*", "src/**/*.d.ts"],
  "exclude": ["node_modules"]
}

And my getEnv function which throws the error of missing env variable:

export const getEnv = (key: string): string => {
  if (!process.env[key]) throw new Error(`Missing environment variable ${key}`);

  return String(process.env[key]);
};

Upvotes: 0

Views: 34

Answers (0)

Related Questions