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.
What additional we required for testing ?
Absolutly Nothing, only you have to use Node Package Manager (NPM) to install few packages that includes.
npm -i -g mocha
- Its a module for testing HTTP calls.
npm -i supertest
- 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.
After running this application when the browser make a request on “/” it looks like
Now coming to our testing file
Different elements in above file are:
- This is variable name holding the module supertest
- 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 lets you write your test cases.
- It signify the expected outcome / output of the test case. In our scenerio we are expecting that status code will be 200.
- 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.
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/