19 Best Practices For Automation testing With Node.js

Image for post
Image for post

Node js has become one of the most popular frameworks in JavaScript today. Used by millions of developers, to develop thousands of project, node js is being extensively used. The more you develop, the better the testing you require to have a smooth, seamless application. This article shares the best practices for the testing node.in 2019, to deliver a robust web application or website.

Let’s say you developed an application in Node JS about the weather forecast. Testing node.js for a weather forecast application is very complex due to numerous modules and features. For example, the web application will tell you the forecast for today and along with it, it will show you different parameters such as precipitation and humidity. This application will also require location tracking since every user is located at a different location. A user using weather application needs to have correct data because many things works on the weather of the day and of the subsequent days like planning a trip maybe.

A complex weather application might include winds and cloud movements for the geologists to study. An application used at such a level cannot contain a single glitch by which the complete country’s future is predicted. So after the development of these modules, we get to testing node.js for these modules so that everything is checked and works fine in real time.

Hold on now! We are not going to perform testing with node.js on a weather application in this article. However, I will demonstrate a simple project where we will initialize a test in Node JS in small steps so that it becomes clear in the end about how the tests are created for testing Node JS and we can focus on the best practices for testing node.js in 2019.

Initializing A Simple Test In Node JS

function mul(x,y)
{
return x*y;
}

This is a basic function for multiplication. But, this function is not valid for every case and can stand invalid for various other numbers. We cannot perform testing in such a situation. We will extend this function to validate the equality feature.

function mul(x,y)
{
return x*y;
}
function testMul()
{
var x = 4;
var y = 5;
val mul = x*y;
var mul2 = mul(4,5);
if(mul == mul2)
console.log(‘Equality Test Passed’);
else
console.log(‘Equality Test Failed’);
}
testMul();

After writing the basic tests, we will initialise the new node project by hooking it up to the npm.

Now you need to install the modules. As we discuss further in this article you will learn more about the importance of Mocha and Chai in the node js testing. Mocha gives you a good platform to define your test case suites, hooks and use assertion of whatever library you want to use. Chai on the other hand is used for writing the assertions only. These assertions are the human readable test codes which has advantages of its own.

npm init

After this, I have created two js files. One being test.js and other mull.js . Save the test.js in the test folder and mull.js in the root directory.

Now paste the function mul written above with an extra line.

function mul(x,y)
{
return x*y;
}
module.exports = mul;

Exporting it will help us in adding it to the require line as we perform testing with node.js.

Open your test.js file in the tests folder and write the following test code given below to go-ahead testing with node.js. This test code will test the equality of the two functions. The expect variable is the object code from chai library to write the “expect” part of the assertion and multiply will be the variable that contains the exported module of the code given just above it (module.exports = mul).

var expect = require(‘chai’).expect;
var multiply = require(‘../mul’);
describe(‘mul()’, function(){
it(‘should multiply two number’, function(){
var x = 4;
var y = 5;
val mul = x*y;
var mul2 = mul(4,5);
expect(mul2).to.be.equal(mul)
});
});

Just run your tests now through npm test in the console window and you are good to go.

Best Practices For Testing Node JS

Isolated and Atomic

You should also keep in mind that the data you are testing upon should be separate for every test. More than one tests working on the same global data harms the overall motive of using the tests upon the application. Your time will absolutely increase leading to good performance but it is of no point. Keep your data specific to the tests.

Naming Of Your Test

  • What is being tested?
  • What are the different scenarios under which you are testing?
  • What should be the expected result of the test?

Here is an example of a meaningful naming convention for testing node.js.

function CheckCountryLanguage()
{
//code to check if the application is showing data in the country’s official language
}

The above test name makes sense because we can easily get what that function would be doing. What if I had written the function name as foo? Then I would have to read the complete code to understand the working of the function.

Using Assertions

A test will use logic in test cases while assertions are the human readable forms where you write tests in human readable forms. This helps when analyzing the tests after they are run. You can use chai library for achieving the same and can learn more about the Chai library here.

expect(‘currentweather’).to.be(‘string’);

Such assertions are human readable and are self-explanatory about the test they are performing. This expect shows that the currentWeather has to be a string such as Hazy, Clear or Rainy etc.

Use Test Runner

Focus On Test Coverage

