关于vue.js:使用Jest测试时未定义全局节点配置变量

Global node-config variable undefined when testing with Jest

我正在从node-config文档中实现选项2。

这很好运行,并且在测试环境之外运行时定义了我的全局配置变量。

但是,当我使用vue-cli和Jest单元测试(例如vue-cli-service test:unit)运行它时,出现此错误:

1
2
3
  ● Test suite failed to run

    ReferenceError: APP_CONFIG is not defined
1
2
3
4
5
6
7
8
// vue.config.js
...
 configureWebpack: {
    plugins: [
      new ConfigWebpackPlugin('APP_CONFIG')
    ]
  },
...

解决这个问题的好方法是什么?是因为Jest在node-config可以完成用其值切换出所有全局变量之前开始执行JS文件吗?


Jest无法运行Webpack,因此您必须手动设置测试配置。解决方法是,可以将配置声明为Jest全局。

要声明全局,将globals属性添加到jest.config.js中的导出对象。子属性键将是config-webpack的命名空间(在您的情况下为APP_CONFIG),值将是config/

中所需的配置JSON文件。

1
2
3
4
5
6
// jest.config.js
module.exports = {
  globals: {
    APP_CONFIG: require('./config/default.json')
  }
}