在脚本中导入/导出变量的最佳方法是什么?

时间:2018-07-18 18:42:15

标签: javascript node.js typescript

我正在用Cucumber + Puppeteer + Typescript开发测试自动化脚本。我面临导入在主模块中声明的变量的问题,例如index.js。首先,关于我想要实现的目标: 我想通过执行test-runner.ts而不是npm run cucumber来运行测试,因为需求需要对流程进行更多控制。 test-runner.ts模块的草稿如下:

const exec = require('child_process').exec;
const commandLineArgs = require('command-line-args');

export let launchUrl: string;

const optionDefinitions: Array<object> = [
  { name: 'country', alias: 'c' },
  { name: 'environment', alias: 'e' },
  { name: 'headless', alias: 'h' },
];

function initGlobals() {
  const options = commandLineArgs(optionDefinitions);

  if (options.environment === 'integration') {
    launchUrl = 'https://example.url.com';
  }
}

function main() {
  let cucumber: any;
  let cucumberHtmlReporter: any;

  cucumber = exec('./node_modules/.bin/cucumber-js', (stdout: any, err: any) => {
    console.log(err);
    console.log(`stdout: ${stdout}`);
  });

  cucumber.on('exit', () => {
    cucumberHtmlReporter = exec('node cucumber-html-reporter.js', (stdout: any, err: any) => {
      console.log(err);
      console.log(`stdout: ${stdout}`);
    });
  });
}

initGlobals();
main();

因此,如您所见,它主要解析参数,运行Cucumber并导出变量。该变量将导入到步骤定义文件中。从理论上讲,它应该可以正常工作,但是不幸的是,它不能。导入时,将再次执行整个功能。这意味着每次执行import { launchUrl } from ../test-runner时,都会运行一个新的Cucumber应用程序并发生某种循环。

问题是:我应该如何导出变量以实现我的目标并避免出现这种情况?

1 个答案:

答案 0 :(得分:1)

无论如何,最佳做法是将常量存储在单独的配置文件中,您可以从中导出launchUrl。然后,您的test-runner.ts将导入它并根据需要对其进行突变。

export const URL_CONFIG = { launchUrl: '' };

然后在您的测试运行器中:

import { URL_CONFIG } from './config';
URL_CONFIG.launchUrl = 'foo'; //Everywhere in the ap launchUrl is 'foo'
相关问题