gpt4 book ai didi

node.js - 动态生成的 Mocha 测试不在异步/等待上下文中执行

转载 作者:搜寻专家 更新时间:2023-11-01 00:50:05 25 4
gpt4 key购买 nike

我无法运行我的 Mocha 测试。我需要测试的部分内容是我以异步方式(从远程服务器)获取的,由我的 getStatus() 函数返回(为简单起见用超时替换)。我有一个没有 async/await 的类似代码示例,它工作正常(如果需要,也可以提供 repl.it)。

简化代码(你可以玩一下 here on repl.it ):

const sleep = require('util').promisify(setTimeout);

const getStatus = async function() {
await sleep(1000);
return 2;
};

describe('main describe', async function () {
let uids = [1,2,3];

describe('Tha test!', async function () {
console.info('started describe() block...');

let outcome;
let status;

const callback = function () {
console.info(`inside callback, status is ${status} and outcome is ${outcome}`);
expect(status).to.equal(outcome);
};

for(let uid in uids) {
status = await getStatus(uids[uid]);
console.info('the status returned by getStatus is:', status);
it(`The status for ${uids[uid]} should be ${outcome}`, callback);
}
});
});

注意:it() 子句中的回调的灵感来自 this question .

输出:

started describe() block...

0 passing (0ms)

the status returned by getStatus is: 2
the status returned by getStatus is: 2
the status returned by getStatus is: 2

预期输出:

started describe() block...

the status returned by getStatus is: 2
the status returned by getStatus is: 2
the status returned by getStatus is: 2

1) number 0 should equal 2
2) number 1 should equal 2
✓ number 2 should equal 2

1 passing (11ms)
2 failing

问题:为什么我的 it() 子句没有执行?

最佳答案

事实证明,您不能将 async 回调传递给 describe()。谁知道。

为了让所有的异步功能正常工作,应该怎么做:

describe('do not put async before the function keyword!', function () {
uids = process.env.ENV_OBJECTS.split(',');

let outcome;

for(let uid in uids) {
it('Can safely put async before the function here', async function() {
outcome = await getOutcome(uid);
// etc.
});
}
});

关于node.js - 动态生成的 Mocha 测试不在异步/等待上下文中执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53327275/

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