Aug 8, 2024

Performing Functional Testing Using Jest For QA

Dive into functional testing with Jest and learn how to write maintainable tests that ensure your JavaScript applications perform flawlessly.

Author

Sankalp Nihal PandeySoftware Engineer
Performing Functional Testing Using Jest For QA

Functional testing is black-box testing that ensures software behaves as expected, validating that each application function operates in conformance with the requirement specification. Jest, a robust JavaScript testing framework developed by Facebook, is particularly effective for testing JavaScript applications, including those built with React. This comprehensive guide will walk you through setting up and performing functional testing using Jest.

Why Jest for Functional Testing?

Jest is favored for functional testing due to its numerous advantages:

  • Ease of Use: Minimal configuration is required, making setting up and testing simple.
  • Rich Assertion Library: Comes with built-in assertions, eliminating the need for additional libraries.
  • Snapshot Testing: Allows easy UI testing by comparing the current output with a stored snapshot.
  • Coverage Reporting: Integrated coverage reporting helps to assess the thoroughness of tests.
  • Parallel Execution: Tests run parallel, speeding up the overall test suite execution.

Prerequisites

Before starting, ensure you have the following:

  • Node.js and npm: Installed and set up on your machine.
  • Basic JavaScript Knowledge: Understanding of JavaScript and testing concepts.
  • Initialized Project: Your JavaScript project should have a package.json file.

Setting Up Jest

Install Jest: Open your terminal and run:

npm install --save-dev jest

Configure Jest: Add a test script in your package.json file to enable running tests using npm:

"scripts": {
  "test": "jest"
}

Create a Configuration File (Optional): For more advanced configurations, create a jest.config.js file:

 module.exports = {
  testEnvironment: 'node',
  verbose: true,
  collectCoverage: true,
  coverageDirectory: 'coverage',
  coverageReporters: ['text', 'lcov'],
};

Writing Functional Tests with Jest:-

Functional tests typically involve writing test cases for individual functions or components to ensure they meet the expected behavior.

  1. Creating a Test File: Jest automatically recognizes files with extensions .test.js or .spec.js. Create a file named sum.test.js.

2. Writing a Simple Test:

// sum.js
function sum(a, b) {
  return a + b;
}
module.exports = sum;

// sum.test.js
const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

3. Running the Test: Execute your tests by running:

npm test

Advanced Functional Testing Techniques :-

  1. Testing Asynchronous Code: Handling asynchronous code in Jest can be done using async/await or Promises.
// fetchData.js
const fetchData = () => {
  return new Promise((resolve) => {
    setTimeout(() => resolve('data'), 1000);
  });
};
module.exports = fetchData;

// fetchData.test.js
const fetchData = require('./fetchData');

test('fetches data', async () => {
  const data = await fetchData();
  expect(data).toBe('data');
});

2. Mocking Functions: Jest provides powerful tools for mocking functions to isolate and test units of code.

// user.js
const fetchData = require('./fetchData');
const getUser = async (userId) => {
  const data = await fetchData();
  return { id: userId, data };
};
module.exports = getUser;

// user.test.js
const getUser = require('./user');
jest.mock('./fetchData');
const fetchData = require('./fetchData');

fetchData.mockResolvedValue('mockData');

test('gets user with mocked data', async () => {
  const user = await getUser(1);
  expect(user).toEqual({ id: 1, data: 'mockData' });
});

3. Snapshot Testing: Snapshots are particularly useful for testing UI components to ensure they render correctly.

// Link.js
const Link = ({ page, children }) => (
  <a href={page}>
    {children}
  </a>
);
module.exports = Link;

// Link.test.js
const renderer = require('react-test-renderer');
const Link = require('./Link');

test('renders correctly', () => {
  const tree = renderer.create(<Link page="<http://www.example.com>">Example</Link>).toJSON();
  expect(tree).toMatchSnapshot();
});

4. Integration with React Testing Library: Combining Jest with React Testing Library enhances the testing capabilities for React components.

// MyComponent.js
const MyComponent = () => (
  <div>
    <button>Click me</button>
  </div>
);
module.exports = MyComponent;

// MyComponent.test.js
import React from 'react';
import { render, screen } from '@testing-library/react';
import MyComponent from './MyComponent';

test('renders button', () => {
  render(<MyComponent />);
  const buttonElement = screen.getByText(/click me/i);
  expect(buttonElement).toBeInTheDocument();
});

