Testing Node.js apps with Jest and supertest. For dummies.

This is probaly the easiest guide to testing in Node.js you’ll ever read. I struggled to find a good guide to follow and decided to write mine. The idea here is for it to be so simple, anyone starting to learn Node can follow.

This article is a follow on from the instagram downloader we built here. This is the same app we will be testing.

There are 3 main types of tests we can write. Unit tests, Integration tests and end-to-end test. In this article, we will be focusing on writing E2E tests. We will be testing how our system will react when we receive data from an external source.

  1. Firstly, we need to install the packages we’ll be using. We’ll be using jest and supertest. Install them as Dev-dependencies since we only need them in development.

Jest is a test runner. I.e It searches your folder for files ending in “anything.test.js” or “anything.spec.js” and runs the commands in that file.

Supertest allows us mimic HTTP requests(i.e GET/POST/PUT etc) to our server and to test the responses. It has over 600k weekly downloads. That’s definitely a super framework!

Also, change the test script in package,json to

2. Next, create a scraper.test.js file anywhere within the app directory.

3. Bring in supertest and our app server.

4. Create a describe block. A describe block allows us group tests that test similar functionality.

5. Within the describe block, let’s write our tests to test for when the URL is valid and when it’s invalid. Jest provides us matchers like toBe and toContain that can be used to test that the responses have an exact value or contain a certain value respectively.

Supertest includes the expect method that allows us test the statuscode of the response and the type of the response.

6. Finally, run the command npm run test. Our tests should pass

Use Ctrl + C to exit the test run if it doesn’t exit automatically.

And that’s how you test Node.js apps!

Full-stack Engineer. Rails/Node.js/React. I love plantain chips! Reach me at Adebola.dev.

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