Test binary response w/ supertest

const request = require('supertest')
const app = require('../app.js')

I’m attempting to test an API endpoint that returns a tar.gz file using supertest. My goal is to test if the file is properly sent and the content is correct.

I’ve tried saving the content of res.text (where const res = request(app).get('/project/export')) to a file, extracting it, and then checking its content. However, this approach does not seem to work, as the extraction function does not recognize it as a properly compressed file.

Any help would be appreciated, including suggestions on other modules or approaches for testing an express app.

const request = require('supertest')
const app = require('../app.js')

One approach you can try is to use the expect function from supertest to check the response’s content type and content length, and then pipe the response to a writable stream to save the file. Here’s an example:

const request = require('supertest')
const fs = require('fs')
const app = require('../app.js')

describe('GET /project/export', () => {
  it('should return a tar.gz file', (done) => {
    request(app)
      .get('/project/export')
      .expect('Content-Type', 'application/gzip')
      .expect('Content-Length', '1234') // replace with your expected content length
      .expect(200)
      .then((res) => {
        const file = fs.createWriteStream('export.tar.gz')
        res.pipe(file)
        file.on('finish', () => {
          // TODO: extract and check file content
          done()
        })
      })
      .catch((err) => done(err))
  })
})

Note that you’ll need to replace 1234 with the expected content length of your tar.gz file.