gpt4 book ai didi

javascript - 有条件地异步执行 mocha 测试

转载 作者:行者123 更新时间:2023-11-29 23:01:24 24 4
gpt4 key购买 nike

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

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

首先,我尝试等待条件:

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

结果:没有找到测试

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

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

结果:待定测试“一些测试”


如果将 const condition = await asyncCondition() 行更改为执行同步函数调用,则代码可以正常工作。

最佳答案

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

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

});

关于javascript - 有条件地异步执行 mocha 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55529793/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com