Jest is a JavaScript testing framework developed by Facebook, designed primarily for unit testing React applications. However, it can be used for testing any JavaScript codebase.
Jest is known for its simplicity, speed, and built-in features, making it one of the most popular choices for testing JavaScript applications.
Setting Up Jest
To get started with Jest
1. Install Jest
Run the following command to install Jest as a dev dependency.
npm install --save-dev jest
If you are using React (Create React App), Jest comes pre-installed.
2. Add a Test Script in package.json
In your package.json file, modify the scripts section to include a test command.

Now, you can run tests using
npm test
Writing Your First Jest Test
Jest makes it easy to write tests for your functions. Below is a simple example of testing a basic function.
JavaScript
//sum.test.js
const add=require('./sum.js')
test('first test',()=>{
expect(add()).toBe(5)
})
JavaScript
//sum.js
function sum(){
return 2+3
}
module.exports=sum
Run the Tests
Now that Jest is installed and your test is written, run the tests using the following command. Each time this command will be used to run the test case.
npm run test

- The sum function simply returns the sum of two numbers.
- The test function defines the test, and expect(sum(1, 2)).toBe(3) checks if the result matches the expected value.
- The test will pass if the result is 3, otherwise, Jest will report a failure.
Testing Asynchronous Code
Jest makes it easy to test asynchronous functions using async/await or returning promises.
JavaScript
// fetchD.js
function fetchD() {
return new Promise((resolve) => {
setTimeout(() => resolve('Date loaded'), 1000);
});
}
module.exports = fetchD;
JavaScript
// fetchD.test.js
const fetchData = require('./fetchData');
test('fetches data successfully', async () => {
const data = await fetchData();
expect(data).toBe('Data loaded');
});
Testing Asynchronous Code- The fetchD function returns a promise that resolves after 1 second with the value 'Data loaded'.
- The await keyword waits for the promise to resolve, and the result is checked using expect().
Mocking in Jest
Jest provides built-in functionality to mock functions, helping to isolate tests.
JavaScript
// api.js
function API() {
return 'Real data from API';
}
module.exports =API;
JavaScript
const API = require('./api');
jest.mock('./api');
test('mocked fetchDataFromAPI returns mocked data', () => {
API.mockReturnValue('Mocked data');
const data =API();
expect(data).toBe('Mocked data');
});
- jest.mock('./api') is used to mock the API function from the api.js file.
- API.mockReturnValue('Mocked data') ensures that when the mocked function is called, it returns 'Mocked data' instead of its original value.
Practical Cases of Testing with jest
1. Testing a normal function in jest
A function is written and exported in one file, imported in the test file, and tested using Jest's test() and expect() functions.
JavaScript
//sum.test.js
const add=require('./sum.js')
test('first test',()=>{
expect(add()).toBe(5)
})
JavaScript
//sum.js
function sum(){
return 2+3
}
module.exports=sum
Testing a normal function in jest
- The sum function returns 5 and is exported using module.exports.
- The result is tested in sum.test.js with test() and expect().
- The test is run using npm run test.
2. Testing a function with parameter's in jest
In this function we will test function with parameter's in a dynamic way.
JavaScript
//sum.js
function sum(a,b){
return a+b
}
module.exports=sum
JavaScript
//sum.test.js
const add=require('./sum.js')
test('first test',()=>{
expect(add(2,3)).not.toBe(3)
})
Testing a function with parameter's in jest
- The sum function returns the sum of its two parameters a and b.
- In sum.test.js, test() and expect() check if the result matches the expected value.
- The test is run using npm run test.
3. Testing a object in jest
Object's can also be checked with the use of toEqual() function in jest.
JavaScript
//sum.js
function sum(){
return {name:"Pranjal"}
}
module.exports=sum
JavaScript
//sum.test.js
const add=require('./sum.js')
test('first test',()=>{
expect(add()).toEqual({name:"Pranjal"})
})
Testing a object in jest- The sum function returns an object { name: "Pranjal" }.
- In sum.test.js, test() and expect() with toEqual() check if the returned object matches the expected value.
- The test passes if the values match, otherwise it fails.
4. Testing callback functions
To test callback functions, use Jest's test() with done, pass the callback, and call done() after the assertion.
JavaScript
//sum.js
function fetchData(cb)
{
return cb('Hi')
}
module.exports=fetchData
JavaScript
//sum.test.js
const fetchData = require('./sum.js')
test('first test', (done) => {
function callback(data) {
try {
expect(data).toBe('Hello')
done()
}
catch (err) {
done(err)
}
}
fetchData(callback)
})
Testing callback functions- The fetchData function in sum.js takes a callback and passes 'Hi' as a string.
- In sum.test.js, fetchData is imported, and the callback is tested with done to check if the data matches the expected value.
- The test passes if the data matches, otherwise it fails.
Why Use Jest?
- Zero Configuration: Works out of the box with minimal setup.
- Fast and Efficient: Runs tests in parallel for improved performance.
- Snapshot Testing: Helps track UI changes over time.
- Mocking Capabilities: Easily mocks functions, modules, and APIs.
- Code Coverage: Provides insights into untested parts of your code.
Similar Reads
Next.js Vitest Testing
Next.js is a popular React framework known for its server-side rendering, static site generation, and hybrid capabilities, which make it an excellent choice for building high-performance, SEO-friendly web applications. Vitest is a fast and lightweight testing framework, inspired by Vite, designed to
2 min read
NextJS Jest Testing
Jest is a delightful JavaScript testing framework with a focus on simplicity. It's widely used with React applications and integrates well with Next.js to provide robust testing capabilities. This article explores how to set up and use Jest for testing in a Next.js application.Steps to Create an App
2 min read
Unit Testing in Devops
In today's rapidly evolving digital world developers are eager to deliver high-quality software at a faster pace without any errors, issues, or bugs, to make this happen the importance of Unit testing in DevOps continues to grow rapidly. unit testing helps the DevOps team to identify and resolve any
9 min read
Performance testing with k6
What is Performance and Load Testing? Performance Testing is the process of analyzing the quality and capability of a product. Load testing is a subset of performance testing where we analyze the behavior of the application under normal or peak load conditions. What is k6? k6 is an open-source load
3 min read
What is Scripted Testing?
Testing practices and their related approaches can be divided into different forms according to needs and specific contexts. Among these, scripted testing is one of the common testing methodologies that is used by most organizations. This article focuses on scripted testing, when and where it is use
7 min read
What is Chaos Testing?
Since the world of software development is highly competitive, it is crucial to guarantee that particular systems are fail-safe and can recover in case of failure. Chaos testing or chaos engineering is a way that aims to inject failures into the thing to be tested and observe the response. Such an a
5 min read
How to Test TypeScript with Jest?
Jest, a powerful JavaScript testing framework, seamlessly integrates with TypeScript, providing all the tools needed to write and run tests for your TypeScript code, ensuring quality and reliability. It handles TypeScript compilation automatically, offers features like mocking and code coverage, and
3 min read
Unit Testing - Software Testing
Unit Testing is a software testing technique in which individual units or components of a software application are tested in isolation. These units are the smallest pieces of code, typically functions or methods, ensuring they perform as expected. Unit testing helps identify bugs early in the develo
12 min read
GUI Testing Tool
GUI Testing is the process of ensuring that the application's graphical user interface works as expected. It entails inspecting application elements like buttons, icons, checkboxes, color, menus, and windows, among other things. The visual dynamics of a web application are critical in determining wh
12 min read
WireMock - Verifying with JUnit Test
In Wiremock, Verification comes after stubbing and request matching. Verification is to check with the Wiremock server as to whether a given request was received by it or not. In Wiremock, at least until it is reset the WireMock server records all requests it receives in memory. And this makes it po
4 min read