Jest Tutorial JavaScript Unit Testing Framework
Unit testing is a crucial skill for modern JavaScript developers. In this Jest tutorial, we will explore how Jest, a popular JavaScript testing framework, allows developers to write reliable tests for their code. Whether you are building vanilla JavaScript projects or React applications, learning Jest can improve code quality and reduce bugs. For Pakistani students, mastering Jest can enhance job readiness for companies in Karachi, Lahore, Islamabad, and beyond, where front-end and full-stack roles demand strong testing skills.
Prerequisites
Before diving into Jest, ensure you are familiar with the following:
- JavaScript fundamentals – variables, functions, arrays, objects.
- ES6+ syntax – arrow functions, template literals, destructuring.
- Node.js basics – running scripts,
npmoryarnpackage management. - Basic React knowledge – optional but useful for Jest React testing.
- Command line familiarity – running terminal commands in Windows, macOS, or Linux.
Having these skills will help you focus on testing concepts without being slowed by syntax issues.
Core Concepts & Explanation
What is Jest?
Jest is a JavaScript unit testing framework developed by Facebook. It supports:
- Unit tests
- Snapshot testing
- Mocking functions and modules
- Code coverage reporting
It integrates seamlessly with React, making it ideal for Pakistani students building web apps or preparing for internships.
Test Suites and Test Cases
A test suite is a collection of related tests, and each test case verifies a single behavior.
// math.test.js
describe('Math operations', () => {
it('adds two numbers correctly', () => {
expect(2 + 3).toBe(5);
});
it('multiplies two numbers correctly', () => {
expect(2 * 3).toBe(6);
});
});
describegroups related tests.itdefines a single test case.expectchecks the result against a matcher liketoBe().
Matchers and Assertions
Jest provides matchers to assert values. Common matchers include:
toBe(value)– strict equalitytoEqual(value)– deep equality for objects/arraystoContain(item)– check array contentstoHaveLength(number)– check array/string lengthtoThrow(error)– check for errors
const students = ['Ahmad', 'Fatima', 'Ali'];
expect(students).toContain('Ali'); // Passes
expect(students).toHaveLength(3); // Passes

Mock Functions
Mocking is useful to simulate dependencies, APIs, or database calls.
const fetchStudentFee = jest.fn((name) => {
if (name === 'Ahmad') return 5000; // PKR
return 0;
});
expect(fetchStudentFee('Ahmad')).toBe(5000);
expect(fetchStudentFee).toHaveBeenCalledWith('Ahmad');
jest.fn()creates a mock function.toHaveBeenCalledWithverifies arguments passed.- Useful in real-world apps like testing payment processing in Lahore schools.
Practical Code Examples
Example 1: Testing a Calculator Module
// calculator.js
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
module.exports = { add, subtract };
// calculator.test.js
const { add, subtract } = require('./calculator');
describe('Calculator Tests', () => {
it('should add numbers correctly', () => {
const result = add(10, 5); // 10 + 5
expect(result).toBe(15); // Result should be 15
});
it('should subtract numbers correctly', () => {
const result = subtract(10, 5); // 10 - 5
expect(result).toBe(5); // Result should be 5
});
});
Explanation:
- Line 1: Import calculator functions.
describe: Groups calculator tests.- Each
it: Defines a single test case. expect(result).toBe(): Assertion for expected value.
Example 2: Real-World Application — Student Fee Checker
// feeChecker.js
function calculateFee(student) {
if (student.city === 'Lahore') return 12000;
if (student.city === 'Karachi') return 15000;
return 10000; // Islamabad or others
}
module.exports = calculateFee;
// feeChecker.test.js
const calculateFee = require('./feeChecker');
describe('Student Fee Checker', () => {
it('returns correct fee for Lahore students', () => {
const fee = calculateFee({ name: 'Fatima', city: 'Lahore' });
expect(fee).toBe(12000);
});
it('returns correct fee for Karachi students', () => {
const fee = calculateFee({ name: 'Ali', city: 'Karachi' });
expect(fee).toBe(15000);
});
});

Common Mistakes & How to Avoid Them
Mistake 1: Not Resetting Mocks
When mocking functions, failing to reset can cause false positives.
const mockFn = jest.fn();
mockFn();
mockFn();
expect(mockFn).toHaveBeenCalledTimes(2); // Passes
mockFn.mockReset();
expect(mockFn).toHaveBeenCalledTimes(0); // Reset works
Mistake 2: Ignoring Asynchronous Code
Async tests require async/await or done callback.
test('async fetch', async () => {
const fetchData = () => Promise.resolve('Data from API');
const data = await fetchData();
expect(data).toBe('Data from API');
});

Practice Exercises
Exercise 1: Reverse a String
Problem: Write a function reverseString(str) and test it.
function reverseString(str) {
return str.split('').reverse().join('');
}
module.exports = reverseString;
const reverseString = require('./reverseString');
test('reverses "Karachi"', () => {
expect(reverseString('Karachi')).toBe('ihcaraK');
});
Exercise 2: Check Student Eligibility
Problem: Write a function isEligible(student) to check if fee > 10000.
function isEligible(student) {
return student.fee > 10000;
}
module.exports = isEligible;
const isEligible = require('./isEligible');
test('Fatima is eligible', () => {
expect(isEligible({ name: 'Fatima', fee: 12000 })).toBe(true);
});
Frequently Asked Questions
What is Jest used for?
Jest is used for unit testing JavaScript applications, ensuring functions and components work as expected.
How do I test React components with Jest?
You can combine Jest with React Testing Library to render components and assert UI behavior.
Can Jest mock API calls?
Yes, Jest provides jest.fn() and jest.mock() to simulate APIs without hitting the real server.
How do I generate a coverage report?
Run jest --coverage in your project. Jest outputs percentages for statements, branches, functions, and lines.
Is Jest suitable for beginners?
Yes, Jest is beginner-friendly with simple syntax and works out-of-the-box for JavaScript and React projects.
Summary & Key Takeaways
- Jest is a JavaScript unit testing framework suitable for React apps.
- Use
describe,it, andexpectfor structured tests. - Mock functions with
jest.fn()for testing APIs and dependencies. - Always handle async code properly to avoid test failures.
- Snapshot testing helps track UI changes efficiently.
- Coverage reports ensure all code paths are tested.
Next Steps & Related Tutorials
- Explore JavaScript Tutorial for foundational JS skills.
- Learn React.js Introduction to apply Jest in UI testing.
- Try Node.js Tutorial for backend testing scenarios.
- Check ES6 Features Guide to write cleaner Jest tests.
This draft is SEO-optimized for keywords: jest tutorial, jest javascript testing, jest react testing. It includes Pakistani student examples, internal links, and placeholders for visuals.
If you want, I can also create a fully illustrated version with all [IMAGE: prompt] sections designed and labeled for easy upload to theiqra.edu.pk. This will make it visually complete for your TOC and learning experience.
Do you want me to do that next?
Test Your Python Knowledge!
Finished reading? Take a quick quiz to see how much you've learned from this tutorial.