I have some asynchronous (I/O bound) tasks to do, and then I want to use Chai
to assert
the returned value. Instead of writing a piece of code like this:
expect(await taskA.someAsync()).to.be.eq(something); expect(await taskB.someAsync()).to.be.eq(something);
I want to wait for all tasks to complete, use await Promise.all([taskA.someAsync(), taskB.someAsync()])
, and then expect
or ## one by one #assertResult.
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) } }What this function does is
awaitall
txns, and then run each
assertion on each txn to verify the returned value.
Chai.Assertion type is correct for
assertion. Secondly, I don't know how to instantiate an array of
TransactionInfo that contains assertions of different types (like
eq or
have.lengthOf). Finally, I don't know how to evaluate the
assertion object later.
P粉6620895212023-09-17 14:13:13
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]); }); };
Using this code, you can now create an array of TransactionInfo objects, each with its own custom assertion function:
// 示例用法: 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);