Search code examples
javascriptstreamingjestjssupertestsuperagent

How to test image upload (stream) with supertest and jest?


I have an image upload endpoint in my API that accepts application/octet-stream requests and handles these streams. I'd like to write test coverage for this endpoint but cannot figure out how to use supertest to stream an image.

Here's my code so far:

import request from 'supertest'

const testImage = `${__dirname}/../../../assets/test_image.jpg`

describe('Upload endpoint', () => {

  test('Successfully uploads jpg image', async () =>
    request(app)
      .post(`${ROOT_URL}${endpoints.add_image.route}`)
      .set('Authorization', `Bearer ${process.env.testUserJWT}`)
      .set('content-type', 'application/octet-stream')
      .pipe(fs.createReadStream(testImage))
      .on('finish', (something) => {
        console.log(something)
      }))

})

This code produces nothing, the finish event is never called, nothing is console logged, and this test suite actually passes as nothing is expected. I cannot chain a .expect onto this request, otherwise I get this runtime error:

TypeError: (0 , _supertest2.default)(...).post(...).set(...).set(...).pipe(...).expect is not a function

How is such a thing accomplished?


Solution

  • This should work. To pipe data to a request you have to tell the readable stream to pipe to the request. The other way is for receiving data from the server. This also uses done instead of async as pipes do not work with async/await.

    Also worth nothing is that by default the pipe will call end and then superagent will call end, resulting in an error about end being called twice. To solve this you have to tell the pipe call not to do that and then call end in the on end event of the stream.

    import request from 'supertest'
    
    const testImage = `${__dirname}/../../../assets/test_image.jpg`
    
    describe('Upload endpoint', () => {
    
      test('Successfully uploads jpg image', (done) => {
          const req = request(app)
              .post(`${ROOT_URL}${endpoints.add_image.route}`)
              .set('Authorization', `Bearer ${process.env.testUserJWT}`)
              .set('content-type', 'application/octet-stream')
    
          const imgStream = fs.createReadStream(testImage);
          imgStream.on('end', () => req.end(done));
          imgStream.pipe(req, {end: false})
      })
    })
    

    Edited to add: this has worked for me with small files. If I try testing it with a large test_image.jpg the request times out.