What to expect from this blog?

  • When you will read the complete blog you will be able to create the server in nodejs, create an endpoint, write the test case for it.
  • Endpoint Created in this blog is very simple, just to create test cases from it.
  • We chose very simple 2 test cases.
    (If you are already master in it, you can still go ahead and let us know where we can improve)

 

complete code: github repository

 

Let’s create nodejs project straight away.

  • create a folder of your_project_name

  • cd your_project_name

  • npm init follow the steps you might be familiar with.

  • npm install –save express body-parser

  • create sub directory server and crate file server.js into it.

 

To create the server we have add some code in server.js.

//server.js

var express = require('express');
var bodyParser = require('body-parser');

var app = express();
app.use(bodyParser()); 
const port = process.env.PORT || 3000;

app.listen(port, () => {
  console.log("Server started on " + port);
});

module.exports = {
  app
}

 

AWESOME!!

 

your folder structure should be like,

your_project_name

– server

– server.js

 

run your application by node server/server.js

 

Your output should be.

Screen Shot 2018-03-23 at 4.25.10 PM

 

Let’s create an endpoint to test it later.

  • create a folder naming routes in your_project_directory
  • add file apiRoute.js

 

Code in apiRoutes.js

 

var express = require('express');
const router = express.Router();

router.get('/check', (req, res)=>{
	if(req.query.id){
		res.status(200).send({success:true})
	}
	res.status(500).send({success:false})
	
});



module.exports  = {router};

 

Let’s Include this route in our server.js, so server.js file will look like

 

var express = require('express');
var bodyParser = require('body-parser');
var {router} = require('./routes/apiRoutes'); // we have to created this files above
var app = express();
app.use(bodyParser()); 
const port = process.env.PORT || 3000;

app.use('/api', router);

app.listen(port, () => {
  console.log("Server started on " + port);
});

module.exports = {
  app
}


Perfect. We have created the endpoint. Now, let’s test it.

 

To Set up the Test Environment we have to install few npm package.

 

npm install –save-dev mocha supertest expect

 

Let us start writing Test cases for node js

 

Create a folder test in server. create file server.test.js in it.

 

const expect = require('expect');
const request = require('supertest');

const { app } = require('./../server');


describe('GET /api/check', ()=>{

    it('should get success flag false', (done)=>{
        request(app)
            .get('/api/check')
            .expect(500)
            .expect((res)=>{
                expect(res.body.success).toBe(false);
            })
            .end(done);
    })

})

 

what we have done in above code is,

  • we have declared describe block.
  • we can write one or more test cases in describe block starting with it block.
  • then we requesting to the server
  • we defined the method name(HTTP methods)
  • then we expect the status
  • then you can expect the output as well.
  • if everything is well then our test case is good and will be passed.

 

How to run the test case?

 

in package.json

 

add test command in scripts like:

 

{
  "name": "test-cases-in-nodejs",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "mocha server/**/*.test.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.2",
    "express": "^4.16.3"
  },
  "devDependencies": {
    "expect": "^22.4.3",
    "mocha": "^5.0.5",
    "supertest": "^3.0.0"
  }
}

 

To Run the Test cases: 

 

npm run test

Your output should be like,

 

Screen Shot 2018-03-23 at 4.15.47 PM

 

 

now lets write a test another test case,

 

const expect = require('expect');
const request = require('supertest');

const { app } = require('./../server');





describe('GET /api/check', ()=>{

    it('should get success flag false', (done)=>{
        request(app)
            .get('/api/check')
            .expect(500)
            .expect((res)=>{
                expect(res.body.success).toBe(false);
            })
            .end(done);
    })

    it('should get success flag true', (done)=>{
        request(app)
            .get('/api/check?id=1')
            .expect(200)
            .expect((res)=>{
                expect(res.body.success).toBe(true);
            })
            .end(done);
    })

 })

 

run your application. You could see 2 test cases are passing.

 

 Test cases for node js can be written in Mocha and can be tested. but to test some complex database updating operation etc. 

  1. I usually use Mocha for testing (with Chai for more complex asserts), and I think is very easy to learn, use and enough power (at least so far to me) for testing most of the things I develop with Javascript (I usually work with NodeJS)

    I started using Mocha with this simple tutorial, which explain basic uses of the library and it shows several examples, so it is very practical: Mocha: Javascript unit testing

    If you have any doubt using it, you can ask here and I’ll be looking forward to help you

    • Hi please can you link a good beginner level tutorial on how to use mocha the syntax and basics…. I’m very new to JS never written a test

Leave a Reply

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

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

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