Node.js — test downloading a file with Jest + Supertest

A few days ago I was working on a task in which I’ve to write an endpoint to download a file from the server.

As usual, for every code we write in the team(at least for the backend side), we write the correct test cases. Until now, I had written test cases that checked the returned http code, the correct Content-Type, Content-Disposition and Content-Length headers and that’s all. This time, I want to check that I’m downloading the correct file (check the content I’m receiving).

First, I was thinking that it would be just check the “body” in the response and verify the data, but that wasn’t enough.

Validate the downloaded content depends on the file type, in my original case I was downloading a zip file so to validate the content, I unzipped the content and checked that the included files were the correct ones. In the example I’m going to show, I’m downloading a CSV file and checking that the file content is the correct one.

After reading a little bit, I realized that from the server I was streaming the file content and usually it’s handled by the browser showing the download/save dialog to perform the action.

I the test case I’m using supertest and by default it works fine. You have access to all the response headers and even the “content-length” which tells you that a response with data has been received. But, if you want to access the downloaded content, you need to adapt the typical used code and add handling the response as a buffer, read the content and write it to the response body.

We go from something like


As you can see, the magic is in “.buffer()” to handle the response as a buffer from the server and then use “parse” to write the received data to “” (here you can use an external temporal variable) to finally return all the content in the “end” event handler (which will end in the “response.body”).

After this, I can access to the file content in “response.body” and validate it

You can see all the code on The concrete files are:

I hope this help you to improve your test cases and if you know any other way to make this validations, please let me know in the comments.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store