如何使用导入构造函数的外部库的玩笑来测试模块

How to test a module using jest which imports an external library which is a constructor

我正在使用一个库,"pdfmake"并且我想使用 jest 编写测试用例。 我有一个模块pdf。在模块 pdf 中,我正在导出 2 个函数。在这两个导出中,我都使用 "pdfmake" 的内部函数来生成 pdf。

这是代码片段: pdf.js

const PdfPrinter = require("pdfmake");
const fonts = require("./../shared/fonts");

const printer = new PdfPrinter(fonts);

const intiateDocCreation = docDefinition =>
  printer.createPdfKitDocument(docDefinition);

const finishDocCreation = (pdfDoc, pdfStream) => {
  pdfDoc.pipe(pdfStream);
  pdfDoc.end();
};
module.exports = {
  intiateDocCreation,
  finishDocCreation
};

我尝试使用

const PdfPrinter = require("pdfmake");
jest.mock("pdfmake", () => {
  return {
    createPdfKitDocument: jest.fn().mockImplementation(() => ({ a: "b" }))
  };
});

describe("test", () => {
  test("pdf", () => {
    const printer = new PdfPrinter(fonts);
    printer.createPdfKitDocument();
    expect(printer.createPdfKitDocument).toHaveBeenCalledTimes(1);
  });
});

Jest报错:

TypeError: PdfPrinter is not a constructor

你快完成了,如果你想模拟节点模块的构造函数(pdfmake),你需要 return jest.fn() 在 [=15] 的工厂函数中=].

例如 pdf.js:

const PdfPrinter = require('pdfmake');
// const fonts = require('./../shared/fonts')
const fonts = {};

const printer = new PdfPrinter(fonts);

const intiateDocCreation = (docDefinition) => printer.createPdfKitDocument(docDefinition);

const finishDocCreation = (pdfDoc, pdfStream) => {
  pdfDoc.pipe(pdfStream);
  pdfDoc.end();
};

module.exports = {
  intiateDocCreation,
  finishDocCreation,
};

pdf.test.js:

const PdfPrinter = require('pdfmake');

jest.mock('pdfmake', () => {
  const mPdfMake = {
    createPdfKitDocument: jest.fn().mockImplementation(() => ({ a: 'b' })),
  };
  return jest.fn(() => mPdfMake);
});

describe('test', () => {
  test('pdf', () => {
    const fonts = {};
    const printer = new PdfPrinter(fonts);
    printer.createPdfKitDocument();
    expect(printer.createPdfKitDocument).toHaveBeenCalledTimes(1);
  });
});

单元测试结果:

 PASS  src/Whosebug/59250480/pdf.test.js (12.04s)
  test
    ✓ pdf (6ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        13.694s