我想验证对我的REST API端点之一的调用正在提供文件,但是我不确定如何处理该文件,因此也看不到任何示例?我确实看过documentation,但这并没有太大帮助。

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

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


和测试用例:

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


我本质上是想做以下测试:


确保响应是文件
确保文件内容有效(校验和测试)


任何帮助,将不胜感激。

最佳答案

提供的解决方案基于进一步的实验,并在https://github.com/chaijs/chai-http/issues/126中提供了答案-注释代码假定使用ES6(已通过Node 6.7.0测试)。

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


编辑:大多数都在Read response output buffer/stream with supertest/superagent on node.js server中并进行了可能的改进

关于node.js - 使用mocha/chai确保REST API提供文件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40517088/

10-11 22:16
查看更多