Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

268
Views
Mocking html-pdf using Jest

I am using the html-pdf package in my nodejs code (not in Typescript). Now, this package has a create() function which is chained with the toBuffer() function. I am unit testing my code using Jest and want to mock this call pdf.create(html).toBuffer().

var pdf = require('html-pdf');
pdf.create(html).toBuffer(function(htmlToPdfError, buffer){
  if (htmlToPdfError) {
    reject(htmlToPdfError);
  }
  resolve(buffer.toString('base64'));
});

EDIT: I am trying to use the following code in my spec file to make the module:

jest.mock('html-pdf', () => ({
    create: jest.fn(() => {
        return Promise.resolve();
    })
}));

This is helping me mock the create() function but I do not know how to return a object in Promise.resolve which would have a toBuffer function

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

will this work?

and then assert that your "pdf" buffer contains "test string"?

jest.mock('html-pdf', () => ({
  create: jest.fn(() => {
    return Promise.resolve({
      toBuffer: function(callback) {
        callback(null, Buffer.from("test string", "utf-8"));
      },
    });
  })
}));

(I haven't tried it)

about 4 years ago · Juan Pablo Isaza Report

0

I could mock it using the following code:

const mockToBuffer = {
    toBuffer: jest.fn((callback: Function) => callback(null, null)),
}

jest.mock('html-pdf', () => ({
    create: jest.fn(() => mockToBuffer),
}))

it('Should work', async () => {
    const expectedResult = Buffer.from([10])

    mockToBuffer.toBuffer.mockImplementation((callback: Function) => {
        callback(null, expectedResult)
    })

    // const result = await yourFuncUsingHtmlPdf(/* fakePayload */)

    // Comparing the buffer using the native function
    // expect(expectedResult.equals(result)).toBe(true)
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!