Quedemy
Sign In
unit-testing-in-node-js

How To Perform Unit Testing in Node JS


Testing is a part of the software development process. We write one or more tests to examine the software. Testing reduces the chance of software failure. Testing is like an exam for software that validates the code of the software.

Unit Testing Analogy

Consider, A teacher writes test papers and examines the knowledge of students using test papers. Then Students failed or passed based on their performance. In the same way, We write the test cases and examine the code of the software. As a result, the software either passes or fails.

There are several approaches for software testing: Unit testing, Integration testing, and End-to-End testing, etc. In this article, We will discuss Unit Testing in node js.

What is Unit Testing in Node JS?

Unit testing in Node JS individually validates the component of the code in software applications. This component could be a class, function, etc. For example, A teacher checks each answer of test copies of the student. In the same way, developers examine each component of the code in software applications.

Unit testing helps to reduce bugs and improve the quality of software. Hence, We spend less time fixing errors and write more efficient code. We can find code failure early with the help of unit testing in node js. Introducing unit testing in the node js application also helps other developers understand the working of code while working with a team.

Why is Unit Testing Important?

Consider, You launch an application with a sign-up form. And Somehow it fails which leaves a bad user experience. Therefore, It is better to test the software application before launch. And Unit testing helps to reduce software failure.

  • Unit Testing prevents unexpected software failures.
  • Unit Testing in node js helps you to enhance the efficieny of your code.
  • Unit Tests can help you ensure that your code of software works as expected.
  • Unit Tests identify bugs early in the development process and improve the stability of the software.
  • Unit testing also helps to make sure that software meets the user requirements and maintains the legacy of the code throughout the development process.
  • Unit Tests also verify that the new changes in code don't break the functionality of the previous code.
  • Therefore, Unit Tests are pretty much helpful while working with a large codebase.

Getting Started with Unit Testing in Node JS

Writing a unit test is the same as writing code for software. We will write unit tests in nodejs without any framework or dependencies first. Then We will use javascript testing frameworks to write unit tests in nodejs.

Creating a Simple Node JS Application

mkdir unit-testing-in-nodejs
cd unit-testing-in-nodejs
npm init -y
{
	"name": "unit-testing-in-nodejs",
	"version": "1.0.0",
	"description": "",
	"main": "index.js",
	"scripts": {
		"test": "echo \"Error: no test specified\" && exit 1"
	},
	"keywords": [],
	"author": "",
	"license": "ISC"
}

We will create a file named index.js and write a simple addTwoNumbers function to add two numbers.

// Add two numbers
function addTwoNumbers(a, b) {
	if (typeof a === 'number' && typeof b === 'number') {
		return a + b
	}
}
module.exports = { addTwoNumbers }

Testing Manually

  • We will verify manually that function addTwoNumbers failed or passed. Let's call the addTwoNumbers function.
console.log(addTwoNumbers(5, 3)) // return 8
console.log(addTwoNumbers(5, '3')) // return undefined
  • addTwoNumbers(5, 3) function return the correct answer as expected. But the addTwoNumbers(5, "3") function return undefined.
  • Here, we can check the answer manually. But it is not possible to check code manually when working with a large team and software.
  • Therefore, we write unit tests in node js that examine our code automatically.

Write and Run Unit Test in Node JS

  • Create a new file named index.test.js and add the following code
const main = require('./index')
const assert = require('assert')

let output1 = main.addTwoNumbers(5, '3') // return undefined
let output2 = main.addTwoNumbers(5, 3) // return 8
let expectedOutput = 8

function testAddTwoNumbers(output, expectedOutput) {
	try {
		assert.equal(output, expectedOutput)
		console.log(
			'\nPassed: Actual output matched the expected output.',
			'\nExpected Output:',
			expectedOutput,
			'\nActual Output: ',
			output,
		)
	} catch {
		console.error(
			'\nFailed: Actual output did not match the expected output.',
			'\nExpected Output:',
			expectedOutput,
			'\nActual Output: ',
			output,
		)
	}
}

testAddTwoNumbers(output1, expectedOutput) // It will fail
testAddTwoNumbers(output2, expectedOutput) // It will pass
  • Run the test using the command node index.test.js and It will show the following output
Failed: Actual output did not match the expected output.
Expected Output: 8
Actual Output: undefined

Passed: Actual output matched the expected output.
Expected Output: 8
Actual Output: 8

Testing Frameworks for Unit Testing in Node JS

There are various testing frameworks for unit testing in node js: Jest, Mocha, ava, Jasmine, Tap, etc. We will discuss quick ways to start working with various testing frameworks.

Jest: Install and Set up Unit Testing in Node JS

npm install jest --save-dev
  • Replace the scripts property in package.json as shown below
"scripts": {
  "test": "jest"
}
const main = require('./index')

test('Add Two Numbers', () => {
	let output = main.addTwoNumbers(5, 3)
	expect(output).toBe(8)
})
  • Run the test
npm run test
  • We can also use the npx jest command to run .test.js files.

Mocha and Chai: Install and Set up Unit Testing in Node JS

  • Mocha and chai are generally used together. Mocha is a test runner and chai is an assertion library.
  • Install Mocha and Chai with the following command
npm install mocha -g
npm install mocha chai --save-dev
  • Change the following property in package.json
"test": "mocha"

Ava: Install and Set up Unit Testing in Node JS

npm install ava --save-dev
"test":"ava"

Jasmine: Install and Set up Unit Testing in Node JS

npm install jasmine --save-dev
npx jasmine init
  • The above command will create a jasmine.json and add the following code block that specifies the directory where we write our tests.
"spec_dir": "specs",
"spec_files": [
  "**/*[sS]pec.?(m)js",
]
  • Change the following property in package.json
"test": "jasmine"

Frequently Asked Questions (FAQs)

What is the objective of Unit Testing?

Unit testing helps to prevent unwanted errors in the application. The objective of unit testing is to verify that each component of the application is working as expected.

What are the Unit Testing Tools?

There is various tool to perform unit testing. Some of them are NUnit, XUnit, JUnit, and MSTest. Selenium is the most popular framework to perform automation in the browser. These tools involve performing automation tests and generating reports. It helps us to improve productivity and accuracy.