0

不确定标题是否正确,因为我很困惑(在我的头上)......

作为自动化测试的一部分,我正在尝试从 csv 中提取标头以验证这些标头。我正在使用 csv-parse 来读取 csv 文件。

一旦我收集了标题,我就会做一个简单的断言来检查每个标题。使用我在测试脚本中输入的字符串值。

然而目前,FOR 是在 csv 读取和标题被收集之前执行的。我不确定如何在执行循环之前等待它完成。

const fs = require('fs');
const csv = require('csv-parser');
let headerArray = null;
const headerValues = values.split(',');
browser.pause(10000);
fs.createReadStream(""+global.downloadDir + "\\" + fs.readdirSync(global.downloadDir)[0])
  .pipe(csv())
  .on('headers', function (headers) {
    return headerArray = headers
  })
for(var i =0; i<headerValues.length; i++){
 assert.equal(headerValues[i], headerArray[i]);
}

4

1 回答 1

1

解决方案是在事件处理程序中使用您的断言运行for循环,例如:'headers'

var results = [] // we'll collect the rows from the csv into this array

var rs = fs.createReadStream(""+global.downloadDir + "\\" + fs.readdirSync(global.downloadDir)[0])
  .pipe(csv())
  .on('headers', function (headers) {
    try {
      for(var i =0; i<headerValues.length; i++){
        assert.equal(headerValues[i], headers[i]);
      }
    } catch (err) {
      // an assertion failed so let's end
      // the stream (triggering the 'error' event)
      rs.destroy(err)
    }
  }).on('data', function(data) {
    results.push(data)
  }).on('end', function() {
    //
    // the 'end' event will fire when the csv has finished parsing. 
    // so you can do something useful with the `results` array here...
    //
  }).on('error', function(err) {
    // otherwise, the 'error' event will have likely fired.
    console.log('something went wrong:', err)
  })
于 2020-11-17T15:09:36.297 回答