使用mocha / chai确保REST API提供文件? [英] Using mocha/chai to ensure REST API serves up a file?

查看:105
本文介绍了使用mocha / chai确保REST API提供文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

The server side code essentially does (in 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                
        });
});     

我本质上是想进行以下测试:

I am essentially wanting to do the following tests:


  • 确保响应为文件

  • 确保文件为有效内容(校验和测试)

任何帮助将不胜感激。

推荐答案

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

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

编辑:大部分内容在在node.js服务器上使用supertest / superagent读取响应输出缓冲区/流并可能进行改进

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

这篇关于使用mocha / chai确保REST API提供文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