2012-11-26 30 views
17

Tôi đang cố gắng viết một bài kiểm tra xem một tuyến đường API có xuất ra tệp ZIP với nội dung chính xác hay không.Đọc bộ đệm/luồng đầu ra phản hồi với supertest/superagent trên máy chủ node.js

Tôi đang sử dụng mocha và supertest để thử nghiệm và tôi muốn đọc luồng đầu ra/bộ đệm, đọc nội dung tệp zip và xem nội dung có chính xác hay không.

Bất kỳ ý tưởng nào tôi nên làm điều đó? Khi tôi cố gắng đọc res.body, nó chỉ là một đối tượng trống.

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

Trả lời

1

Tôi nghĩ bạn sẽ muốn tạo trình phân tích cú pháp của riêng bạn cho ứng dụng/zip và sử dụng để lấy dữ liệu phản hồi thực tế; trình phân tích cú pháp JSON là here, chẳng hạn. Một khi bạn đã có mà bạn có thể sử dụng nó bằng cách chuyển nó đến request.parse; để thử nghiệm của bạn sẽ trở thành:

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

Để tìm câu trả lời cho điều này tôi chủ yếu dựa vào việc kiểm tra các bộ kiểm tra superagent. :)

22

Mở rộng trên @ câu trả lời Beau của, sau đây có thể được sử dụng để có được bất kỳ nội dung phản ứng nhị phân như một bộ đệm mà bạn có thể nghiên cứu sâu hơn trong 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(); 
     }); 
}); 
+1

Điều này rất tuyệt, mặc dù tôi phải thêm '.buffer()' vào yêu cầu. – Nate

+0

Với @Nate, từ [tài liệu] (http://visionmedia.github.io/superagent/#parsing-response-bodies), "Nếu phản hồi đệm không được bật (.buffer (false)) thì sự kiện phản hồi sẽ được phát ra mà không cần đợi trình phân tích cú pháp nội dung kết thúc, do đó response.body sẽ không khả dụng ". – ZachB

+0

@ZachB để '.buffer(). Parse (binaryParser)'? – rcoup

-1

câu trả lời hiện tại không làm việc cho tôi. Những gì tôi đã làm cuối cùng là:

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