3

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?

tony19
  • 125,647
  • 18
  • 229
  • 307
writofmandamus
  • 1,151
  • 1
  • 23
  • 40

1 Answers1

3

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')
  }
}
tony19
  • 125,647
  • 18
  • 229
  • 307
  • I tried setting `globals` in the Jest config but problem was the config was supposed to be dynamic (taking from test.json first, and then the rest from default.json). However, I suppose I can provide a complete copy of the test config. However, I think I may end up using option 1 here: https://github.com/lorenwest/node-config/wiki/Webpack-Usage – writofmandamus Jul 18 '19 at 14:46
  • I see. Technically, you could still recreate that dynamic loading in `jest.config.js` with minimal effort. – tony19 Jul 18 '19 at 23:40