Unit Testing JavaScript Code using Jest

Jest is a framework to test JavaScript and Node.js code. It smoothly works with JavaScript programs and quickly executes unit tests.

Command to install Jest: npm install –save-dev jest

Modify package.json:
{
“scripts”: {
“test”: “jest”
}
}

Testing if an array contains specific desired values:
// initializing an array with specific values
const premiumUsers = [
‘Sachin’,
‘Rahul’,
‘Shoaib’
];
// test() contains expect() that looks for a match
test(‘test for specific values in premiumUsers’, function() {
// expecting the array containing two specific values
expect(premiumUsers).toEqual(expect.arrayContaining([‘Rahul’, ‘Shoaib’]));
// or, expect(premiumUsers).toContain(‘Sachin’);
})

// The above test will result in a PASS success.

Testing the summation result of a calculation:
// testForAddition.js
testForAddition: (num1, num2) => {
return (num1+num2)
},

// testForAddition.test.js
test(‘test of adding two numbers’, function() {
expect(testFns.testForAddition(112, 67)).toBe(179);
});

The above test should pass with the following result:

Command to run a test: yarn test or npm test

Official documentation link: https://jestjs.io/

Published by Farial Mahmod Tishan

Life-long learner. Developing mobile apps and solving coding challenges.

Leave a comment

Design a site like this with WordPress.com
Get started