Generate a diverse collection of Chai assertions for future evaluation
P粉593649715
P粉593649715 2023-09-16 23:25:50
0
1
321

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.

I created this function (pseudocode) to make things more general:

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.

First of all, I'm not sure if the

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.S. I am not a professional JavaScript developer. Please be kind :)

P粉593649715
P粉593649715

reply all(1)
P粉662089521
import { expect } from 'chai';

type TransactionInfo = {
  txn: Promise; // 要等待的异步任务
  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);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!