使用mocha / chai来确保REST API提供一个文件?

我想validation一个调用我的REST API的端点之一是提供一个文件,但我不知道如何去做,我没有看到任何这方面的例子? 我看过文档 ,但是这对我没有多大帮助。

服务器端代码本质上是(在Express中):

handleRetrieveContent(req, res, next) { const filepaht = '...'; res.sendFile(filepath) } 

和testing案例:

 it('Should get a file', (done) => { chai.request(url) .get('/api/exercise/1?token=' + token) .end(function(err, res) { if (err) { done(err); } res.should.have.status(200); // Not sure what the test here should be? res.should.be.json; // TODO get access to saved file and do tests on it }); }); 

我基本上想做下面的testing:

  • 确保响应是一个文件
  • 确保文件是有效的内容(校验和testing)

任何帮助,将不胜感激。

提供的解决scheme基于进一步的实验和https://github.com/chaijs/chai-http/issues/126中提供的答案 – 注释代码假定ES6(使用节点6.7.0进行testing)。

 const chai = require('chai'); const chaiHttp = require('chai-http'); const md5 = require(md5'); const expect = chai.expect; const binaryParser = function (res, cb) { res.setEncoding('binary'); res.data = ''; res.on("data", function (chunk) { res.data += chunk; }); res.on('end', function () { cb(null, new Buffer(res.data, 'binary')); }); }; it('Should get a file', (done) => { chai.request(url) .get('/api/exercise/1?token=' + token) .buffer() .parse(binaryParser) .end(function(err, res) { if (err) { done(err); } res.should.have.status(200); // Check the headers for type and size res.should.have.header('content-type'); res.header['content-type'].should.be.equal('application/pdf'); res.should.have.header('content-length'); const size = fs.statSync(filepath).size.toString(); res.header['content-length'].should.be.equal(size); // verify checksum expect(md5(res.body)).to.equal('fa7d7e650b2cec68f302b31ba28235d8'); }); }); 

编辑:这大部分是在读取响应输出缓冲区/stream与supertest / superagent在node.js服务器可能改进