Best Practices for Functional Testing with Jest :-

  1. Isolate Tests: Ensure that tests are independent and do not rely on each other. Each test should set up and tear down its environment.

  2. Use Descriptive Test Names: Clear and descriptive test names help understand what is being tested and the expected outcome.

  3. Mock External Dependencies: Mock any external services or APIs to ensure tests are reliable and run quickly.

  4. Maintainable Test Code: Write clean and maintainable test code. Refactor tests when necessary to improve readability and maintainability.
  5. Test Coverage: Utilize Jest’s coverage reporting feature to ensure comprehensive testing. This helps identify untested parts of the code.
npm test -- --coverage

Example of Comprehensive Functional Testing :-

Let's consider a more comprehensive example involving a simple user authentication system.

Authentication Logic:

// auth.js
const users = [{ username: 'user1', password: 'pass1' }];

const authenticate = (username, password) => {
  const user = users.find(user => user.username === username && user.password === password);
  return user ? 'Authenticated' : 'Authentication Failed';
};

module.exports = authenticate;

Authentication Test:

// auth.test.js
const authenticate = require('./auth');

describe('Authentication tests', () => {
  test('successful authentication', () => {
    expect(authenticate('user1', 'pass1')).toBe('Authenticated');
  });

  test('failed authentication with wrong password', () => {
    expect(authenticate('user1', 'wrongpass')).toBe('Authentication Failed');
  });

  test('failed authentication with non-existent user', () => {
    expect(authenticate('nonexistent', 'pass')).toBe('Authentication Failed');
  });
});

Conclusion

Jest is a powerful and versatile tool for functional testing in JavaScript applications. Its ease of use, integrated features, and ability to handle asynchronous code, mocks, and snapshots make it an excellent choice for ensuring software quality. By following the detailed steps and best practices outlined in this guide, you can leverage Jest to write effective and maintainable tests that enhance the reliability and robustness of your codebase.

Subscribe to Our Newsletter

RELATED ARTICLES

More from the engineering frontline.

Dive deep into our research and insights on design, development, and the impact of various trends to businesses.
The Bug That Doesn't Show Up in Code Review: Why Your Flutter Web App Reloads on Safari
The Bug That Doesn't Show Up in Code Review: Why Your Flutter Web App Reloads on Safari
A real-world look at how oversized images can trigger Safari reloads and iOS crashes in Flutter apps and how smarter image decoding prevents them.
From Prompting to Process: What Changed When Flutter Shipped Agent Skills
From Prompting to Process: What Changed When Flutter Shipped Agent Skills
This blog explores how Flutter Agent Skills improve AI-assisted development by combining official framework workflows with project-specific guidance for more consistent development.
Why Everything Your AI Builds Looks the Same
Why Everything Your AI Builds Looks the Same
This blog explores why AI-generated interfaces often look alike and explains how design systems, product context, and reusable engineering practices help teams build distinctive, scalable
How We Built the Missing Bridge from Code to Figma
Technology

Jul 10, 2026

How We Built the Missing Bridge from Code to Figma
This blog explores how AI-generated React apps get turned into fully editable, designer-ready Figma files by reading React Fiber instead of the DOM.
Building a Resilient Hybrid-Cloud Network with WireGuard HA, Route-Based Failover, and Deep Observability
Technology

Jun 27, 2026

Building a Resilient Hybrid-Cloud Network with WireGuard HA, Route-Based Failover, and Deep Observability
A practical breakdown of building resilient AWS-to-on-premises connectivity with WireGuard HA, active-standby failover, and deep packet-forwarding observability.
We Built a 114-Second AWS-to-Azure Failover. Here’s What We Learned
Technology

Jun 19, 2026

We Built a 114-Second AWS-to-Azure Failover. Here’s What We Learned
A practical guide to building a 114-second multi-cloud disaster recovery failover between AWS and Azure — what we built, what broke, and what we learned.
Cloud-Native and Cloud-Agnostic Are Not Ideologies; They Are Business-Stage Decisions
Technology

Jun 12, 2026

Cloud-Native and Cloud-Agnostic Are Not Ideologies; They Are Business-Stage Decisions
This blog explains how organizations can balance speed, scalability, and operational flexibility as they grow from startup to enterprise scale.

The Right Conversation Can Save You Six Months.

Whether you’re navigating AI adoption, modernizing legacy systems, or scaling a product - we start by listening. No pitch deck. No template. A real conversation.