Dmytro Zarezenko
Dmytro Zarezenko

Reputation: 10686

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

Upvotes: 4

Views: 1784

Answers (2)

Brian Adams
Brian Adams

Reputation: 45800

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.

Upvotes: 2

Aldarund
Aldarund

Reputation: 17621

You can just set them in beforeAll

beforeAll(() => {
  process.env = Object.assign(process.env, { get_settings: 'get_settings' });
});

Upvotes: 1

Related Questions