我有一些异步(I/O绑定)任务要做,然后我想用Chai来assert返回的值。而不是写像这样的一段代码:
expect(await taskA.someAsync()).to.be.eq(something); expect(await taskB.someAsync()).to.be.eq(something);
我想要等待所有任务完成,使用await Promise.all([taskA.someAsync(), taskB.someAsync()]),然后逐个expect或assert结果。
我创建了这个函数(伪代码)来使事情更通用:
type TransactionInfo = {
txn: Promise<any>; // 要等待的异步任务
assertion: Chai.Assertion // 要在txn结果上运行的断言
}
const assertAll = async function(...txns: TransactionInfo[]) {
let values = await Promise.all(allTxns);
for (let txnInfo of txns) {
evaluate(txnInfo.assertion)
}
}
这个函数的作用是await所有的txns,然后对每个txn运行每个assertion来验证返回的值。
首先,我不确定Chai.Assertion类型对于assertion是否正确。其次,我不知道如何实例化一个包含不同类型断言(如eq或have.lengthOf)的TransactionInfo数组。最后,我不知道如何在以后评估assertion对象。
P.S. 我不是一个专业的JavaScript开发者。请友善点:)
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
import { expect } from 'chai'; type TransactionInfo = { txn: Promise<any>; // 要等待的异步任务 assertion: () => void; // 表示要在txn结果上运行的断言函数 }; const assertAll = async function (...txns: TransactionInfo[]) { let values = await Promise.all(txns.map((txnInfo) => txnInfo.txn)); txns.forEach((txnInfo, index) => { txnInfo.assertion(values[index]); }); };使用这段代码,现在可以创建一个TransactionInfo对象的数组,每个对象都有自己的自定义断言函数:
// 示例用法: const txn1: TransactionInfo = { txn: someAsyncTaskA(), assertion: (result) => { expect(result).to.be.eq(something); }, }; const txn2: TransactionInfo = { txn: someAsyncTaskB(), assertion: (result) => { expect(result).to.have.lengthOf(3); }, }; // 使用TransactionInfo对象数组调用assertAll函数 await assertAll(txn1, txn2);