javascript - 如何使用导入构造函数的外部库的 Jest 来测试模块

标签 javascript node.js testing jestjs pdfmake

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

最佳答案

你几乎就在那里,如果你想模拟一个 Node 模块的构造函数(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

关于javascript - 如何使用导入构造函数的外部库的 Jest 来测试模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59250480/

相关文章:

node.js - 如何使用 Sails.js/Waterline 以多对多的方式将模型与其自身关联?

c# - 集成测试入门

javascript - 如何将Angular Material md-datepicker的日期值初始化为任意指定日期

javascript - Crossrider - 如何触发页面中用户事件的事件?

javascript - 将声音(wav)文件从 objective-c 传递到 javascript

node.js - 如何在 express 上配置 ssl

node.js - Azure blob sasToken "Signature did not match"

python - 如何配置 pycharm/intellij idea 来运行 tox 测试

html - 机器人框架下载文件

javascript - 如何访问 $FirebaseArray 中的各个元素而不等待 $loaded?