您可以利用节点process.argv 从名为createSpec.js 的文件中读取参数(即user 或session)。
要更好地了解如何操作,请按以下步骤操作:
-
在createSpec.js 的顶部添加以下代码行:
console.log(process.argv);
-
然后通过您的 CLI 运行 grunt e2etest:user,您应该会看到以下记录到您的控制台:
[ 'node', '/usr/local/bin/grunt', 'e2etest:user' ]
注意:您想要的信息位于数组的索引二处。
现在,从createSpec.js 中删除我们刚刚添加的console.log(process.argv); 行。
createSpec.js
因此,上述步骤 (1-3) 说明了参数(user 或 session)可以使用 process.argv 在 createSpec.js 中访问。在这种情况下,您可以在 createSpec.js 中执行以下操作。
const argument = process.argv[2].split(':').pop();
if (argument === 'user') {
// Run `user` specific tests here...
} else if (argument === 'session') {
// Run `session` specific tests here...
}
注意,我们使用 process.argv[2].split(/:/).pop(); 从位于索引 2 的数组项中提取 user 或 session,其初始值将分别为 e2etest:user 或 e2etest:session。
Gruntfile
您的 createSpec.js 文件现在在某种程度上依赖于正确调用名为 e2etest 的 grunt 任务。例如,如果用户在不提供参数的情况下运行 grunt e2etest,那么 createSpec.js 不会做太多事情。
要强制正确使用e2etest 任务(即它必须使用grunt e2etest:user 或grunt e2etest:session 运行),您可以在Gruntfile 中更改您的任务,如下所示:
grunt.registerTask('e2etest', function(scope) {
if (!scope || !(scope === 'user' || scope === 'session')) {
grunt.warn(`Must be invoked with: ${this.name}:user or ${this.name}:session`);
}
grunt.task.run('mochaTest');
});
上面的 gist 最初检查参数是否已提供,并且是 user 或 session。如果参数不正确或丢失,则使用grunt.warn 警告用户。
如果您的 nodejs 版本不支持ES6 Template literals,请改用grunt.warn,如下所示:
grunt.warn('Must be invoked with: ' + this.name + ':user or ' + this.name + ':session');
补充评论
如果您的用例与您在问题中提到的完全一样,上面 createSpec.js 部分中显示的代码/要点将起作用。 IE。您可以使用grunt e2etest:user 或grunt e2etest:session 通过命令行调用。但是,如果这种情况发生变化并且您不能保证 e2etest:user 或 e2etest:session 将准确定位在 process.argv 数组的索引 2 处,那么您可能需要在 createSpec.js 的顶部执行以下操作:
// Return the value in the array which starts with
// `e2etest` then extract the string after the colon `:`
const argument = process.argv.filter(arg => {
return arg.match(/^e2etest:.*/);
}).toString().split(':').pop();
if (argument === 'user') {
// Run `user` specific tests here...
} else if (argument === 'session') {
// Run `session` specific tests here...
}