【问题标题】:Global node-config variable undefined when testing with Jest使用 Jest 测试时未定义全局节点配置变量
【发布时间】:2019-11-26 19:45:00
【问题描述】:

我正在实施来自node-config docs 的选项 2。

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

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

  ● Test suite failed to run

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

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

【问题讨论】:

    标签: vue.js webpack vuejs2 jestjs node-config


    【解决方案1】:

    Jest 不运行 Webpack,因此您必须手动设置测试配置。作为一种解决方法,您可以将配置声明为 Jest global

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

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

    【讨论】:

    • 我尝试在 Jest 配置中设置 globals,但问题是配置应该是动态的(首先从 test.json 获取,然后从 default.json 获取其余部分)。但是,我想我可以提供测试配置的完整副本。但是,我想我最终可能会在这里使用选项 1:github.com/lorenwest/node-config/wiki/Webpack-Usage
    • 我明白了。从技术上讲,您仍然可以轻松地在 jest.config.js 中重新创建动态加载。
    猜你喜欢
    • 2018-06-27
    • 2016-05-28
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    • 2014-12-03
    • 1970-01-01
    相关资源
    最近更新 更多