gulp command to take parameters

2019-04-02 09:35发布

问题:

my package.json has scripts like this

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

          "test": "gulp e2e",
         }
    }

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.

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);
               });


            });

So when I call gulp directly like

          gulp e2e --suite HomePageTests

it gets printed as

           suite: HomePageTests

But if i use

            npm test --suite HomePageTests

It fails as it prints gulp e2e HomePageTests

questions

  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 }

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

Thanks!!

回答1:

You could use the yargs dependence

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

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

gulp test --arg HomePageTests

it will output on console HomePageTests