当前位置: 动力学知识库 > 问答 > 编程问答 >

node.js - Using mocha/chai to ensure REST API serves up a file?

问题描述:

I am wanting to validate that a call to one of my REST API's end-point is serving up a file, but I am not sure how to go about it and I am not seeing any examples on this? I did look at the documentation, but this didn't help me much.

The server side code essentially does (in Express):

handleRetrieveContent(req, res, next) {

const filepaht = '...';

res.sendFile(filepath)

}

and the test case:

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

});

});

I am essentially wanting to do the following tests:

  • ensure the response is a file
  • ensure the file is of valid content (checksum test)

Any help would be appreciated.

网友答案:

The solution provided was based on further experimenting and an answer provided in https://github.com/chaijs/chai-http/issues/126 - note code assumes ES6 (tested with 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');              
        });
});

Edit: Most of this was in Read response output buffer/stream with supertest/superagent on node.js server with possible improvements

分享给朋友:
您可能感兴趣的文章:
随机阅读: