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
From Test Failure to Root Cause: Building an AI-Assisted Playwright Failure Analysis Pipeline
Oct 9, 2026

From Test Failure to Root Cause: Building an AI-Assisted Playwright Failure Analysis Pipeline

This blog explains how an AI-assisted Playwright pipeline can analyze test failure evidence, identify probable root causes, and support human-validated debugging.

Insight
The Model Context Protocol: From First Call to Production
Oct 8, 2026

The Model Context Protocol: From First Call to Production

This blog explains how Model Context Protocol (MCP) works, from tool discovery and execution to OAuth authorization, security controls, and production deployment.

Insight
Stop Automating Everything: A Balanced Quality Engineering Approach to Testing
Oct 8, 2026

Stop Automating Everything: A Balanced Quality Engineering Approach to Testing

Balanced quality engineering places automation, API testing, exploratory work, and AI where each gives the most value, so teams ship faster without trading away user-perceived quality.

Insight
From Rolling Deployments to Zero-Downtime Releases
Oct 6, 2026

From Rolling Deployments to Zero-Downtime Releases

This blog explains how Blue-Green deployment helps reduce downtime in online banking releases through traffic switching, pod readiness, static-resource versioning, and rapid rollback.

Insight
The Deprecation Notice Nobody Reads
Oct 5, 2026

The Deprecation Notice Nobody Reads

This blog explains why API deprecation notices often fail and how staged retirement, telemetry, brownouts, and scheduled enforcement can make API migrations more controlled and predictable.

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.

Footer

The Right Conversation Can

Save You Six Months.

Book a Call