我有一个小函数,设计来解压缩文件使用'unzipper'和提取到一个给定的位置。
当单元测试函数超时时,我使用jest进行单元测试。
请参阅以下代码:
exports.unzipFile = async (folderPath) => {
return new Promise((resolve, reject) => {
fs.createReadStream(folderPath)
.pipe(unzipper.Extract({ path: tmpPath+ path.parse(folderPath).name })).on('close', () => resolve()).on('error', (error) => reject(error))
})
函数本身按预期工作。我已经尝试了一些改变函数,但这似乎打破了函数。我需要这个函数完全执行,因为解压缩的文件,然后依赖于后面的程序。
该程序是在节点16中编写的。如有任何帮助,将不胜感激,谢谢
编辑:这是我当前的单元测试-我已经尝试了各种方法:
const { PassThrough } = require('stream')
const os = require('os');
const unzipper = require("unzipper")
const fs = require("fs")
let tmpdir, mockReadStream
beforeEach(() => {
tmpdir = os.tmpdir() + "/uploadFolder/";
if (!fs.existsSync(tmpdir)){
fs.mkdirSync(tmpdir);
}
fs.writeFileSync(tmpdir+"tempfile.zip", "file to be used")
mockReadStream = new PassThrough()
})
afterEach(() => {
// Restore mocks
jest.clearAllMocks()
})
describe('Test helper.js unzip method', () => {
test('should be able to unzip file ', async () => {
jest.isolateModules(() => {
helper = require('helper')
})
const result = await helper.unzipFile(tmpdir+"tempfile.zip")
console.log(result)
})
})
1条答案
按热度按时间brccelvz1#
您需要进行一些小的更改以对其进行测试
在helper.js中
1.将unzipFile函数的签名更改为
unzipFile = async (zipFilePath, outputDir)
然后您需要创建一个简单的zip文件,并将其添加到您的本地测试目录中
在我的示例中,我创建了一个简单的zip文件
1.txt.zip
,其中包含字符串为hello
的文本文件那么您的测试应该如下所示