在node.js服务器上读取supertest / superagent的响应输出缓冲区/stream

我正在尝试编写一个testing,检查API路由是否输出正确内容的ZIP文件。

我正在使用mocha和supertest进行testing,我想实际读取输出stream/缓冲区,读取zip文件的内容,看看内容是否正确。

任何想法我应该怎么做? 当我尝试阅读res.body ,它只是一个空的对象。

  request(app) .get( "/api/v1/orders/download?id[]=1&id=2" ) .set( "Authorization", authData ) .expect( 200 ) .expect( 'Content-Type', /application\/zip/ ) .end( function (err, res) { if (err) return done( err ); console.log( 'body:', res.body ) // Write the temp HTML file to filesystem using utf-8 encoding var zip = new AdmZip( res.body ); var zipEntries = zip.getEntries(); console.log( 'zipentries:', zipEntries ); zipEntries.forEach(function(zipEntry) { console.log(zipEntry.toString()); // outputs zip entries information }); done(); }); 

扩展@Beau的答案,可以使用以下方法将任何二进制响应内容作为一个缓冲区,您可以在request.end()进一步检查:

 function binaryParser(res, callback) { res.setEncoding('binary'); res.data = ''; res.on('data', function (chunk) { res.data += chunk; }); res.on('end', function () { callback(null, new Buffer(res.data, 'binary')); }); } // example mocha test it('my test', function(done) { request(app) .get('/path/to/image.png') .expect(200) .expect('Content-Type', 'image.png') .buffer() .parse(binaryParser) .end(function(err, res) { if (err) return done(err); // binary response data is in res.body as a buffer assert.ok(Buffer.isBuffer(res.body)); console.log("res=", res.body); done(); }); }); 

我想你会想创build你自己的应用程序/ zipparsing器,并使用它来获取实际的响应数据; 例如,JSONparsing器就在这里 。 一旦你有了,你可以通过将它传递给request.parse来使用它; 所以你的testing会变成:

 request(app) .get( "/api/v1/orders/download?id[]=1&id=2" ) .set( "Authorization", authData ) .expect( 200 ) .expect( 'Content-Type', /application\/zip/ ) .parse( function (res, fn) { res.data = ''; res.on( 'data', function (chunk) { res.data += chunk; } ); res.on( 'end', function () { try { fn( null, new AdmZip( res.data ) ); } catch ( err ) { fn( err ); } }); }) .end( function (err, res) { if (err) return done( err ); console.log( 'body:', res.body ) // Write the temp HTML file to filesystem using utf-8 encoding var zipEntries = res.body.getEntries(); console.log( 'zipentries:', zipEntries ); zipEntries.forEach(function(zipEntry) { console.log(zipEntry.toString()); // outputs zip entries information }); done(); }); 

为了find答案,我主要依靠检查superagenttesting套件。 🙂

现有的答案不适合我。 我最终做的是:

 // parses response.body buffer into a data object const parsePDF = response => { return new Promise((resolve, reject) => { // code that parses response.body as buffer // and calls resolve(data); when done // or reject(err); on error }) }; const binaryParser = require('superagent-binary-parser'); // test snippet request(app) .get('/some/api/returning/pdf') .expect(200) .expect('content-type', 'application/pdf') .parse(binaryParser) .buffer() .then(parsePDF) .then((pdf) => { chai.expect(pdf.pages.length).to.be.equal(5); })