Free Ebook cover How to create APIs in NodeJS from basic to advanced

How to create APIs in NodeJS from basic to advanced

5

(1)

149 pages

Working with Routes in ExpressJS: Testing Routes with Jest or Mocha

Capítulo 62

Estimated reading time: 4 minutes

Audio Icon

Listen in audio

0:00 / 0:00

Chapter 7.16: Working with Routes in ExpressJS: Testing Routes with Jest or Mocha

One of the key features of ExpressJS is its ability to manage routes efficiently and effectively. Routes are essential for any web application as they determine how an application responds to a client request at a given endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, etc.).

To create a route in ExpressJS, we use the app.METHOD() method, where METHOD is the HTTP request method you want to use. For example, if we wanted to create a route to respond to GET requests at the root path (/), we could do it like this:

app.get('/', function (req, res) {
  res.send('Hello World!')
})

Although creating routes is relatively simple, it is important to ensure that they are working correctly. And that's where testing comes in. There are several testing tools available for Node.js, but in this course, we'll focus on two of the most popular ones: Jest and Mocha.

Jest is a complete testing framework that requires little or no setup effort, making it an excellent choice for beginners. It also has a very clear and easy-to-understand test syntax, which makes it easy to write tests. Let's see how we can use Jest to test our routes.

const request = require('supertest');
const app = require('../app');

describe('Test the root path', () => {
    test('It should response the GET method', () => {
        return request(app).get("/").then(response => {
            expect(response.statusCode).toBe(200);
        })
    });
});

In this example, we first import the supertest module, which allows us to make HTTP requests to our application. Next, we import our Express app. We then use Jest's describe function to wrap our tests and the test function to define a test. The test itself is quite simple: we make a GET request to the root route and check that the response status code is 200, which is the HTTP status code for "OK".

Continue in our app.

You can listen to the audiobook with the screen off, receive a free certificate for this course, and also have access to 5,000 other free online courses.

Or continue reading below...
Download App

Download the app

Now, let's see how we can do something similar with Mocha. Unlike Jest, Mocha is just a testing framework and requires additional modules to make assertions or HTTP requests. In this example, we are going to use Chai as our assertion library and supertest for the HTTP requests.

const request = require('supertest');
const app = require('../app');
const expect = require('chai').expect;

describe('GET /', function () {
  it('should respond with 200', function (done) {
    request(app)
      .get('/')
      .end(function(err, res) {
        expect(res.statusCode).to.equal(200);
        done();
      });
  });
});

As you can see, Mocha's syntax is a little different than Jest's, but the general idea is the same. We make a GET request to the root route and check if the response status code is 200.

In short, ExpressJS makes creating routes a simple task, but it's important to make sure those routes are working properly. For this, we can use testing tools like Jest or Mocha, which allow us to write clear and concise tests for our routes.

Testing your routes is a best practice as it allows you to discover and fix issues before they affect your users. In addition, tests can also serve as documentation, showing other developers (or yourself in the future) how your application should behave.

So spend some time learning and using these testing tools. Your code will be more robust, your application will be more reliable, and you'll be able to sleep better at night knowing your application is well tested.

Now answer the exercise about the content:

What is the main functionality of ExpressJS mentioned in the text and what are the suggested testing tools to ensure the routes work correctly?

You are right! Congratulations, now go to the next page

You missed! Try again.

ExpressJS's core functionality is its ability to manage routes efficiently, as highlighted in the text. The suggested testing tools mentioned for ensuring routes work correctly are Jest and Mocha.

Next chapter

Introduction to API's

Arrow Right Icon
Download the app to earn free Certification and listen to the courses in the background, even with the screen off.