[英]Using mocha/chai to ensure REST API serves up a file?
我想驗證對我的 REST API 端點之一的調用是否正在提供文件,但我不知道如何去做,而且我沒有看到任何關於此的示例? 我確實看過文檔,但這對我沒有多大幫助。
服務器端代碼本質上是(在 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');
});
});
編輯:其中大部分是在node.js 服務器上使用 supertest/superagent 讀取響應輸出緩沖區/流,並有可能的改進
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.