typescript - 量角器外部的打字稿和异步初始化
问题描述
我从具有异步行为的CSV
文件中读取了测试配置。csv-parser
当我将解析器包装在 Promise 中并在我的异步it
测试用例中使用它时,配置数据被解析......在“它”之外它没有被解析,因为 describe 支持 no并且不允许顶级await。配置数据包含用于在具有不同参数的循环中在“it”测试用例上运行的测试数据。所以我需要一种方法:async
module: commonjs
- 解决“它”之外的承诺以获取配置数据或
- 在返回配置数据之前找到一种等待
csv-parser
流/管道/打开完成的方法。
export function initCountryMatrixFromCsv() {
return new Promise <Map<string, ShopFunction>>((resolve, reject) => {
const countryShopFunctions = new Map<string, ShopFunction>();
countryShopFunctions.set(ALL_FUNCTIONS, new Map<string, ShopFunction>());
const fs = require('fs');
const csv = require('csv-parser');
const parsedCsv = [];
// behaves async... returns imediately and without the promise countryShopFunctions map is not filled:
fs.createReadStream(__dirname + '/country_matrix.csv')
.pipe(csv({ separator: ',' }))
.on('headers', async (headers) => {
// some header inits
}
)
.on('data', async (data) => await parsedCsv.push(data))
.on('end', async () => {
// init configuration in countryShopFunctions
});
});
describe('E2E-I18N-CMX: test country matrix', () => {
// a promise... await not alowed here
const matrix = initCountryMatrixFromCsv();
// not possible since matrix is a promise
matrix.forEach((shopFunction, roleName) = > {
it('Test ' + role, async (){
// perform test with shopFunction params
// first place to resolve the promise ... but i need it outside the it
const matrix2 = await initCountryMatrixFromCsv();
});
});
});
我尝试了几种带有和不带有 promise 的变体,但是当我不将 Promise 与 await 一起使用时,所有变体都以空地图告终。
解决方案
将初始化函数放在 beforeAll/beforeEach 块中。然后矩阵在每个它中都可用
describe('your test', () => {
let matrix2;
beforeAll(async () => {
matrix2 = await initCountryMatrixFromCsv();
});
it('my test', () => {
expect(matrix2).toBeTruthy(); // do more verifications ...
});
});
还要确保resolve
函数中的承诺。我猜你希望它在 on('end') 中解决