
Jest is a Javascript Testing Framework by Facebook. It is used most commonly for unit testing. Unit testing is when you provide input to a unit of code(usually, a function) and match the output with the expected output.
Jest Features:
- zero config: As we will see later in this article, close to none configuration is required to get started with writing tests and deploying them. However, a config file can be supplied to the test suite as well.
- snapshots: Jest has the ability to enable snapshot testing as well. Essentially, the snapshots are matched with the saved snapshot and check for matching functionality.
- isolated tests: Jest tests are run parallelly to improve run time.
Setting up a jest project

npm install jest. The -D keyword installs jest as dev dependency
- Project Structure:
In the project root directory, make a tests folder. This folder will store all the test files.
Note that the js files(which are to be tested) are mapped by their names.
For example, index.js is mapped to index.test.js. This index.test.js file is placed in the ‘tests’ folder. This is the conventional project structure.
Start testing:
- To start, lets see a basic test workflow.

test – adding two pos nums
- To run the test, use the script
npm run test
- This will look for the test script mentioned in the package.json of the project.

pkg-json-test-script-ss. See test in scripts
We will use the ‘expect’ method to test our functions. The functions can also be tested using ‘describe’ and ‘it’.
A basic test: adding two positive nums and checking result.
//index.js
testForAdd: (a, b) => { return (a + b) },
//index.test.js
test('test adding two positive nums', function() {
expect(testFns.testForAdd(4, 5)).toBe(9);
});
When the ‘npm run test’ is run, the index.test.js file is gone through. Then the testForAdd function is run which is placed in the ‘testFns’ object. The toBe is used to ‘match’ the returned response from the test to what is expected. This ‘result matching’ leads to either a ‘fail’ or a ‘pass’.

test adding two pos nums
The following test will fail because of the ‘toBe(8)’.
//example of a failing test
test('test adding two positive nums - failing test', function() {
expect(testFns.testForAdd(4, 5)).toBe(8);
});
Opposite of toBe: not.toBe()
The opposite of the ‘toBe’ matcher is created by simply prefixing it with ‘not.’
For example:
//test successful - test for opposite of a matcher.
//The following test will 'Pass' if the returned value is not equal to 8.
test('test adding two positive nums - failing test', function() {
expect(testFns.testForAdd(4, 5)).not.toBe(8);
});
Using ‘toBe’ with JS Objects:
Let’s think of a case where every field of a JS object is to be tested. Jest provides us a way to do this using ‘toEqual’. The ‘toEqual’ is a deep-matcher(checks every field and sub-fields possible).
//expect toEqual example - check every field's value
// testFns.test_toEqual(gfgObj)
test('check gfgObj toEqual', () => {
let gfgObj = { name: "GFG" };
gfgObj['type'] = "company";
expect(gfgObj).toEqual({ name: "GFG", type: "company" });
});
Running the above test will ‘Pass’.

gfgobj toEqual
Another variation of doing this is matching two objects using the ‘toEqual’.
This is done so like this :
test('check gfgObj toEqual', () => {
let gfgObj = {
name: "GFG",
type: "company",
members: {
employees: 100,
contributors: 500
}
};
let testObj = {
name: "GFG",
type: "company",
members: {
employees: 100,
contributors: 500
}
};
expect(gfgObj).toEqual(testObj);
});
This test demonstrates the deep-matching feature of toEqual.
The above test passes as every key-pair in gfgObj matches with testObj.

gfgobj-testobj-toequal
toBeCloseTo – for floating point numbers and other approximate matches
//see here that a+b != c even though simple addition is taking place.
> var a = 1.32
> undefined
> var b = 2.31
> undefined
> c = a+b;
> 3.63
> var res = false;
> if(c==(a+b)) {c=true;}
> undefined
> c
> false
In such conditions, it is good to use ‘toBeCloseTo’ matcher from the Jest library.
test('floating point number - use toBeCloseTo instead', function() {
// const num1 = 0.3;
// const num2 = 0.2;
const result = 9.31 + 9.2;
expect(result).toBeCloseTo(18.51);
})
The above test passes too.
matching truthy and falsy:
https://jestjs.io/docs/en/using-matchers#truthiness
A lot of times, tests are written to check for truthy and falsy values returned by ‘expect’.
Falsy values in JS.
Truthy values in JS.
//checking for truthy values - All the tests will return truthy.
test('check for truthy', function() {
const gfgObj = {
first: null,
second: undefined,
third: false
}
expect(gfgObj.first).not.toBeTruthy(); // True - Pass
expect(gfgObj.second).toBeUndefined(); // True - Pass
expect(gfgObj.third).toBeFalsy(); // True - Pass
})
The above test passes.

