Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access `process.env` property when testing nuxt.js app with jest

I want to write unit tests for my Nuxt.js application with Jest. But some of my components use process.env property declared in the nuxt.config.js file. When I run my tests I received this error:

enter image description here

Test file example:

import Config from "../nuxt.config"
import { mount } from "@vue/test-utils"
import CleanMapButton from "../components/UI/buttons/CleanMapButton.vue"

beforeAll(() => {
  process.env = Config.env
})

describe("Clean map button tests", () => {
  it ('Always true test', () => {
    expect(true).toBe(true)
  })
})
like image 482
Dmytro Zarezenko Avatar asked Sep 01 '25 10:09

Dmytro Zarezenko


2 Answers

Imports are hoisted so the import statements all run before process.env is set in beforeAll.

If an import-ed module needs a global variable set then it must be set before the test starts running by setting it in a setup module and configuring Jest to run that setup module using something like setupFilesAfterEnv.

On the other hand, calling require runs the code at the time it is required so the alternative is to refactor your test code to call require('../components/UI/buttons/CleanMapButton.vue') after beforeAll sets process.env.

like image 82
Brian Adams Avatar answered Sep 03 '25 14:09

Brian Adams


You can just set them in beforeAll

beforeAll(() => {
  process.env = Object.assign(process.env, { get_settings: 'get_settings' });
});
like image 34
Aldarund Avatar answered Sep 03 '25 15:09

Aldarund