使用 Supertest & Jest 从请求响应生成 Excel 文件

问题描述

我想访问包含在 response.text 中的 Excel 文件以在 supertest 中检查其内容

我的 Nodejs 后端有一个函数可以返回生成的 Excel 文件。如果我从我的 React 客户端触发文件生成,一切都会按预期进行;即保存文件后,我可以用 Excel 打开它,一切都按预期进行。

我需要帮助的地方是使用 Jest 和 supertest 编写测试。我尝试使用 Nodejs 文件系统模块保存在 response.text 中收到的数据,如下所示:


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

文件生成得很好,但当我尝试打开它时,Excel 说内容有问题并中止。

这是我在后端发送文件的方式:

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

我假设 response.text 中的数据是有效的,因为如果从客户端触发下载工作。

Multer 和类似工具是为文件 multipart/form-data 文件上传编写的。由于文件内容在响应正文中,因此不需要这些工具。

我最好的猜测是一些编码问题,但我只是在这里钓鱼。

非常感谢任何帮助/建议。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...