Testing with Jest (original) (raw)

Last Updated : 07 Feb, 2025

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.

Screenshot-2025-01-13-173931

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

Screenshot-2025-01-13-152758

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'); });

`

Screenshot-2025-02-07-154135

Testing Asynchronous Code

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'); });

`

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

`

Screenshot-2025-01-13-152758

Testing a normal function in jest

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) })

`

Screenshot-2025-01-13-155112

Testing a function with parameter's in jest

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"}) })

`

Screenshot-2025-01-13-163054

Testing a object in jest

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)

})

`

Screenshot-2025-01-13-162833

Testing callback functions

**Why Use Jest?