在node.js服务器上使用supertest/superagent读取响应输出缓冲区/流 [英] Read response output buffer/stream with supertest/superagent on node.js server

查看:340
本文介绍了在node.js服务器上使用supertest/superagent读取响应输出缓冲区/流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个测试,以检查API路由是否输出了包含正确内容的ZIP文件.

I am trying to write a test that checks whether an API route outputs a ZIP file with the correct contents.

我正在使用mocha和supertest进行测试,我想实际读取输出流/缓冲区,读取zip文件内容并查看内容是否正确.

I am using mocha and supertest for testing, and I would like to actually read the output stream/buffer, read the zip file contents and see if the contents are correct.

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

Any ideas how should I do it? When I try to read res.body, it's just an empty object.

  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的答案,以下内容可用于获取任何二进制响应内容作为Buffer,您可以在request.end()中进一步检查:

Expanding on @Beau's answer, the following can be used to get any binary response content as a Buffer which you can examine further in 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();
        });
});

这篇关于在node.js服务器上使用supertest/superagent读取响应输出缓冲区/流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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