Unit Testing in NodeJS

Here are some insights into today’s topic

  • Unit Testing: what is it?
  • What are its advantages?
  • What are the Detriments of Unit testing?
  • Workflow 
  • How to integrate it in NodeJs
  • How it will enhance Code Coverage

Software development necessitates unit testing, which ensures a high-quality product by testing each individual software component. Developers can quickly find and fix bugs before the product goes into production by using the Unit testing method. The correction of the isolated code is the primary objective of this unit testing.

Unit Testing: what is it?

The first level of testing known as unit testing is nothing more than examining each individual module or component of your code to prioritize and address bugs before they are released to production.

One method of testing known as unit testing is typically carried out by developers. Quality assurance engineers also perform unit testing despite developers’ reluctance to test. 

By providing the necessary inputs to the test script and asserting that the actual output matches the expected results, the developers create unit tests.
Life cycle of Unit testing

Life cycle of Unit testing [PC: tutorialspoint]

Now that we’ve covered the fundamentals of unit testing, let’s have a look at its advantages.

What are its advantages?

  1. It reduces bugs or defects in newly developed features when modifying existing functionality. Hence the cost of testing can decrease as defects are discovered early on.
  2. It improves design and makes it easier to refactor code which ultimately improves the build’s quality.
  3. Since bugs are discovered in the early stages of development, this approach has the potential to reduce overall testing costs.
  4. Because Unit testing is more reliable, it makes it easier to refactor code.
  5. This training additionally conditions engineers to reevaluate how they code.
  6. Specifically, developing modular parts that can be mocked if they have dependencies.
  7. Tests can be automated, which is very helpful for scaling code maintenance.
  8. Overall, it raises the code’s quality

Advantages of Unit testing

Advantages of Unit testing [PC: TestingExperts]

What are the Detriments of Unit testing?

  1. Integration or interface issues between two modules cannot be detected by unit testing. Non-functional aspects like the system’s scalability and performance cannot be tested.
  2. It is unable to detect system-wide errors involving multiple modules.
  3. The application’s business requirements or functional correctness cannot be guaranteed by unit tests as well.
  4. Depending on the level of complexity, one or more unit tests are typically required, hence it is necessary to increase the amount of code that must be written.
  5. It is very challenging to test the user interface (UI) and is useful for testing the implementation of business logic. However, unit testing is not great for UI as it is a back-end test. They can check that a calculation is correct, but they can’t verify whether the results display correctly to your user or not.
  6. Unit Testing cannot identify all programming errors, impossible for it to test integration errors.

The following are some of the best unit testing tools and frameworks, some of which we will use in our NodeJs test case integration:

  • Mocha – a JavaScript test framework running on Node.js and in the browser.
  • Chai – is an assertion library that adds a more expressive language to tests.
  • Jasmin – a behavior-driven development (BDD) framework for testing JavaScript code.
  • Jest – for testing javascript front-end and back-end applications.
  • There are a lot of unit testing frameworks available based on different languages, for more information you can refer to the below link: https://en.wikipedia.org/wiki/List_of_unit_testing_frameworks

Workflow

This is the unit testing workflow, which will help you better understand how it works.
Work Flow

Now that we’ve seen the advantages, drawbacks, and workflow, let’s try putting it into your system so we can come up with more ideas. First things first: what we need and how to set it up.

Before starting you need to check the below prerequisites in your system:

  • JAVA (Oracle JRE 11 or OpenJDK 11), you can also find more [details]
  • Should have NodeJS version 8 or higher installed
  • SonarQube and Sonar Scanner (refer SonarQube Integration in NodeJs) to download and install Sonar Scanner and SonarQube.

How to integrate it in NodeJs

Assuming that all the above prerequisites are installed in your system now you need to install two more npm packages by using the following steps

1) Install globally
npm install mocha -g

OR
2) install in the current directory
npm install mocha –save-dev OR npm install mocha –save

Which will be shown in your package.json file in the dependencies object as below

"dependencies': { 
  "chai": "^4.3.6",
  "chai-http": "^4.3.0",
  "dotenv": "^8.6.0",
  "express": "^4.17.1",
  "mocha": "^10.0.0",


After that, you need to add a test script in your package.json file in the script object

"test": "mocha --exit --colors src/test/**/*.ts",

Here is an example of a Test case:


//Import assert library
     const assert = require('assert');

   // We can group similar tests inside a describe block
     describe("Sum of two value",()=>{

     it("return 5 when sum of 1 and 4", ()=> {
     assert.equal(1+4,5);
     });
});

We can also write test cases for third-party API-called functions as well by using the Chai plugin. Now let’s look at the following steps of installing Chai as below:

1) Install globally
npm install chai -g

OR

2) install in the current directory
npm install chai –save-dev OR npm install chai –save


"dependencies': { 
"chai": "^4.3.6",

Which will be shown in your package.json file in the dependencies object as below

Here is an example of a Test case:

//Import chai library
const chai = require('chai') , chaiHttp = require('chai-http');

chai.use(chaiHttp);

// You create individual request for success and fail
it('request failed' function(done) {
 chai.request('http://localhost:3333')
  .get('/')
  .end (function (err, res) {
   expect(res), to.have.status(400);
   done();
  });
});

it('success request', function() {
 chai.request('http://localhost:3333')
  .get('/')
  .end (function (err, res) {
   expect(res), to.have.status(400);
  });
});

Run the below command in the terminal in your project root directory to start the sonar scanner: 

npm run test 

npm run coverage // will be used to show your code coverage report on sonar for this you need to add the below script in your package.json script object

"coverage": "nyc --reporter=lcov npm run test"

npm run sonar 

Once the command runs successfully, your dashboard will look like this:Dashboard

Summary

In short, if software testing is done well from the beginning of product development, businesses can be sure of bug-free and high-quality software. The program’s individual modules are tested using this testing strategy. Certain advantages such as early detection of bugs and code correction prior to their costly resolution in the SDLC can be achieved by teams as a result of this strategy. The earliest form of testing that focuses on the code is called unit testing. Businesses must engage in unit testing from the beginning of the software development lifecycle (SDLC) to guarantee quality and bug-free software.

As a result, defects are discovered, analyzed, and fixed when a straightforward automated test could have detected them.
8 Valuable Tips to Master Best Code Practices in Node.JS

Tell us Your
Big Idea!

  • =
  • This field is for validation purposes and should be left unchanged.

@2022 Solution Analysts Pvt Ltd. All Right Reserved