Automating Node.js Unit Testing With DroneCI Using Jest Framework

Written by PavanBelagatti | Published 2022/10/12
Tech Story Tags: continuous-integration | devops | devops-tools | programming | software-development | debugging | automation | quality-assurance

TLDRUnit testing is a crucial part of software development that has grown in popularity over the past few years. Testing software heavily relies upon continuous integration (CI) best practices and tools in the modern cloud-native world. Organizations need to focus on automated testing and make testing easy for developers so they can focus on building rich features. In this blog post, we’ll go over the basics of unit testing with Jest as an example, see why unit testing is important and show you how you can implement it in your project.via the TL;DR App

Software development processes have changed drastically over the years, from agile development to the DevOps practices that we see today. Additionally, software testing has gained tremendous momentum through new tools and automation. Testing software heavily relies upon continuous integration (CI) best practices and tools in the modern cloud-native world. Organizations need to focus on automated testing and make testing easy for developers so they can focus on building rich features. Hence, software testing is an essential process in the software development lifecycle (SDLC).

So what’s the best way to ensure that your code continues to work as you make future changes? Write unit tests. Unit testing is a crucial part of software development that has grown in popularity over the past few years. Why? Because it helps you identify potential bugs or issues before they occur, and it prevents them from ever making their way into production.

In this blog post, we’ll go over the basics of unit testing with Jest as an example, see why unit testing is important, and show you how you can implement it in your project.

What is Unit Testing?

Unit tests are small chunks of code that can validate individual functions, features, or methods. These tests focus on testing the logic behind your code rather than its behaviour. They don’t test user interfaces or performance but rather test if the code you wrote meets the expectations. Unit tests are also known as “test-driven development” (TDD). You might wonder why every code/feature gets tested with unit tests because it has many benefits: it can catch bugs before they go into production, prevent regression, and improve code quality over time. The main objective of unit testing is to ensure that individual units of source code operate as intended and do not have any hidden bugs or defects. Unit testing isn’t something you can turn on and off like a switch; it’s a process that needs to be part of your development workflow from the beginning.

Jest Framework for Unit Testing

Image credit: openbase

Jest is a JavaScript testing framework created by Facebook and used to test JavaScript code. Jest has many features that make it a better choice than other testing frameworks like Jasmine or Mocha. It has the ability to test asynchronous code without introducing any complexities. In addition, it is designed to take advantage of the benefits of using a mocking library in conjunction with a test runner. It also provides many other helpful features that are not available in other frameworks.

Pre-requisites:

  • Install Docker Desktop.
  • Download and install Node.js from the official website here.
  • Ngrok to create a tunnel to the internet so our Drone CI process can receive webhook traffic from GitHub.
  • Drone CI set-up. Follow this simple tutorial to get Drone CI up and running on your local machine.

Tutorial:

  • Create a new directory to store all the source code of this tutorial and enter to the root of the directory:

mkdir jest-unit-testing

cd jest-unit-testing

  • Initiate the node application with the following command:

npm init -y

You should see the package.json file getting created after you run the above command on your terminal.

  • Now, since we are using __Jest__as our unit testing framework, we need to add Jest as a dependency for our project. Let’s add it by running the following command:

npm install --save-dev jest


Now, you can go back to your package.json file and confirm that Jest has been added as a dependency.

  • Also, we need to specify the unit test framework used in the package.json file. We need to replace the "test": "echo \"Error: no test specified\" && exit 1" to "test": "jest" in the package.json file.

Finally, your package.json file should look like this:

  • Let’s create the main application logic in a new file calculator.js and let’s add the following code into it:

const mathOperations = {

   sum: function(a,b) {

       return a + b;

   },

   

   diff: function(a,b) {

       return a - b;

   },

   product: function(a,b) {

       return a * b

   }

}

  module.exports = mathOperations


In the above example, we are basically using mathOperations - addition, subtraction and multiplication - as our logic.

  • It is time to write a test case using Jest framework for the logic that we have created above. For this, create a new file calculator.test.js in the same root directory and add the following code:

const mathOperations = require('./calculator');

 

describe("Calculator tests", () => {

 test('adding 2 + 4 should return 6', () => {

   // arrange and act

   var result = mathOperations.sum(2,4)

   // assert

   expect(result).toBe(6);

 });

 

 test("subtracting 3 from 10 should return 7", () => {

   // arrange and act

   var result = mathOperations.diff(10,3)

 

   // assert

   expect(result).toBe(7);

 });

 

 test("multiplying 3 and 9 should return 27", () => {

   // arrange and act

   var result = mathOperations.product(3,9)

 

   // assert

   expect(result).toBe(27);

 });

})

  • Finally, let’s test it locally by using the following command on our terminal:

npm test


You should see that the tests passed successfully for the inputs we provided in thecalculator.test.js file. You can alter this file and add your own values.

The source code of the example project is shared here:  https://github.com/pavanbelagatti/jest-unit-test-drone

Continuous Integration with Drone CI

In our example project, the codebase is small and we can easily manage it, but what if the project gets bigger and more developers start working on it?

Developers usually collaborate and work with DevOps tools for more productivity and efficiency. One prominent tool is GitHub, which helps developers push and merge their code to the main branch. Whenever developers push their code, there has to be a system to automatically test the code and alert for possible bugs or errors. Manual testing takes a lot of time and it is not trustworthy in most cases. This is where continuous integration comes into the picture. Drone CI by Harness, a continuous integration testing tool, has emerged as one of the best open-source tools in the market. It tests and builds against the tests specified. It’s also very simple to set up and easy to understand.

Let’s set up a Drone CI server on our local machine to automate our testing.

My colleague’s article will help you get your own Drone CI up and running.

Using a CI server like Drone helps companies find bugs and rectify the errors before they reach customers.

While working with Drone CI, you need a configuration file .drone.yml.  Below is the sample file for node projects:

kind: pipeline

name: default

steps:

- name: test

  image: node

  commands:

  - npm install

  - npm test

Our code repo already has this configuration file.


When you open the Drone UI, you will see a welcome message and you need to enter some basic information as part of the sign up process.

Once you log in, you will see all your repositories listed. Select the one we are working on. Activate the repository by going to the settings and adding secrets. Secrets are basically your Docker hub username and password.

Click on the new build after adding the secrets. You should see the screen as shown below:

How cool is that. You can see the test executed successfully. Now, whenever someone pushes any code to the main branch, the drone starts its magic and runs the test specified, in this case, the Jest unit test framework.

Drone Desktop

Some of you might wonder if there is a Drone extension you can use instantly without setting up DroneCI on your computer. Well, we have it for you. You just need to have Docker Desktop installed on your computer, and using the below command, you can easily set up the Drone extension in a minute.

docker extension install drone/drone-ci-docker-extension:latest

See, it is very straightforward. Click on the Import Pipelines tab.

You will be prompted to search and add your repo that has a .drone.yml file. So let’s go ahead and add our repo.

Then, click on the Run Pipeline button under Actions to trigger your pipeline.

Once you click on the Run Pipeline button, you will be prompted to add some information required to run the pipeline, such as the secrets file to be used, environment variables if needed, and the stages to be run by the pipeline.

We only have one simple step, i.e Test and don’t have an environment variables file and a secret file. After selecting the step as test, click the Runtab.

You will see the pipeline executing successfully if the step passes.

You can check the logs too.

Finally, you should see the pipeline completed successfully within minutes, depending on the steps included in the pipeline to execute. Congratulations on successfully running your CI pipeline through the DroneCI Docker extension. You can also refer to this detailed tutorial on the __DroneCI Docker extension __to know about running continuous integration using DroneCI on your laptop in minutes.

Also published here.


Written by PavanBelagatti | Developer Advocate at Harness!
Published by HackerNoon on 2022/10/12