Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

265
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda