Performing Functional Testing Using Jest For QA

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.

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

More from the engineering frontline.

Dive deep into our research and insights on design, development, and the impact of various trends to businesses.
Insight
Why Legacy Systems Make Business Growth More Expensive: Navigate A Smarter Path to Legacy Modernization
Sep 23, 2026

Why Legacy Systems Make Business Growth More Expensive: Navigate A Smarter Path to Legacy Modernization

Learn how legacy systems make business growth more expensive and how edge-first modernization can remove constraints without replacing the existing system.

Insight
SSO, Audit Logs and RBAC: The Enterprise Features AI Prototyping Tools Do Not Cover | Sarika Gautam
Sep 23, 2026

SSO, Audit Logs and RBAC: The Enterprise Features AI Prototyping Tools Do Not Cover | Sarika Gautam

Why AI-generated prototypes fail enterprise review: the context behind SSO, the cost of skipping audit logs, and how role explosion makes RBAC a product of its own.

Insight
Feature Flags as Technical Debt: The Cleanup Nobody Schedules
Sep 21, 2026

Feature Flags as Technical Debt: The Cleanup Nobody Schedules

This blog explains how unmanaged feature flags create technical debt and how teams can detect, manage, and remove them safely.

Insight
Building AI-First Enterprises: Why System Design Matters More Than AI Adoption
Sep 21, 2026

Building AI-First Enterprises: Why System Design Matters More Than AI Adoption

This blog explores how system design, architecture, and validation shape AI-first enterprises, while examining AI’s impact on software engineering and human decision-making.

Insight
The Product Studio in the AI Era: What Actually Changes | Sarika Gautam
Sep 21, 2026

The Product Studio in the AI Era: What Actually Changes | Sarika Gautam

What changes in product development when AI writes the code: the shift to architecture, the token cost of unplanned builds, and why juniors still matter.

Insight
AI and the Future of Digital Customer Experience: Where Technology Meets Human Creativity
Sep 18, 2026

AI and the Future of Digital Customer Experience: Where Technology Meets Human Creativity

A discussion on how AI, human creativity, research, and cross-functional collaboration are shaping the future of digital customer experience.

Insight
Scaling Down Before Scaling Up: Why Bigger Servers Don’t Fix Bad Architecture
Sep 17, 2026

Scaling Down Before Scaling Up: Why Bigger Servers Don’t Fix Bad Architecture

This blog explores how inefficient backend architecture can cause performance issues even under low traffic, covering practical ways to reduce database load, API latency, and resource usage before scaling infrastructure.

Footer

The Right Conversation Can

Save You Six Months.

Book a Call