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
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
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
Automating API Testing with Postman Testing the functionality, dependability, and performance of an API is known as API testing. API testing can be done automatically or manually. The technique of automating the execution of API tests with tools is known as automated API testing. This can save time and effort, as well as ensure that A
5 min read
Getting Started with Postman API Testing Postman is an API(application programming interface) development tool that helps to build, test and modify APIs. Almost any functionality that could be needed by any developer is encapsulated in this tool. It is used by over 5 million developers every month to make their API development easy and sim
3 min read