获取参数的 gulp 命令

2022-01-12 00:00:00 javascript gulp

我的 package.json 有这样的脚本

my package.json has scripts like this

  {
   "scripts": {
         "pretest": "npm run tsc",

          "test": "gulp e2e",
         }
    }

我们使用 typescript 和 webdriverIO 来实现自动化.我想使用 gulp 以便我可以将参数传递给我的测试框架.示例:

we use typescript and webdriverIO for automation. I want to use gulp so that i can pass parameters to my test framework. Example:

       npm test --suite HomePageTests

那么与主页相关的规范必须运行.

then the specs related to Home page must run.

我有这样的 gulp 文件

I have the gulp file like this

      // gulpfile.js
      const gulp = require('gulp');

       const Launcher = require('webdriverio/build/lib/launcher');
       const wdio = new Launcher(path.join(__dirname, 
                                      'src/config/conf.ts'));



        // fetch command line arguments
        const arg = (argList => {
           let arg = {}, a, opt, thisOpt, curOpt;
           for (a = 0; a < argList.length; a++) {

                thisOpt = argList[a].trim();
                opt = thisOpt.replace(/^-+/, '');
                 if (opt === thisOpt) {
                       // argument value
                       if (curOpt) arg[curOpt] = opt;

                                 curOpt = null;

                  }else {

                    // argument name
                    curOpt = opt;
                    arg[curOpt] = true;
                  }

                }
               console.log("arg", arg)
               return arg;
               })(process.argv);


              gulp.task('e2e', () => {
                  return wdio.run(code => {
                     process.exit(code);
                  }, error => {
                  console.error('Launcher failed to start the test',error.stacktrace);
                 process.exit(1);
               });


            });

所以当我像直接调用 gulp 时

So when I call gulp directly like

          gulp e2e --suite HomePageTests

它被打印为

           suite: HomePageTests

但是如果我使用

            npm test --suite HomePageTests

它在打印 gulp e2e HomePageTests

问题

  1. 如何从 npm 传递这些值以使 gulp 理解
  2. 如果我传递给另一个值,比如 gulp e2e --server staging,并且想在我的规范文件中使用变量staging",比如

  1. How do I pass these values from npm to make gulp understand
  2. If I am pass to another value like gulp e2e --server staging and would like to use the variable "staging" in my spec file like

如果服务器=== 暂存{//做这个} 别的 {//去做}

if server=== staging{ // do this } else { // do that }

我应该如何将它们从 gulp 文件传递​​到我的规范文件?

How should I pass them from gulp file to my spec file?

谢谢!!

推荐答案

你可以使用 yargs 依赖

var argv = require('yargs').argv;
gulp.task('test', function(){
   console.log(argv.arg);
});

那么如果你在一个 gulp 上运行一个命令,像这样传递 arg

then if you run a command on a gulp passing the arg like this

gulp test --arg HomePageTests

它将在控制台输出HomePageTests

相关文章