我正在通过Jest在Node中编写测试,在其中我读取了一堆CSV文件,解析了一个特定的列,将其放入一个集合中,然后针对该集合验证计数器以确定是否存在重复。
但是,将CSV值解析为设置它的操作相当冗长(3-4分钟)。然而,Jest并不等待它:它只是立即通过测试。
示例代码:
describe('Test that all values are unique', () => {
let validationCounter = 0
const validationSet = new Set([])
it('Read all csv files', () => {
for (const number of dirsToCheck.keys()) {
const baseDest = baseDir + "/something" + number
Filehound.create()
.ext('csv')
.paths(baseDest)
.find((err, csvFiles) => {
if (err) {
return console.error("handle err", err)
} else {
for (file of csvFiles) {
csv({
flatKeys: true,
})
.fromFile(file)
.on("json", (jsonObj) => {
const designatedValue = Object.values(jsonObj).toString().split(';')[2]
validationSet.add(designatedValue)
validationCounter++
console.log(designatedValue) // Will make everything "hang" until this is finished, if logged
})
}
}
});
}
})
it('Validate array counter to the unique set', () =>{
console.log(validationCounter) // Returns 0?
console.log(validationSet.size) // Also 0?
expect(uniqueVurderingsejendomsIds.size).toBe(validationCounter); // Somehow passes?
})
});
如果我console.log(designatedValue)
,它将持续整个四分钟,然后一旦它完成添加到集合后退出 - 不运行测试。
如果我删除这个console.log语句,Jest几乎可以立即通过整个测试套件(2秒)
发生了什么,为什么Jest不等待这个操作?它立即通过所有测试,然后Jest挂起而没有退出。这是非常奇怪的行为。
它不会自动等待。
如果你正在进行任何异步操作,你需要向你的测试发出信号,否则测试会假定同步代码,“冲过”它,发现没有错误并认为它是成功的。
这是通过在done
回调中指定test
参数然后在实际完成异步处理时调用该参数来完成的。
来自Jest: Testing Asynchronous Code:
还有一种替代形式的测试可以解决这个问题。不要将测试放在具有空参数的函数中,而是使用名为done的单个参数。在完成测试之前,Jest将一直等到完成回调。
describe('fetchData', () => {
it('callback with peanut butter', done => {
fetchData((err, result) => {
if (err) {
// calling `done` with an argument assumes an error
// and fails the test
return done(err)
}
expect(result).toBe('peanut butter')
done()
})
})
})
function fetchData(cb) {
setTimeout(() => {
cb(null, 'peanut butter')
}, 200)
}
在尝试此操作之前,请确保您拥有最新版本的Jest。在Jest中有used to be a bug会导致超时。