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

问题描述 投票:1回答:1

我正在使用一个库“ 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);
  });
});

开玩笑给出一个错误:

TypeError:PdfPrinter不是构造函数

javascript node.js testing jestjs pdfmake
1个回答
0
投票

[您快到了,如果要模拟节点模块(pdfmake)的构造函数,则需要在jest.fn()的工厂函数内返回jest.mock

例如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/stackoverflow/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
© www.soinside.com 2019 - 2024. All rights reserved.