有条件地异步执行摩卡测试

时间:2019-04-05 06:56:30

标签: javascript mocha

如果条件是异步函数调用,如何有条件地执行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()更改为执行同步功能调用,则该代码有效。

1 个答案:

答案 0 :(得分:1)

Mocha run cycle运行所有describe回调并同步收集测试,因此只能使用可同步使用的条件在it和{{1 }}在it.skip回调执行期间。

  

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

Mocha provides .skip()至...

  

...告诉Mocha简单地忽略这些套件和测试用例。

可以在describe中使用

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

});