DEV Community

loading...

Test APIs with Supertest and Jest

lo_victoria2666 profile image Victoria Lo Originally published at lo-victoria.com on ・3 min read

Hello everyone! Last week, as I was writing my Let's Build a Node.js API Series, I learned from a reader that testing MVC APIs using Supertest and Jest is a good idea.

What's MVC Architecture?

It stands for Model View Controller and it is a popular software design pattern used when building APIs or full-stack apps. In MVC architecture, the software is divided into 3 interconnected components - Model, View and Controller.

MVC image

Model

Refers to the data structure of the app. For example, if your app is a blog, your model may have "author", "date", "content" in its model.

View

Refers to the elements that the user will see and interact with. It allows the user to read the data in a more engaging format and defines how the user can manipulate it (i.e. CRUD).

Controller

The controller is the bridge of communication between the Model and View component. From the View, it receives user input which instructs what kind of actions to perform on the Model.

Jest


It is a testing framework developed by Facebook and uses built-in test runners and assertion libraries in JavaScript. It is also easy to setup, which we will see later in this tutorial.

Supertest

It is used to test HTTP servers by sending a method like GET, PUT, POST or DELETE, Supertest can test any HTTP requests. Even multipart file uploads like the one my API has.

A simple example

So now that we have gone through the basics of the tools and concepts we need for today, let's try making some tests! I have a Tea API (or T-API for short) that I deployed on https://tea-api-vic-lo.herokuapp.com/. This API uses the MVC architecture.

Step 1: Install jest and supertest

We can run the following in our project root directory:

npm install --save-dev jest supertest
Enter fullscreen mode Exit fullscreen mode

Step 2: Package.json

In our package.json, we can add a "jest" portion that looks like:

 "jest": {
    "testEnvironment": "node"
  }
Enter fullscreen mode Exit fullscreen mode

In our "scripts" key of our package.json, we have:

"scripts": {
  "test": "jest"
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Create test files

The cool thing about jest is that it can automatically detect your test files as long as you name it in any of the 3 following formats:

  1. Any

    
    file in a folder named
    
    ```__tests__```
    
    
  2. Any

    
    file with a name like
    
    ```[name].spec.js```
    
    
  3. Any

    
    file with a name like
    
    ```[name].test.js```
    
    

I'm going to test the routes of my API so I'm creating a


 in my routes folder like so:


Enter fullscreen mode Exit fullscreen mode

routes/
|- tea.js
|- tea.test.js



### Step 4: Write a test
And in

 ```tea.test.js```

, I can write a simple test like:


Enter fullscreen mode Exit fullscreen mode

describe("Get all tea", () => {
it("should get all tea", async () => {
await request(app)
.get("/tea")
.set("Accept", "application/json")
.expect("Content-Type", /json/)
.expect(200);
});
});



- `describe` is where we can describe the test suite
- `it` defines the test and what it should do. In this case, we make an async GET request to the `/tea` route
- `expect` is  to check whether the test matches certain conditions. In this case, we expect a `json` with a status code of 200 to be returned from this test.

### Step 5: Run test
We run the test with `npm test`.

The console would show the following output:

![pass.PNG](https://cdn.hashnode.com/res/hashnode/image/upload/v1596645667999/yis-k3LJD.png)

## Conclusion
Both POSTman and Supertest with Jest are useful testing tools to test your API and their HTTP routes. POSTman requires more manual testing because you need to write in the URL, set the method and req.body to test endpoints. However, it is simple and intuitive to use. You don't need to install any npm packages or set up anything other than install the software itself. If your API is simple enough like my T-API, POSTman is not a bad idea to use.

If your API has a lot of endpoints, I'd say Supertest is a better choice. One reason is that it can execute all the tests easily in one command instead of manually testing them one by one. Also, it uses intuitive syntax like

 ```describe```

 and

 ```expect```

. Thanks for reading this simple introduction to Jest and Supertest. I hope you found this article helpful. Feel free to read the resources below to learn more. Till next time, cheers!

-----

### References 
- [Supertest documentation](https://www.npmjs.com/package/supertest)
- [Jest documentation](https://jestjs.io/docs/en/getting-started)
- Image from: https://mdn.mozillademos.org/files/16042/model-view-controller-light-blue.png

Enter fullscreen mode Exit fullscreen mode

Discussion (0)

pic
Editor guide