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