gpt4 book ai didi

javascript - 对回调中可访问的相同数据进行多个单元测试

转载 作者:行者123 更新时间:2023-12-03 02:31:47 24 4
gpt4 key购买 nike

我实现了一个解析器来从 Excel 文件中提取数据并返回具有特定结构的对象。为了使代码异步工作,我使用了一个简单的回调方案来进一步处理提取的数据:

parse(inputFile, callback) {
const workbook = new Excel.Workbook();
workbook.xlsx.readFile(inputFile).then((workbook) => {
// Parsing
callback(result);
});
}

现在我想使用 MochaChai 为此例程编写一个单元测试。当然,我可以简单地将 expect() 语句放在回调函数中:

const ExcelParser = require('ExcelParser');
var chai = require("chai");
const expect = chai.expect;

describe('Unit::Test parsing', () => {
const excelParser = new ExcelParser();

it('should parse the data correctly', (done) => {
excelParser.parse('sheet.xlsx', (data) => {
expect(data).to.have.property('mainContent');
expect(data['mainContent']).to.be.an('array');
});

done();
});

});

这工作正常,但我想在单独的 it() block 中为返回的数据对象编写更多测试。通过这种方式,将对每个子测试重复解析

我尝试将 parse() 的调用放在 before() block 中,并定义一个回调方法,将结果对象存储在全局变量中,但显然运行测试时解析尚未完成。

如果可能的话,最好的方法是什么?如果 parse() 方法返回 Promise 而不是使用回调,会有帮助吗?

最佳答案

您应该能够通过在 before block 中传递 done 进行解析来实现此目的。然后照常在 it 语句中进行测试,

const ExcelParser = require('ExcelParser');
var chai = require("chai");
const expect = chai.expect;

describe('Unit::Test parsing', () => {
const excelParser = new ExcelParser();
let data = null;

before((done) => {
excelParser.parse('sheet.xlsx', (result) => {
data = result;
done();
});
})

it('should parse the data correctly', () => {
expect(data).to.have.property('mainContent');
expect(data['mainContent']).to.be.an('array');
});

it('should have prop foo', () => {
expect(data).to.have.property('foo');
});

...

});

假设 excelParser.parse 返回一个 promise ,您不需要将 done 传递给 before:

 before(() => {
return excelParser.parse('sheet.xlsx')
.then((result) => {
data = result;
});
})

关于javascript - 对回调中可访问的相同数据进行多个单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48705078/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com