JavaScript Answers

How to unit test routes with Express and JavaScript?

Spread the love

To unit test routes with Express and JavaScript, we use supertest.

For instance, we write

describe("GET /users", () => {
  it("respond with json", (done) => {
      .set("Accept", "application/json")
      .end((err, res) => {
        if (err) return done(err);

to call request with app to use the Express app to make requests.

Then we call get to make a get request to the /users route.

We call set to set the request header.

We call expect to check that the status code returned is 200.

And we call end with a callback that calls done to finish the test.

The test passes if done is called with no argument.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *