单元测试unzip方法节点/jest时出现问题

5hcedyr0  于 2022-12-08  发布在  Jest
关注(0)|答案(1)|浏览(145)

我有一个小函数,设计来解压缩文件使用'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)
  })
})
brccelvz

brccelvz1#

您需要进行一些小的更改以对其进行测试
在helper.js中
1.将unzipFile函数的签名更改为unzipFile = async (zipFilePath, outputDir)

const unzipper = require("unzipper")
const fs = require("fs")

const unzipFile = async (zipFilePath, outputDir) => {
    return new Promise((resolve, reject) => {
        fs
            .createReadStream(zipFilePath)
            .pipe(unzipper.Extract({ path: outputDir }))
            .on('close', () => resolve())
            .on('error', (error) => reject(error))
    })
}

module.exports = { unzipFile }

然后您需要创建一个简单的zip文件,并将其添加到您的本地测试目录中
在我的示例中,我创建了一个简单的zip文件1.txt.zip,其中包含字符串为hello的文本文件
那么您的测试应该如下所示

const path = require("path");
const shelljs = require("shelljs");
const helper = require("./helper")
const fs = require("fs")
const testFilesDir = path.join(__dirname, "test");
const outPutDir = path.join(__dirname, "output")

console.log(testFilesDir)
beforeAll((done) => {
  shelljs.mkdir("-p", testFilesDir);
  shelljs.mkdir("-p", outPutDir);
  shelljs.cp("-r", path.join(__dirname, "*.zip"), testFilesDir);
  done();
});

afterAll((done) => {
  shelljs.rm("-rf", testFilesDir);
  done();
});

describe('Test helper.js unzip method', () => {
  test('should be able to unzip file  ', async () => {
    await helper.unzipFile(path.join(testFilesDir, "1.txt.zip"), outPutDir)
    const files = fs.readdirSync(outPutDir)
    expect(files.length).toEqual(1);
    expect(files[0]).toEqual("1.txt");
    const text = fs.readFileSync(path.join(outPutDir,"1.txt"),"utf8")
    expect(text).toEqual("hello");
  })
})

相关问题