We are going to Test the Route life cycle in NodeJS using mocha. If you want to know how to test NodeJS application when a particular route is requested using the browser / API calls then you can continue with this post. This post will give you a basic idea for integration testing.

About application that we are going to test.

We are going to Test application build in NodeJS using express framework. Node.js is a open-sourced, free, cross-platform JavaScript run-time environment for server-side scripting. And express is a powerful framework which provide a set of features for the web application development.

What additional we required for testing ?

Absolutly Nothing, only you have to use Node Package Manager (NPM) to install few packages that includes.

  • Mocha
    • Mocha is a feature-rich JavaScript test framework running on Node. js and in the browser, making asynchronous testing simple and fun.
    • npm -i -g mocha
  • SuperTest
    • Its a module for testing HTTP calls.
    • npm -i supertest
  • Assert
    • It provides a simple set of assertion tests that can be used to test invariants.
    • npm -i assert

What we are going to test ?

We will simply check the status code 200 (OK) for a particular route path. If the application return status code 200 then the test case is passed otherwise it failed.

NodeJS application developed using express returning status code 200 when request recieved on path “/”

After running this application when the browser make a request on “/” it looks like

NodeJS application running on port 11000

Now coming to our testing file

File used by mocha to test the application

Different elements in above file are:

  • supertest
    • This is variable name holding the module supertest
  • describe
    • mocha uses pattern of describe-it-expect for testing. Describe is the string description for the test or the group of tests that are going to be performed.
  • it
    • It lets you write your test cases.
  • expect
    • It signify the expected outcome / output of the test case. In our scenerio we are expecting that status code will be 200.
  • app
    • It is a variable that holds our main file of the NodeJS server. In our case it is app.js

We are passing the app inside supertest and making a get request on the path “/” and expecting that the response status code will be 200.

Mocha test passed

Now just to make sure everything working correctly. Remove the 200 with some other code in your test file and you will see your test will fail.

If you have feedback or questions about this page, add a comment below or send message to me on LinkedIn https://www.linkedin.com/in/adeshkumarsingh/

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.