First of all, you should always keep in mind that test coverage percentage is totally depended upon the nature of your application. If it is some application say Music Player then it need not have 100% test coverage because as we increase the test coverage it becomes more and more expensive for the company. But if you have an important application like any real time application receiving data from satellite or an application for the manufacturer of Airplanes then you need to have 100% coverage because it will affect the application to a great extent. We will focus on test coverage for the upcoming points. For this you can use Mocha along with Istanbul and run your Mocha tests over Istanbul.

Use Plugins For Test Coverage

Analyse The Test Coverage Report

Use Mutation Testing

Check Plagiarism On Tests

In order to use the plagiarism checker, you can install the node js npm plagiarism-checker package.

To install it just type the following code:

npm i plagiarism-checker

After that, in order to use that SDK, type the following code:

var a = require(‘plagiarism-checker’);
var b = new a();
var config = b.getConfig();

Download the code from this repository and add it to your project. Keep in mind the following dependencies are installed

$ npm install lodash
$ npm install request
$ npm install request-promise
$ npm install mime-types

Use Realistic Inputs

Many times it so happens that the testers use the inputs that are not realistic or according to the real life scenarios. For example an input demanding phone numbers should be tested on numbers which resemble the real phone numbers. So you should always use realistic inputs while testing your application. The best library available for this purpose is Faker library. According to GitHub, Faker library is a php library that generates fake data for the input you are willing to test upon.

You should also keep in mind to use more and more inputs for a single input parameter so as to test heavily. As in real life, many inputs will be processed on the same function, you should use as many as possible to test them.

A simple portrayal of the situation can be the same weather application that we discussed in the beginning of this chapter.

function CountryName(string country)
{
//code
}

Now, this function should be tested with realistic inputs such as

function CountryName(India)
{
//code
}
function CountryName(Netherlands)
{
//code
}

Instead of :

function CountryName(abc)
{
//code
}
function CountryName(foo)
{
//code
}

Use Linters

Property Based Testing

for all(a,b)

b is always an even number

Property based testing helps us as it

  • Contains the scope of all inputs and that can generate a huge number of test cases
  • Can take us to the failure in a very short time as it has something specific to put as the input like even numbers in the above case. It can keep on inserting even numbers until a point that it fails and we can get the threshold value of the function quite easily.

You can use FastCheck, QuickCheck or Mocha Test Check for property based testing.

Use Chai Library

For example,

expect(‘a’).to.not.have.property(‘b’);

this way few lines of code is summarised to a single line of chai assertion.

Check For Exceptional Scenarios

Many firms develop their own methods to achieve these things. A good example is Netflix which has developed something they call Chaos Engineering which tests their functions and method by killing off their servers one by one. This way they are also assured that even if one server fails, the application works correctly.

Follow The Testing Pyramid

Image for post
Image for post

While testing with node.js, you should try to follow the test automation pyramid. As seen from the following image the unit test should be taken as the base of all the testing.

We do so because unit test will cover the basic units of functionality independently of one another. After the unit tests are done then move ahead to the integration testing. Integration testing will let you test the different modules combined with one another as a group. After that we move on to the next part of the pyramid and test the front-end or User-Interface testing using Selenium or similar tools.

As you can see, the cost incurred keeps on increasing as we move on to the pyramid but the speed keeps on decreasing. Unit test takes most of the time to execute while the front end is tested fastest because of the less complexities and modules.

Use Component Testing

Image for post
Image for post

As seen in the image, each component has a test plan and every test plan has various different tests under it and then they are tested to check the functionality of the component. It is recommended to use the component testing after the unit testing in the pyramid. Component testing is a very good approach and has a great coverage and speed greater than unit testing.

Keep Infrastructure Issues In Mind

Going Parallel

Automate The Updation Of Your Dependencies

Use An Online Selenium Grid For Cross Browser Testing

LambdaTest offers an online Selenium grid using which you can perform testing with node.js on over 2000+ real browsers and browser versions running on different operating systems. You can automate your testing process and can even perform testing with node.js in parallel. You can even perform test using any other test automation framework with respect to different languages such as Python, PHP, C#, Java and more.

Well, that was all from my end. Testing with node.js may look a little scary at first. However, you can get rid of hesitation and perform it like a professional by keeping the above best practices for testing Node JS in mind. Let me know if there is a special practice that I have missed, and you feel is indispensable for the article. Happy testing! 🙂

Originally published at LambdaTest

Author Harish Rajora

Image for post
Image for post

Written by

Product Growth at @lambdatesting (www.lambdatest.com)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store