writofmandamus
writofmandamus

Reputation: 1231

Global node-config variable undefined when testing with Jest

I am implementing Option 2 from the node-config docs.

This runs fine, and my global config variable is defined when running outside of a test environment.

However, when I run this with vue-cli and Jest unit testing (e.g. vue-cli-service test:unit), I get this error:

  ● Test suite failed to run

    ReferenceError: APP_CONFIG is not defined
// vue.config.js
...
 configureWebpack: {
    plugins: [
      new ConfigWebpackPlugin('APP_CONFIG')
    ]
  },
...

What is a good way around this? Is it because Jest starts executing the JS files before the node-config can finish switching out all global variables with their values?

Upvotes: 3

Views: 2922

Answers (1)

tony19
tony19

Reputation: 138236

Jest does not run Webpack, so you would have to manually setup the config for your tests. As a workaround, you could declare the config as a Jest global.

To declare the global, add the globals property to the exported object in jest.config.js. The sub-property key would be the config-webpack's namespace (APP_CONFIG in your case), and the value would be the required config JSON files from config/:

// jest.config.js
module.exports = {
  globals: {
    APP_CONFIG: require('./config/default.json')
  }
}

Upvotes: 3

Related Questions