[英]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 报错:
类型错误:PdfPrinter 不是构造函数
你是几乎没有,如果你想嘲笑一个节点模块(的构造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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.