2

I am using exceljs to generate an excel file with some data in it. I want to write test cases for the function.

Here's the function:

public exportUploadErrors(data: UploadError[]): void {
    const fileName = `lei-upload-errors-${new Date().toISOString()}`;
    const workbook = new Workbook();
    const worksheet: Worksheet = workbook.addWorksheet('Upload Errors');

    const headers = [
      { header: 'LEI ID', key: 'leiId' },
      { header: 'Error Message', key: 'error' },
    ];

    worksheet.columns = headers;

    worksheet.getRow(1).fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'cccccc' },
    };

    worksheet.getRow(1).font = {
      size: 12,
      bold: true,
    };

    // adding data to excel sheet
    data.forEach((error: UploadError) => {
      worksheet.addRow(error);
    });

    workbook.xlsx.writeBuffer().then((leiExportArr) => {
      const blob = new Blob([leiExportArr], {
        type:
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      });

      fs.saveAs(blob, `${fileName}.xlsx`);
    });
  }

When I call the exportUploadErrors method with dummy data, workbook.xlsx.writeBuffer() method doesn't get called and so is fs.saveAs method.

How do I mock these methods?

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Pritam Bohra
  • 3,912
  • 8
  • 41
  • 72

1 Answers1

-3

one of these should work:

await workbook.xlsx.writeFile(filename);

or

const buffer = workbook.xlsx.writeBuffer()
await fs.writeFileSync('file.xlsx', buffer);

doc: https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options

BTW. For generating purposes, I will offer you my lib: xlsx-renderer, which is powered by ExcelJS