Learn Node.js unit testing with Jest, using mocking, snapshots, and best practices to ensure reliable and efficient application performance.
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.
There are several approaches for softwasre testing: Unit testing, Integration testing, and End-to-End testing, etc. In this article, We will discuss 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.
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.
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.
mkdir unit-testing-in-nodejs
cd unit-testing-in-nodejsnpm 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 }addTwoNumbers failed or passed. Let's call the addTwoNumbers function.console.log(addTwoNumbers(5, 3)) // return 8
console.log(addTwoNumbers(5, '3')) // return undefinedaddTwoNumbers(5, 3) function return the correct answer as expected. But the addTwoNumbers(5, "3") function return undefined.index.test.js and add the following codeconst 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 passnode index.test.js and It will show the following outputFailed: 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: 8There 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.
npm install jest --save-devscripts 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)
})npm run testnpx jest command to run .test.js files.npm install mocha -g
npm install mocha chai --save-devpackage.json"test": "mocha"npm install ava --save-dev"test":"ava"npm install jasmine --save-devnpx jasmine initjasmine.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",
]package.json"test": "jasmine"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.
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.
