代码之家  ›  专栏  ›  技术社区  ›  ste

在javascript文件中为nodejs添加环境变量

  •  1
  • ste  · 技术社区  · 6 年前

    我正在用NightWatch对Vue JS应用程序进行测试。因为我已经在gitlab ci/cd中集成了测试,所以我需要两种不同的夜视配置。

    为了实现这一目标,我做了以下工作:

    为本地测试和Gitlab测试创建两个不同的脚本

       "scripts" : {
        "e2e" :  "node test/e2e/gitlab_runner.js" ,
        "local-test" :  "node test/e2e/local_runner.js" ,
        "test": "npm run e2e"
    

    然后我将需要的变量嵌入到 local_runner gilab_runner 文件夹

    process.env.NIGHTWATCH_CONFIG = 'nightwatch.local.js';
    require('./runner.js');
    

    对于 gitlab_runner

    process.env.NIGHTWATCH_CONFIG = 'nightwatch.conf.js';
    require('./runner.js');
    

    然后在文件里 runner.js 我有以下代码行

      opts = opts.concat(['--config', 'test/e2e/' + NIGHTWATCH_CONFIG]);
    

    这样我就能得到正确的文件。

    问题是,当我运行脚本时,会出现以下错误:

    (node:21061) UnhandledPromiseRejectionWarning: ReferenceError: NIGHTWATCH_CONFIG is not defined
        at devConfigPromise.then.then (xxxxxx/test/e2e/runner.js:30:51)
        at <anonymous>
        at process._tickCallback (internal/process/next_tick.js:182:7)
        at Function.Module.runMain (internal/modules/cjs/loader.js:697:11)
        at startup (internal/bootstrap/node.js:201:19)
        at bootstrapNodeJSCore (internal/bootstrap/node.js:516:3)
    (node:21061) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
    (node:21061) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
    

    我还尝试在 本地跑步者 Gitlab_跑步者 文件夹:

      module.exports = {
        NIGHTWATCH_CONFIG = 'nightwatch.local.js';
      };
    

    但后来 NIGHTWATCH_CONFIG 中的变量 跑步者.js 文件未定义。

    我该怎么解决?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Ashok JayaPrakash    6 年前

    参考误差 NIGHTWATCH_CONFIG 未定义,因为在调用环境变量时 process.env 需要指定。

    opts = opts.concat(['--config', 'test/e2e/' + process.env.NIGHTWATCH_CONFIG]);