node.js - 在 node.js 服务器上使用 supertest/superagent 读取响应输出缓冲区/流

标签 node.js zip mocha.js superagent supertest

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

我正在使用 mocha 和 supertest 进行测试,我想实际读取输出流/缓冲区,读取 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();
        });
});

关于node.js - 在 node.js 服务器上使用 supertest/superagent 读取响应输出缓冲区/流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13573315/

相关文章:

javascript - Office365 IMAP 访问 : User is Authenticated but not Connected

c++ - 在 C++ 中创建一个 zip 存档

testing - 为什么 Mocha 不报告每次测试的时间?

node.js - 当mongodb不在同一个VM中时,mongodb连接超时

node.js - 如何解决 "customFds not yet supported"错误

node.js - 使用变量作为带有修饰符的 mongodb 中的键名

Java:处理输入流中的大文件

Android 从 Api 下载 Zip 并存储在 SD 卡中

node.js - 在 Heroku NodeJS 服务器上运行 MochaJS 测试

node.js - Mocha之前一个套件中的每个都在另一个套件中运行