我有一个代码,其中某些测试在CI环境中总是失败。我想根据环境条件禁用它们。
如何在运行时执行期间以编程方式跳过mocha测试?
我有一个代码,其中某些测试在CI环境中总是失败。我想根据环境条件禁用它们。
如何在运行时执行期间以编程方式跳过mocha测试?
当前回答
正如@danielstjules在这里回答的,有一种跳过测试的方法。@本主题的作者从github.com mochajs的讨论中复制了答案,但没有关于哪个版本的mocha可用的信息。
我正在使用咕哝摩卡测试模块集成摩卡测试功能在我的项目。跳转到最后一个(现在)版本- 0.12.7带来了mocha 2.4.5版本,实现了this.skip()。
在package。json中
"devDependencies": {
"grunt-mocha-test": "^0.12.7",
...
然后
npm install
这个钩子让我很开心:
describe('Feature', function() {
before(function () {
if (!Config.isFeaturePresent) {
console.log('Feature not configured for that env, skipping...');
this.skip();
}
});
...
it('should return correct response on AB', function (done) {
if (!Config.isABPresent) {
return this.skip();
}
...
其他回答
mocha test/ --grep <pattern>
https://mochajs.org/
我们可以编写一个整洁的包装器函数来有条件地运行测试,如下所示:
function ifConditionIt(title, test) {
// Define your condition here
return condition ? it(title, test) : it.skip(title, test);
}
然后可以在您的测试中要求并按以下方式使用:
ifConditionIt('Should be an awesome test', (done) => {
// Test things
done();
});
使用Mocha的skip()函数
它可以用来静态地禁用测试或整个套件,也可以在运行时动态地跳过它。
下面是一个运行时用法的例子:
it('should only test in the correct environment', function() {
if (/* check test environment */) {
// make assertions
} else {
this.skip();
}
});
我不确定这是否可以称为“程序性跳过”,但是为了有选择性地跳过我们CI环境中的某些特定测试,我使用了Mocha的标记功能(https://github.com/mochajs/mocha/wiki/Tagging)。 在describe()或it()消息中,可以添加@no-ci这样的标记。要排除这些测试,可以在包中定义特定的“ci目标”。使用——grep和——invert参数,如下:
"scripts": {
"test": "mocha",
"test-ci" : "mocha --reporter mocha-junit-reporter --grep @no-ci --invert"
}
要跳过测试,请使用describe。Skip还是it.skip
describe('Array', function() {
it.skip('#indexOf', function() {
// ...
});
});
以包括您可以使用描述的测试。Only或it.only
describe('Array', function() {
it.only('#indexOf', function() {
// ...
});
});
更多信息请访问https://mochajs.org/#inclusive-tests