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.

Mobile App DevelopmentTestingTechnologyApp Development

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.
Why Legacy Systems Block Real-Time AI Decision-Making
Business

Aug 4, 2026

Why Legacy Systems Block Real-Time AI Decision-Making
Learn how legacy systems limit real-time AI decision-making and what businesses can do to build an AI-ready infrastructure.
What Makes an AI Product Enterprise-Ready? A Business Leader’s Perspective
Business

Aug 4, 2026

What Makes an AI Product Enterprise-Ready? A Business Leader’s Perspective
Most AI pilots never make it to production. Here are the five questions business leaders should ask before approving, buying, or scaling an AI product.
Building AI-Powered Banking CRM Platforms Without Replacing Core Banking Systems
Business

Jul 31, 2026

Building AI-Powered Banking CRM Platforms Without Replacing Core Banking Systems
Banks can modernize CRM with AI without replacing their core banking systems. This guide covers the architecture, use cases, governance, and roadmap to do it.
AI in Fintech: Everyone's Talking, Few are Shipping
Business

Jul 30, 2026

AI in Fintech: Everyone's Talking, Few are Shipping
This blog covers the key engineering, governance, and compliance principles required to build production-ready AI systems for financial services.
ERP and MES Integration for U.S. Pharma Manufacturers: A Roadmap to Achieve Zero-Error Production and End-to-End Traceability
Business

Jul 27, 2026

ERP and MES Integration for U.S. Pharma Manufacturers: A Roadmap to Achieve Zero-Error Production and End-to-End Traceability
A strategic roadmap for U.S. pharma leaders integrating ERP and MES to reduce production errors, accelerate batch release, strengthen compliance readiness, and enable end-to-end traceability across manufacturing sites.
How to Build Medical Device Software with AI: Compliance, Architecture, and Development Process
Business

Jul 24, 2026

How to Build Medical Device Software with AI: Compliance, Architecture, and Development Process
A guide for engineering leaders on building compliant, production-ready AI medical device software, from architecture to FDA clearance.

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.