简体   繁体   中英

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 (eg 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM