Automation Testing

Setting up mocha for NodeJs (loopbackJs)

Installing libraries

Let’s begin with installing the required libraries. We are going to install 3 libraries which are Mocha, chai, and chai-http.

Mocha

Mocha is a JavaScript test framework for Node.js. For more details and documentation check its Github repo. To install mocha check below cmd:

npm install mocha --save-dev

Chai

Chai is an assertion library, similar to Node’s build in assert. It makes testing much easier by giving you lots of assertions you can run against your code. For more details and documentation check its Github repo. To install mocha check below cmd:

npm install chai --save-dev

Chai-http

Chai-http is a js library which helps you make HTTP request using chai. For more details and documentation check its Github repo. To install mocha check below cmd:

npm install chai-http --save-dev

Setting up Tests for APIs

Creating the new Data source for test

We are going to create a new data source for the test so that testing does not impact the Production Data.

  • Copy the datasources.json file from the server folder and paste it under the same folder and rename it as datasources.test.json.
  • Open the datasources.test.json file and rename data.json to test-data.json mentioned in file field.

Before

"fileSystem": {
    "name": "fileSystem",
    "localStorage": "",
    "file": "data/data.json",
    "connector": "memory"
  }

After

"fileSystem": {
    "name": "fileSystem",
    "localStorage": "",
    "file": "data/test-data.json",
    "connector": "memory"
  }

Q. What’s the use of creating datasources.test.json?

Ans. Whenever we start loopback server after setting NODE_ENV=test our models will now use datasource mentioned in datasources.test.json instead of using datasources from datasources.json. So the file path mentioned in datasources.test.json is data/test-data.json, hence our models will use the test-data.json file instead of using data.json, therefore our production data which is present in data.json will not be impacted while testing.

Setting up the test file

  • Create a new tests folder and add a new test file, let’s call it as contact.test.js
  • Now in test file lets set NODE_ENV to test so that when the server starts it uses datasources.test.json instead of datasources.json
process.env.NODE_ENV = 'test';
  • Now import the dev dependencies,
// Require the dev-dependencies
let chai = require('chai');
let chaiHttp = require('chai-http');
let server = require('../../server/server');
let should = chai.should();
chai.use(chaiHttp);

Writing test

After setting up the test framework in contact.test.js file, let’s write our 1st test.

Create a describe and it block as shown below

describe('Contacts', () => {
  /*
  * Test the /GET route
  */
  describe('/GET contact', () => {
    it('it should GET all the contacts', (done) => {
      // test code goes here
    });
  });
});

Now inside the it block we can write our test to check get request. This is how it block looks after adding the test,

it('it should GET all the contacts', (done) => {
      chai.request(server)
        .get('/api/Contacts')
        .then(function(response) {
          response.should.have.status(200);
          done();
        })
        .catch(function(error) {
          done(error);
        });
    });

NOTE: In above code snipped you can see /api/contact , this is the API endpoint written in our project which gives list of all contacts.

To know more about the project check here : Angular6-contact-book

Clearing Database after running tests

We should clear the DB after running the tests, so that next time when tests run there is no junk data already present in our DB. Hence we are going to clear the DB i.e. test-data.json file in after block of mocha. After block runs when the execution of all the tests is done.

Create an after block which runs after running all test.

  after(function() {
    // runs after all tests in this block
  });

Now inside this after block we will write our logic to delete the test-data.json file using file stream.

let fs = require('fs');
    let fileToRemove = 'data/test-data.json';
    fs.unlink(fileToRemove, function(err) {
      if (err && err.code == 'ENOENT') {
        // file doens't exist
        console.info('File does not exist');
      } else if (err) {
        // other errors, e.g. maybe we don't have enough permission
        console.error('Error occurred while trying to remove DB file');
      } else {
        console.info('removed DB file');
      }
    });

Running test

Running the test is very simple just type mocha and give the path to your test file.

./node_modules/mocha/bin/mocha tests/contact.test.js

In above cmd, it will run only a single test which is contact.test.js Now, in the bigger project we might have more than one test file, so let’s make it generic so that it can run all the test file.

./node_modules/mocha/bin/mocha tests/**/test.js

So here we are asking mocha to run every file inside the folder test which has test.js in their filename.

Running test via npm

This is a very easy step, all you need to do is just add below snippet inside script field of your package.json "test": "./node_modules/mocha/bin/mocha tests/**/*test.js --reporter spec"

This is how it looks in package.json

"scripts": {
    "start": "node .",
    "test": "./node_modules/mocha/bin/mocha tests/**/*test.js --reporter spec"
  },

Q. What is the advantage of creating a new script in package.json

Ans. The advantage of creating test script above is that we can now run the test by simply typing npm test in our terminal.

Ref: https://scotch.io/tutorials/test-a-node-restful-api-with-mocha-and-chai This blog explains how to use mocha, chai and chai-http for node.

 

Github Project

All the steps mentioned above are implemented in the project Angular6-contact-book. Go through branch wise merges to find all the development in stepwise.

 

Let me know your thoughts

Theme by Anders Norén

%d bloggers like this:
Bitnami