如何在异步函数上运行Jest测试

时间:2019-11-25 07:30:34

标签: asynchronous promise jestjs

我有一个功能,可以在目录中找到一个zip文件并解压缩该文件,它可以正常工作。但是,我想知道如何使用Jest在此功能上运行测试。

var fs = require('fs'),
    PNG = require('pngjs').PNG
const unzipper = require('unzipper')
PNG = require('pngjs').PNG
const dir = __dirname + "/";

function unzipFile(fileName, outputPath) {
  return new Promise((resolve, reject) => {
    if (fs.existsSync(fileName) !== true) {
      reject("there is no zip file");
    }
    const createdFile = dir + fileName;
    const stream = fs
      .createReadStream(createdFile)
      .pipe(unzipper.Extract({ path: outputPath }));

    stream.on("finish", () => {
      console.log("file unzipped");
      resolve(outputPath);
    });
  });
}

我已经阅读了文档并尝试使用.then,但是我不确定使用Jest时的预期输出会是什么样。

1 个答案:

答案 0 :(得分:0)

这是单元测试解决方案:

index.js

const fs = require("fs");
const unzipper = require("./unzipper");
const dir = __dirname + "/";

function unzipFile(fileName, outputPath) {
  return new Promise((resolve, reject) => {
    if (fs.existsSync(fileName) !== true) {
      reject("there is no zip file");
    }
    const createdFile = dir + fileName;
    const stream = fs
      .createReadStream(createdFile)
      .pipe(unzipper.Extract({ path: outputPath }));

    stream.on("finish", () => {
      console.log("file unzipped");
      resolve(outputPath);
    });
  });
}

module.exports = unzipFile;

index.spec.js

const unzipFile = require("./");
const fs = require("fs");
const unzipper = require("./unzipper");

jest.mock("fs", () => {
  return {
    existsSync: jest.fn(),
    createReadStream: jest.fn().mockReturnThis(),
    pipe: jest.fn()
  };
});

describe("unzipFile", () => {
  afterEach(() => {
    jest.restoreAllMocks();
    jest.resetAllMocks();
  });
  it("should unzip file correctly", async () => {
    const filename = "go.pdf";
    const outputPath = "workspace";
    const eventHandlerMap = {};
    const mStream = {
      on: jest.fn().mockImplementation((event, handler) => {
        eventHandlerMap[event] = handler;
      })
    };
    const logSpy = jest.spyOn(console, "log");
    fs.existsSync.mockReturnValueOnce(true);
    fs.createReadStream().pipe.mockReturnValueOnce(mStream);
    jest.spyOn(unzipper, "Extract").mockReturnValueOnce({});
    const pending = unzipFile(filename, outputPath);
    eventHandlerMap["finish"]();
    const actual = await pending;
    expect(actual).toEqual(outputPath);
    expect(fs.existsSync).toBeCalledWith(filename);
    expect(fs.createReadStream).toBeCalled();
    expect(fs.createReadStream().pipe).toBeCalledWith({});
    expect(logSpy).toBeCalledWith("file unzipped");
    expect(mStream.on).toBeCalledWith("finish", eventHandlerMap["finish"]);
  });
});

带有覆盖率报告的单元测试结果:

 PASS  src/stackoverflow/59027031/index.spec.js
  unzipFile
    ✓ should unzip file correctly (10ms)

  console.log node_modules/jest-mock/build/index.js:860
    file unzipped

-------------|----------|----------|----------|----------|-------------------|
File         |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-------------|----------|----------|----------|----------|-------------------|
All files    |    92.31 |       50 |       75 |    92.31 |                   |
 index.js    |    91.67 |       50 |      100 |    91.67 |                 8 |
 unzipper.js |      100 |      100 |        0 |      100 |                   |
-------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        5.618s, estimated 9s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59027031