Write Test Cases for your node app using mocha
Hey now we are good to write the node APIs, aren’t we ?
Of Course yes, we are.
So here we are to write the test cases for the APIs to provide the assertion and best quality.
#Introduction:
In this tutorials we will write the test cases for our API. To achieve this, we will do following things:
# Test Case
# Mocha
# Chai
# Prerequisites
# Project Setup
# The server
# Write the test case
# Run the test case
# Conclusion
#Test Case:
A Test case basically a line of code where we write the condition to test the another line of code. Here we ensure that this particular system is working according the expectation or satisfy the requirements.
By writing the test cases can also help to determine the problem, bugs in existing system. We write the test cases to get the surety that system is working fine.
#Mocha:
Mocha is used for testing, It is a javascript framework for nodejs. Mocha is asynchronous. Mocha is used to build an environment where we can write and run our test cases.We can also use our assertion libraries under the mocha environment, here we will use “Chai”.
#Chai:
“Chai” is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javaScript testing framework. “Chai” provide a better way to write the test cases under mocha environment.
Why Chai ?
Actually Mocha provide the environment for making our test, But we need to test our API and our API using http calls like GET, PUT, DELETE, POST etc. So we need a assertion library to fix this challenge. Chai helps us to determine the output of this test case.
Chai provide the various interface: “should”, “expect”, “assert”.
#Prerequisites:
- Installed Nodejs.
- Installed Mocha ( Run command: “npm install -g mocha” )
#Project Setup:
Here is the project structure, Yo need to follow this:
myApp
— — →server.js
— — →test — — — — — — — →apitest.js
— — →package.json
— — →node_modules
#Server Setup:
Now it’s time to make our node server where we will write our API, further we will write our test case to test these APIs. We will use express framework for nodeJs to write our API in easy way.
STEP 1: Create your package.json by using following command:
“npm init”
After this command you will be asked to enter details of this project then enter the information. Now replace your package.json content with below code. Your package.json will have only below code.
package.json:
{
“name”: “demotest”,
“version”: “1.0.0”,
“description”: “this is to understand the demo.”,
“main”: “server.js”,
“directories”: {
“test”: “test”
},
“scripts”: {
“test”: “mocha — timeout 10000”,
“start”: “node server.js”
},
“author”: “Shubham Verma”,
“license”: “ISC”,
“devDependencies”: {
“chai”: “4.2.0”,
“chai-http”: “4.2.1”,
“mocha”: “5.2.0”
},
“dependencies”: {
“express”: “4.16.4”
}
}
STEP 2: install the dependencies:
Run “npm install” to install all the dependencies required for this project. It will create a node_modules directory in your root folder. “npm install” command will install following things:
Chai
Chai-http
Mocha
Express
STEP 3: Create your server.js file
Now its time to create a server file name server.js inside your root directory ( myApp-> server.js ). Please paste below code into your server.js file
server.js:
const express = require('express');
const app = express();
const port = 3300;app.get('/message', function (req, res) {
res.send('This is the message');
});app.get('/media', function (req, res) {
var response = {
podcasts: [{
"description": "some text",
"id": 574,
"title": "Why long-term value is a winning bet",
"media": "podcast",
"publishedDate": "2018-12-19T18:00:00.000Z",
"isLive": true,
"isDeleted": false,
"link": "https://podcasts.com/574",
"createdAt": "2018-12-20T06:30:00.618Z",
"updatedAt": "2019-01-31T06:30:00.864Z"
}],
total: 1
}if (response.podcasts.length > 0) {
res.send(response);
} else {
var errorObj = {
httpCode: 404,
message: 'NOT_FOUND',
description: 'The resource referenced by request does not exists.',
details: 'Podcast is not available'
}res.status(404);
res.send(errorObj)
}
});app.listen(port, function () {
console.log("\nServer is running on port " + port);
});module.exports = app; // for testing
#description and understanding of above code:
const express = require(‘express’);
const app = express();
The above code we are using the require function to include the “express module and before we can start using the express module, we need to make an object of the express module.
const port = 3300; // Defining the port number where our server will run, the default host is localhost.app.get(‘/message’, function (req, res) {
res.send({‘message’: ‘This is the message’});
});
The above code is a simple API with end point ”/message”, It accepts all HTTP GET request with endpoint “/message”.
app.get(‘/media’, function (req, res) {
var response = {
podcasts: [{
“description”: “some text”,
“id”: 574,
“title”: “Why long-term value is a winning bet”,
“media”: “podcast”,
“publishedDate”: “2018–12–19T18:00:00.000Z”,
“isLive”: true,
“isDeleted”: false,
“link”: “https://podcasts.com/574",
“createdAt”: “2018–12–20T06:30:00.618Z”,
“updatedAt”: “2019–01–31T06:30:00.864Z”
}],
total: 1
}if (response.podcasts.length > 0) {
res.send(response);
} else {
var errorObj = {
httpCode: 404,
message: ‘NOT_FOUND’,
description: ‘The resource referenced by request does not exists.’,
details: ‘Podcast is not available’
}
res.status(404);
res.send(errorObj)
}});
The above code is also a simple API with end point ”/media”, It accepts all HTTP GET request with endpoint “/media” and return an object in response with status code 200.
app.listen(port, function () {
console.log(“\n Server is running on port “ + port);
});
The above code is the important code to run this server. It tells to node that this server is running on given port ( 3300 here ).
module.exports = app; // for testing
The above line is for testing purpose, It will return the main server object.
Using this server object we will create our test cases. Now our server part is done, Lets run our server.
STEP 4: Run the server:
Open CMD/Terminal, Goto the project location and hit command:
”npm start”
Now you can see the message “Server is running on port 3300”.
It means server is started.
STEP 5: Test the APIs:
Now we need to test the server so Let’s check on browser. Open browser and hit url “localhost:3300/message”. After this you can see the response on browser “{“message”:”this is the message” }”
It means our one API with endpoint “/message” is working fine. Now test the other API using same process with endpoint “/media”
You can see the result as :
It means our both API is working fine.
#Write the test case:
Now it’s time to write the test cases for our both API which is written on above server file. We will use mocha and chai to write the test cases. So lets start to write test case. Create a file with name apitest.js inside test folder ( myApp — -> test — -> apitest.js):
Copy below code and paste into your apitest.js:
apitest.js:
let chai = require(‘chai’);
let chaiHttp = require(‘chai-http’);
var should = chai.should();
chai.use(chaiHttp);
let server = require(‘../app’);//Our parent block
describe(‘Podcast’, () => {
describe(‘/GET media’, () => {
it(‘it should GET all the podcast’, (done) => {
chai.request(server)
.get(‘/media’)
.end((err, res) => {
(res).should.have.status(200);
(res.body).should.be.a(‘object’);
(res.body.podcasts.length).should.be.eql(1);
done();
});
});
});describe(‘/GET message’, () => {
it(‘it should GET a message’, (done) => {
chai.request(server)
.get(‘/message’)
.end((err, res) => {
(res).should.have.status(200);
(res.body).should.be.a(‘object’);
done();
});
});
});
});
# Description and understanding of file apitest.js:
let chai = require(‘chai’);
let chaiHttp = require(‘chai-http’);
var should = chai.should();
chai.use(chaiHttp);
In the above code we are importing the library. “chai” is the module as describe at the top of the tutorial.
describe(‘Podcast’, () => { …… });
The above describe function is use to describe about what we want. It takes two parameter a string ( anything that tells you about the operation ) and a callback function.
it(‘it should GET all the podcast’, (done) => { });
The “it()” used to tells us that what is going to be tested in this method.
chai.request(server)
.get(‘/media’)
.end((err, res) => {
(res).should.have.status(200);
(res.body).should.be.a(‘object’);
(res.body.podcasts.length).should.be.eql(1);
done();
});
In the above code we are going to test tha “/media” API in with “server” object. The “server” object is our node server’s object and getting by import
“let server = require(‘../app’);”.
(res).should.have.status(200); check the status of that API ( HTTP status code should be 200.
(res.body).should.be.a(‘object’); Check body of response should be an object.
(res.body.podcasts.length).should.be.eql(1); Check the length of the “res.body.podcasts” should be 1.
done() will be called when everything is ok. And the same description for other test case.
# Run the test case:
Now it’s time to run our test cases. To do this open CMD/Terminal, go to the server location and run command:
“mocha”
Or
“npm test”
You can see the results: 2 Passing. We have created 2 test cases and both are passed. It means our API is good and will respond as expected.
Congratulations……………. You did it :)
# Conclusion:
We have created a server.
Created 2 APIs associated with this server.
Wrote test cases for those APIs.
Run our test cases.
Verified and sure that APIs will behave as expected.
Now, We are able to write the test cases for our node app.
If you’re interested in Node.js or JavaScript, then this link will help.Write your comment for any query.
Thanks for reading.