我有一个代码,其中某些测试在CI环境中总是失败。我想根据环境条件禁用它们。

如何在运行时执行期间以编程方式跳过mocha测试?


当前回答

您可以通过在describe或it块前面放置x或在其后放置.skip来跳过测试。

xit('should work', function (done) {});

describe.skip('features', function() {});

您还可以通过在测试上放置.only来运行单个测试。例如

describe('feature 1', function() {});
describe.only('feature 2', function() {});
describe('feature 3', function() {});

在这种情况下,只有特征2块会运行。

似乎没有一种通过编程方式跳过测试的方法,但是您可以在beforeEach语句中进行某种检查,并且只在设置了标志的情况下运行测试。

beforeEach(function(){
    if (wrongEnvironment){
        runTest = false
    }
}

describe('feature', function(){
    if(runTest){
         it('should work', function(){
            // Test would not run or show up if runTest was false,
         }
    }
}

其他回答

正如@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();
        }

        ...

您可以通过在describe或it块前面放置x或在其后放置.skip来跳过测试。

xit('should work', function (done) {});

describe.skip('features', function() {});

您还可以通过在测试上放置.only来运行单个测试。例如

describe('feature 1', function() {});
describe.only('feature 2', function() {});
describe('feature 3', function() {});

在这种情况下,只有特征2块会运行。

似乎没有一种通过编程方式跳过测试的方法,但是您可以在beforeEach语句中进行某种检查,并且只在设置了标志的情况下运行测试。

beforeEach(function(){
    if (wrongEnvironment){
        runTest = false
    }
}

describe('feature', function(){
    if(runTest){
         it('should work', function(){
            // Test would not run or show up if runTest was false,
         }
    }
}

这个答案确实适用于ES6。

而不是:

describe('your describe block', () => {

你想要的:

(condition ? describe : describe.skip)('your describe block', () => {

如果条件为假,这将有条件地跳过描述块中的所有测试。

或者,代替:

it('your it block', () => {

你想要的:

(condition ? it : it.skip)('your it block', () => {

如果条件为假,则有条件地跳过一个测试。

我不确定这是否可以称为“程序性跳过”,但是为了有选择性地跳过我们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