【问题标题】:What is the best way to import/export variables in typescript?在打字稿中导入/导出变量的最佳方法是什么?
【发布时间】:2018-07-18 18:42:15
【问题描述】:

我正在用 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 应用程序并发生某种循环。

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

【问题讨论】:

    标签: javascript node.js typescript


    【解决方案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'
    

    【讨论】:

    • 我明白你的意思,但想法是通过在命令行中传递 env 名称在特定的开发环境中执行测试自动化脚本。我猜你提出的解决方案不允许这样做。
    • 嗯不知道你的意思。当您在 initGlobals 函数中设置 URL_CONFIG.launchUrl 时,它将在应用程序的整个生命周期中设置,并且不会强制您每次导出时都运行 initGlobals() 和 main(),因为它位于单独的文件中,您只需要确保在将 URL_CONFIG.launchUrl 传递到命令行参数之前调用 initGlobals
    • 好吧,我误会你了。但这是不可能的。我无法更改导入对象的值。我错了吗?
    • 据我所知,当我导入一个对象时,会创建一个对象的副本,我只修改副本,而不是原始对象
    • 当它作为 const 导出时,无论导入到哪里,它在内存中的相同对象
    猜你喜欢
    • 2016-12-17
    • 1970-01-01
    • 2016-03-05
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    • 2017-07-21
    • 2016-10-03
    • 2023-01-19
    相关资源
    最近更新 更多