truthy-test-js-all-test-passing
However, if any of the ‘expect’ above fails, Jest returns meaningful error messages like below.
Note that in above case, if any of the ‘expect’-s fail, the test also completely fails.

truthy-test-js-one-expect-failing-so-test-failing
Matching Numbers:
//tests for Number matches
test('test for numbers', function() {
const result = 3 + 9;
// expect(result).toBe(12); //the plain old matcher
expect(result).not.toBeLessThan(10); // result > 10
expect(result).toBeLessThan(15); // result < 15
expect(result).not.toBeGreaterThan(15); // result 10
expect(result).toBeGreaterThanOrEqual(12); //result >= 12
// expect(result).not.toBeGreaterThanOrEqual(12); // result == 12, this Fails
// expect(result).toBeLessThanOrEqual(10); // result >= 10, this Fails
})

number matching using jest
Testing values contained in arrays:
We can also test if particular values are contained in an array. Note that this test will ‘Fail’ if at least one value is not present in the array. For example,
//testing arrays
const gfgUsers = [
'user1',
'user2',
'user3'
];
test('test for a value in gfgUsers', function() {
// expect(gfgUsers).toContain('user2');
// expect(gfgUsers).not.toContain('user2');
//expect array containing
expect(gfgUsers).toEqual(expect.arrayContaining(['user1', 'user3']));
})
Th above test passes as user1 and user3 are present in gfgUsers.

user1-and-user3-in-gfgUsers
However, the following test will fail because ‘user4’ is not present in gfgUsers.
//testing arrays
const gfgUsers = [
'user1',
'user2',
'user3'
];
test('test for a value in gfgUsers', function() {
//expect array containing
expect(gfgUsers).toEqual(expect.arrayContaining(['user1', 'user4']));
})

arraycontaining-fail-due-to-user4-absence
Testing using Regex:
test('string match tests - toMatch - used for regex-es', function() {
const str = 'GeeksforGeeks';
// expect(str).toMatch(/f/);
// expect(str).toMatch(/Z/);
//you can create more complex Regexes
const str1 = 'This is a test paragraph. I wrote it.'
expect(str1).toMatch(/[pP][hH][\.]/); //matches 'ph.' in the word 'paragraph'
})

