【问题标题】:Conditionally asynchronously execute mocha test有条件地异步执行 mocha 测试
【发布时间】:2019-08-27 00:39:12
【问题描述】:

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

我尝试基于synchronous example 进行异步实现。在下面的两个 sn-ps 中,我预计 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() 行更改为执行同步函数调用,则代码有效。

【问题讨论】:

    标签: javascript mocha.js


    【解决方案1】:

    Mocha run cycle 运行所有describe 回调并同步地收集测试,因此在describe 回调期间只能使用同步可用条件在itit.skip 之间切换执行。

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

    Mocha provides .skip() 到...

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-01
      • 1970-01-01
      • 2014-02-08
      • 2020-03-26
      • 1970-01-01
      • 2012-08-22
      • 2018-03-06
      相关资源
      最近更新 更多