如何使用 chai-http 下载文件?

How to download a file with chai-http?

这是我的问题:我必须测试一个丰富文件并使它们可下载的路径。我遇到的问题是我在测试期间无法获取丰富的文件。

我设法用 Axios 恢复了这个文件(用于终端命令),但我必须使用 chai-http 进行测试。

router.js

const router = require('express').Router();
const path = require('path');

const { enrichmentFileJSON } = require('../services/enrich/json');

router.post('/enrich/json', async (req, res) => {
  let { args } = req.query;
  await enrichmentFileJSON(req, args);
  return res.status(200).download(path.resolve(tmpDir, 'enriched.jsonl'));
});

testEnrichment.js

const chai = require('chai');
const chaiHttp = require('chai-http');
const fs = require('fs-extra');
const path = require('path');

chai.should();
chai.use(chaiHttp);

const url = 'http://localhost:8080';

describe('/enrich/json enrich a jsonl file', () => {
    it('should return the enriched file', async () => {
      const response = await chai.request(url)
        .post('/enrich/json')
        .attach('fileField', path.resolve(__dirname, 'enrichment', 'file.jsonl'), 'file.jsonl')
        .set('Access-Control-Allow-Origin', '*')
        .set('Content-Type', 'multipart/form-data')

      // i want to use something like this
      const writer = fs.createWriteStream(path.resolve(__dirname, 'tmp', 'enriched.jsonl'));
      response.data.pipe(writer);
    });
  });

提前致谢!

对于"chai-http": "^4.3.0",在response对象上调用.buffer().parse()方法来获取下载文件的缓冲区。

然后,使用stream模块的Readable.from(buffer)将缓冲区转换为可读流。

例如

index.js:

const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();

var upload = multer({ dest: path.resolve(__dirname, 'uploads/') });

app.post('/enrich/json', upload.single('fileField'), async (req, res) => {
  return res.status(200).download(path.resolve(__dirname, 'file.jsonl'));
});

module.exports = app;

index.test.js:

const chai = require('chai');
const chaiHttp = require('chai-http');
const fs = require('fs');
const path = require('path');
const { Readable } = require('stream');
const app = require('./');
chai.use(chaiHttp);

const binaryParser = function (res, cb) {
  res.setEncoding('binary');
  res.data = '';
  res.on('data', function (chunk) {
    res.data += chunk;
  });
  res.on('end', function () {
    cb(null, Buffer.from(res.data, 'binary'));
  });
};

describe('66245355', () => {
  it('should pass', async () => {
    const response = await chai
      .request(app)
      .post('/enrich/json')
      .attach('fileField', path.resolve(__dirname, 'file.jsonl'), 'file.jsonl')
      .set('Content-Type', 'multipart/form-data')
      .buffer()
      .parse(binaryParser);

    const writer = fs.createWriteStream(path.resolve(__dirname, 'enriched.jsonl'));
    Readable.from(response.body.toString()).pipe(writer);
  });
});

file.jsonl,您尝试上传的文件:

{
  'ok': true
}

enriched.jsonl,您丰富下载的文件:

{
  'ok': true
}