Read response output buffer/stream with supertest/superagent on node.js server

后端 未结 3 1108
粉色の甜心
粉色の甜心 2021-02-05 07:15

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

I am using mocha and supertest for testing, and I would like t

3条回答
  •  时光取名叫无心
    2021-02-05 07:46

    Existing answers didn't work for me. What I ended up doing was:

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

提交回复
热议问题