Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

269
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda