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

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


当前回答

这个答案确实适用于ES6。

而不是:

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

你想要的:

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

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

或者,代替:

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

你想要的:

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

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

其他回答

我们可以编写一个整洁的包装器函数来有条件地运行测试,如下所示:

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

正如@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 --config ./config/parallelrc.cjs --parallel --jobs 3 -- tests/spec/**/index.js -g @flaky -i

我们在测试描述中标记flaky测试@flaky,并设置特殊的-g规则,这意味着mocha只运行带有@flaky标签的测试,接下来使用-i -它意味着反转,因此mocha只运行测试而不是@flaky。

所以,我认为这对你很有用)

假设我想跳过我的参数化测试,如果我的测试描述包含字符串“foo”,我会这样做:

// Skip parametrized test if description contains the string "foo"
(test.description.indexOf("foo") === -1 ? it : it.skip)("should test something", function (done) {
    // Code here
});

// Parametrized tests
describe("testFoo", function () {
        test({
            description: "foo" // This will skip
        });
        test({
            description: "bar" // This will be tested
        });
});

在你的例子中,我相信如果你想检查环境变量,你可以使用NodeJS的:

process.env.ENV_VARIABLE

例如(警告:我还没有测试这段代码!),可能是这样的:

(process.env.NODE_ENV.indexOf("prod") === -1 ? it : it.skip)("should...", function(done) {
    // Code here
});

您可以将ENV_VARIABLE设置为您要关闭的任何值,并使用该值,跳过或运行测试。(供参考NodeJS进程的文档。Env在这里:https://nodejs.org/api/process.html#process_process_env)

我不会把这个解决方案的第一部分完全归功于我,我找到并测试了答案,它可以通过这个资源完美地跳过基于简单条件的测试:https://github.com/mochajs/mocha/issues/591

希望这能有所帮助!:)

对于您所描述的相同场景,我使用Mocha的运行时跳过。它是从文档中复制粘贴的:

it('should only test in the correct environment', function() {
  if (/* check test environment */) return this.skip();

  // make assertions
});

如您所见,它跳过了基于环境的测试。我自己的条件是if(process.env。NODE_ENV === '持续集成')。