【问题标题】:How to test express controller fetching a file with Jest如何测试快速控制器使用 Jest 获取文件
【发布时间】:2022-10-17 13:11:19
【问题描述】:

我有一个使用 Express 的简单端点,允许用户下载 csv 文件。 我应该如何仅使用 Jest 对文件下载端点进行测试

我不确定应该使用哪个函数或模拟来测试这种情况,因为它返回 Number of calls: 0 以进行以下测试

控制器.js

const getFile = async (req, res, next) => {
try {
    res.setHeader('Content-Type', 'text/csv');
    res.setHeader('Content-Disposition', 'attachment; filename=sample.csv');
    const csv = 'ID\n1\n2\n3';
    res.send(csv);
  } catch (e) {
    next(
      new HttpException(
        'internal error',
        'file download error',
        e.message,
      ),
    );
  }
}

控制器.test.js

test('should successfully download the csv', async () => {
      const mockReq = {};
      const mockRes = {
        send: jest.fn(),
      };
      await controller.getFile(mockReq, mockRes, jest.fn());
      
      expect(mockRes.send).toHaveBeenCalledWith({ 'Content-Type': 'text/csv' });
});

【问题讨论】:

  • 不确定您要做什么。你的getFile 没有返回任何东西,也没有调用next()(开玩笑的回调),它不应该这样,否则你会得到一个错误。你在这里有一些奇怪的实现。
  • 应该是expect(mockRes.send).toHaveBeenCalledWith('ID\n1\n2\n3')

标签: express jestjs


【解决方案1】:

如果有人像我一样遇到类似的问题,我认为最简单的方法是使用 supertest 库。这个库支持HTTP assertions,所以我可以在路由级别进行测试:

const request = require('supertest');
...

const response = await request(app).get(
        '/api/.../download-file',
      );
expect(response.status).toEqual(200);
expect(response.headers['content-type']).toMatch('text/csv; charset=utf-8');
expect(response.headers['content-disposition']).toMatch(
        'attachment; filename=' + 'sample.csv',
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-27
    • 2019-05-23
    • 2021-02-03
    • 2019-08-23
    • 2018-12-23
    • 2017-08-13
    • 2020-09-02
    • 2017-09-19
    相关资源
    最近更新 更多