【发布时间】:2020-05-25 20:18:09
【问题描述】:
我有一个脚本来循环目录并匹配具有特定类型的文件。不幸的是,jest 在它结束之前通过了这个测试。我知道为什么,但我不知道如何让脚本等待循环结束。
import fs from 'fs'
const path = require('path');
describe('something', () => {
it('should something', () => {
const traverseDir = (dir, callback) => {
fs.readdirSync(dir).forEach(file => {
let fullPath = path.join(dir, file);
if (fs.lstatSync(fullPath).isDirectory()) {
callback(fullPath)
traverseDir(fullPath, callback);
} else {
callback(fullPath)
}
});
}
traverseDir('src/', (fullPath) => {
const splitted = fullPath.split('/')
const filename = splitted[splitted.length - 1]
if (filename.match(/.*.foo/)) {
fs.readFile(fullPath, 'utf8', (err, data) => {
expect(err).toBe(null)
// some assertion
})
}
})
})
})
【问题讨论】:
-
你读过关于在 Jest 中测试异步代码的文章吗? jestjs.io/docs/en/asynchronous
标签: javascript unit-testing asynchronous testing jestjs