node: testing apis with supertest

2021-11-21

 | 

~2 min read

 | 

222 words

Once you’ve designed an API, you will likely want to test it. If it’s a Node server, supertest is a popular solution for writing tests.

(Note: the example tests below are written assuming Jest is the test runner. I have notes on configuring jest and other tips as well.)

To get started, make sure that the server definition is separate from the invocation:

server/app.ts
import express from "express"

export const app = express()
// ... middleware, routes, etc.
index.ts
import { app } from "./server/app"
app.listen(3000)

With this separation in place, we are able to cleanly test the API.

server/app.test.ts
import request from "supertest"
import { app } from "./app"

describe("Server", () => {
  test("/GET index", async () => {
    await request(app).get("/").expect(200)
  })
})

This is the most basic test. It gets the server running and then checks the endpoint and it’s resulting status.

We can expand on this a bit to ensure that we are getting the expected data:

server/app.test.ts
import request from "supertest"
import { app } from "./app"

describe("Server", () => {
  test("/GET index", async () => {
    await request(app)
      .get("/")
      .expect(200)
      .then((response) => {
        expect(response.body).toEqual([])
      })
  })
})

Since there’s no database connection (yet), we would expect the test to return the default value for this endpoint (assumed here to be an empty array).


Related Posts
  • Node: Testing Protected APIs with Supertest


  • Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!