有条件地异步执行 mocha 测试

Conditionally asynchronously execute mocha test

如果条件是异步函数调用,我如何有条件地执行 mocha 测试?

我尝试基于 synchronous example 进行异步实现。在下面的两个片段中,我预计 some test 会被执行,因为 asyncCondition() 返回的承诺被解析为 true.

首先,我尝试await条件:

const assert = require('assert');

const asyncCondition = async () => Promise.resolve(true);

describe('conditional async test', async () => {
  const condition = await asyncCondition();

  (condition ? it : it.skip)('some test', () => {
    assert.ok(true);
  });    
});

结果:No tests were found.

接下来,我尝试了一个异步 before 钩子:

const assert = require('assert');

describe('conditional async test', async () => {
  let condition;

  before(async () => {
    condition = await asyncCondition();
  });

  (condition ? it : it.skip)('some test', () => {
    assert.ok(true);
  });
});

结果:Pending test 'some test'.


如果将 const condition = await asyncCondition() 行更改为执行同步函数调用,则代码有效。

Mocha run cycle 运行所有 describe 回调并同步收集测试 ,因此只能使用同步可用条件在 [=13= 之间切换] 和 it.skipdescribe 回调执行期间。

How can I conditionally execute mocha tests based if the condition is an asynchronous function call?

Mocha provides .skip() 到...

...tell Mocha to simply ignore these suite(s) and test case(s).

.skip() 可以在 before 中使用以跳过测试套件中的 所有 测试:

const assert = require('assert');

const asyncCondition = async () => Promise.resolve(false);

describe('conditional async test', function () {

  before(async function () {
    const condition = await asyncCondition();
    if (!condition) {
      this.skip();  // <= skips entire describe
    }
  });

  it('some test', function () {
    assert.ok(true);
  });

});

...或者它可以在单个测试中使用以跳过该测试:

const assert = require('assert');

const asyncCondition = async () => Promise.resolve(false);

describe('conditional async test', function () {

  let condition;
  before(async function () {
    condition = await asyncCondition();
  });

  it('some test', function () {
    if (!condition) this.skip();  // <= skips just this test
    assert.ok(true);
  });

});