tomatch-matching-ph-in-paragraph
Extending the Matchers
Jest also has the provision to extend its ‘Matchers’ functionality, which is accomplished using the ‘expect.extend()’ keyword. The .extend() function is passed matchers as objects.
Syntax: expect.extend({matcher1, matcher2}) ;
For example, if we want to build a matcher that checks for a phrase presence in a string:
expect.extend({
stringPresent(receivedString, phraseString) {
bool phrasePresent = true;
var re = new RegExp(phraseString);
if (re.test(receivedString)) {
phrasePresent = true;
} else {
phrasePresent = false;
}
if (phrasePresent === true) {
return {
message: () =>
`string present`,
pass: true,
};
} else {
return {
message: () =>
`string absent`,
pass: false,
};
}
},
});
Dealing with exceptions
We can also check the types of errors that a unit of code throws. We can check the error thrown by name, message, object, etc.
Syntax:expect( fnName() ).toThrow( error );
The error parameter/argument is optional here.
Let’s suppose that we want to test a function by the message of the error thrown.
function testGFGMessage() {
throw new Error('this is testGFGMessage function error');
}
test('testing testGFGMessage', function(){
expect(testGFGMessage).toThrow('this is testGFGMessage function error');
})
There are many other ways to throw Errors and check for them. A detailed reference can be found here.
Skipping/Running a subset of tests
https://jestjs.io/docs/en/api#testskipname-fn
Jest also has a provision for skipping specific tests while running the test suite.
To implement it, simply use the ‘skip’ keyword. For example,
function addFn(num1, num2){
return num1 + num2;
}
test.skip('skip test example - skipping the addition test', () => {
expect(addFn(2, 3)).toBe(5);
});
The opposite of this is implementing only a subset of tests, which is achieved by using the ‘only’ keyword. For example,
function addFn(num1, num2){
return num1 + num2;
}
test.only('skip test example - skipping the addition test', () => {
expect(addFn(2, 3)).toBe(5);
});
Similar Reads
What is Destructuring in ES6 ?
Destructuring in ES6 is a convenient feature that allows you to extract values from arrays or objects and assign them to variables in a more concise and readable way. It simplifies the process of extracting specific data from complex structures. Destructuring Arrays:Basic Array Destructuring:const n
2 min read
How to work with Structs in JavaScript ?
Structs are typically found in languages like C, C++, and similar, and they provide a way to organize related data items under one name. Typically JavaScript does not have built-in support for structs, but you can achieve similar functionality using objects. Objects in JavaScript are dynamic collect
4 min read
What is Memoization in JavaScript ?
Memoization is an optimization technique used in computer programming to store the results of expensive function calls and return the cached result when the same inputs occur again. This can help to improve performance by avoiding redundant calculations. In JavaScript, memoization can be implemented
2 min read
JavaScript String prototype Property
The prototype property allows to add new properties and methods to the existing JavaScript object types. There are two examples to describe the JavaScript String prototype property. Syntax: object.prototype.name = valueReturn Value: It returns a reference to the String.prototype object. Example 1: T
2 min read
What are Closures in JavaScript ?
JavaScript closures involve the combination of functions and the scope in which they are defined. A closure allows a function to access variables from its scope, outer function scope, and the global scope. This creates a "closed-over" environment, preserving the state of the outer function even afte
1 min read
How are strings stored in JavaScript ?
In this article, we will try to understand how strings are stored in JavaScript. Strings are a primitive data type in JavaScript and are allocated a special place in memory to store and manipulate. Unlike some other languages, JavaScript does not have a String Constant Pool. Instead, JavaScript engi
3 min read
ES6 Merge Objects
In this article, we are going to learn how to merge two objects in JavaScript. We can merge two JavaScript Objects in ES6 by using the two popular methods. The methods are listed below: Object.assign() methodObject spread syntax method Using Object.assign() method: Using this method, we can merge tw
3 min read
Fabric.js extend() Method
The extend() method is used to create a copy of all the properties of the source objects over the destination object and return the destination object. Do not clone or extend fabric.Object subclasses. This is mostly for internal use and has extra handling for fabricJS objects, it skips the canvas pr
2 min read
What does '...' mean in JavaScript?
The '...' (or 3 dot symbol) in JavaScript is known Spread operator or Rest operator based on the usage. This syntax is used to expand the iterable into individual elements such as arrays, objects etc. Syntax for Spread Operator cosnt a1 = [ 10, 20, 30, 40 ];const a2 = [ ...a1, 50]; // Extracting the
4 min read
Collect.js duplicates() Method
The duplicates() function in collect.js is used to extract the duplicates from the given array. It returns an object containing key as the index of the duplicate and value as the duplicate itself. Installation: Using NPM:npm install collect.jsUsing CDN of collect.js<script src="https://cdnjs.com/
1 min read
Cloning an Object with Lodash
Cloning an object refers to creating a copy of an existing object. This is particularly useful in JavaScript to avoid unintentional mutations of the original object. Lodash provides various methods for cloning objects, allowing for shallow or deep copies depending on the use case. Below are the foll
3 min read
Interesting Facts about Object in JavaScript
Let's see some interesting facts about JavaScript Objects that can help you become an efficient programmer. JavaSctipt Objects internally uses Hashing that makes time complexities of operations like search, insert and delete constant or O(1) on average. It is useful for operations like counting freq
4 min read
JS Classes In JavaScript
Classes in JavaScript are a blueprint for creating objects, introduced in ES6. They encapsulate data and behavior by defining properties and methods, enabling object-oriented programming. Classes simplify the creation of objects and inheritance, making code more organized and reusable. Creating a Si
2 min read
What are factory functions in JavaScript ?
In JavaScript, a factory function is a function that returns an object. It is a way of creating and returning objects in a more controlled and customizable manner. Factory functions are a form of design pattern that enables the creation of objects with specific properties and behaviors. Why it is us
2 min read
Lodash _.extendWith() Method
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc. The _.extendWith() method of Object in lodash is similar to _.assignIn() method and the only difference is that it accepts customizer which is called in order t
2 min read
JavaScript Reflect set() Method
JavaScript Reflect.set() method in JavaScript is used to set the value of an object property. It returns a Boolean value true if the property is successfully set else it returns false. Syntax: Reflect.set(obj, Key, value, receiver) Parameters: This method accepts four parameters as mentioned above a
2 min read
JavaScript Set Reference
JavaScript Set is a collection of items that are unique, meaning no element can be repeated. Elements of the set can be iterated in the insertion order. A Set can store any type of value, whether primitive or objects. Syntaxnew Set()Example: This example will show the use of Set() constructor. [GFGT
3 min read
How to clone array in ES6 ?
The spread operator in ES6 is used to clone an array, whereas the slice() method in JavaScript is an older way that provides 0 as the first argument. These methods create a new, independent array and copy all the elements of oldArray to the new one i.e. both these methods do a shallow copy of the or
2 min read
What is an Object in JavaScript ?
An object in JavaScript is a non-primitive data type that is used to store multiple values of different primitive data types in the form of key-value pairs. A JavaScript object can be created using the following ways: Using Object literal: it is the most common way to create objects in JavaScript. I
1 min read