0

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

2 Answers2

1

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)
}
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)

Alex028502
  • 3,486
  • 2
  • 23
  • 50