Generate Excel file from Request Response using Supertest & Jest

Viewed 465

I want to access an Excel file contained in response.text to check its content in supertest.

There is a function in my Nodejs backend which returns a generated Excel file. If I trigger the file generation from my React client, all works as expected; i.e. after saving the file, I can open it with Excel and everything looks as expected.

Where I need help is to write a test with Jest and supertest. I tried to save the data received in response.text using the Nodejs file system module like so:


it('File Upload: Export project succeeds', async () => {
 const response = await request(app)
    .get(`/api/project/${project.id}/export`)
    .set('Cookie', global.signin())
    .expect(
      'Content-Type',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    )
    .expect(200);

  expect(response.text).toBeDefined();

  await saveFile(response.text);
});

const saveFile = (data: any) => {
  return new Promise((resolve, reject) => {
    fs.writeFile('my_excel_file.xlsx', data, function (err) {
      if (err) {
        reject(err);
      }
      const successObject = {
        msg: 'success',
        data: 'successfully stored file',
      };
      resolve(successObject);
    });
  });
};

The file is generated just fine but when I try to open it, Excel says there is a problem with the content and aborts.

Here is how I send the file in my backend:

fileUploadRouter.get(
  '/api/project/:id/export/',
  requireAuth,
  validateUserRole(UserRoles.BASIC),
  async (req: Request, res: Response) => {

  ...

  await workbook.xlsx.writeFile(file);

  res.setHeader('Content-disposition', 'attachment; filename=' + filename);
  res.contentType(
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  );

  res.download(file, filename, (err) => {
    if (err) {
      console.log(err);
      }
  });
}

I assume the the data in response.text is valid as the download works if triggered from the client.

Multer and similar tools were written for file multipart/form-data file uploads. As the file content is in the response body, these tools are not required.

My best guess it is some encoding issue but I'm just fishing here.

Any help/advice is much appreciated.

0 Answers
Related