我的问题是:我必须测试一个路由,它可以丰富文件并使它们可下载。我的问题是,我不能在我的测试中得到充实的文件。
我设法用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
}