Unit Testing Tool‐JEST - JUCSE49-Mavericks/Smart-Class-Routine-Management-System GitHub Wiki


🎯 Jest Unit Testing Tool Documentation

Jest License

check

📋 Overview

Jest is an open-source testing framework maintained by Facebook, primarily designed for testing JavaScript applications. It is widely used for unit, integration, and snapshot testing in Node.js, React, and other JavaScript projects. Jest requires zero configuration and supports small to large applications seamlessly.


📑 Table of Contents

  1. Key Features
  2. Installation and Setup
  3. Writing Tests with Jest
  4. Running Tests
  5. Jest Assertions
  6. Mocking in Jest
  7. Code Coverage
  8. Best Practices
  9. References

🚀 Key Features

Feature Description
Zero Configuration Works out of the box without extra setup.
Mocking & Spies Mock functions and modules for better isolation.
Snapshot Testing Track UI changes with snapshots.
Asynchronous Testing Supports promises, callbacks, and async/await.
Code Coverage Reporting Built-in reports for test coverage.
Parallel Test Execution Runs tests in parallel to boost performance.
TypeScript Support Works with ES6+ and TypeScript.

⚙️ Installation and Setup

Prerequisites

  • Node.js: Ensure Node.js and npm are installed.
  • JavaScript Project: Jest works with new or existing projects.

Installing Jest

# Using npm
npm install --save-dev jest

# Using yarn
yarn add --dev jest

Add Jest to package.json

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

For advanced setups, use jest.config.js:

module.exports = {
  verbose: true,
  testEnvironment: "node",
};

✍️ Writing Tests with Jest

A typical Jest test file has .test.js or .spec.js extension.

// 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);
});
  • test(): Defines a test case.
  • expect(): Asserts the expected outcome.
  • .toBe(): Strict equality matcher.

🏃‍♂️ Running Tests

Run tests using:

npm test

Alternatively, run with Jest CLI:

npx jest

Common Options

  • --watch: Run tests in watch mode.
  • --coverage: Generate code coverage reports.
  • --verbose: Display detailed test results.

Jest Assertions

Matcher Description
.toBe() Strict equality comparison.
.toEqual() Deep equality for objects or arrays.
.toBeNull() Checks if a value is null.
.toBeDefined() Verifies if a value is defined.
.toHaveLength() Checks length of arrays or strings.

Example

test('object assignment', () => {
  const data = { one: 1 };
  data['two'] = 2;
  expect(data).toEqual({ one: 1, two: 2 });
});

🎭 Mocking in Jest

Mocking helps isolate tests by replacing dependencies with mock functions.

Mocking a Function

const myMock = jest.fn().mockReturnValueOnce(10).mockReturnValueOnce(20);

console.log(myMock()); // 10
console.log(myMock()); // 20

Mocking a Module

jest.mock('./myModule');
const myModule = require('./myModule');

test('mocked function call', () => {
  myModule.someFunction.mockReturnValue('mocked value');
  expect(myModule.someFunction()).toBe('mocked value');
});

📊 Code Coverage

Generate code coverage reports with:

npx jest --coverage

This will create a coverage folder containing metrics like:

  • Statements Covered
  • Branches Tested
  • Functions Covered
  • Lines Covered

🏆 Best Practices

  1. Isolate Tests: Ensure tests run independently.
  2. Use Mocking Carefully: Mock external dependencies only when necessary.
  3. Write Descriptive Test Names: Test names should reflect the purpose clearly.
  4. Group Tests: Use describe() to group related tests.
  5. Run Tests Frequently: Use watch mode to catch bugs early.

📊 Jest vs Mocha vs Jasmine: A Comparative Guide

Overview

This table provides a detailed comparison of Jest, Mocha, and Jasmine across key criteria to help developers understand when Jest is the optimal choice.


Comparison Table: Jest vs Mocha vs Jasmine

Criteria Jest Mocha Jasmine
Configuration Zero-config, works out-of-the-box. Requires setup and configuration. Minimal setup, but requires some tweaking.
Performance Runs tests in parallel by default. Single-threaded; slower without tuning. No built-in parallel support.
Built-in Features Comes with spies, mocks, and assertions. Requires additional libraries (e.g., Chai, Sinon). No built-in mocks, spies must be manually created.
Community & Ecosystem Highly popular in React/Node.js projects. Strong community but requires more dependencies. Smaller community but stable.
Asynchronous Code Testing Native support for async/await. Requires more boilerplate for async code. Async support available, but with quirks.
Snapshot Testing Built-in support for snapshot testing. No built-in snapshot support. No snapshot support.
Code Coverage Code coverage built-in. Requires nyc or istanbul integration. No built-in coverage; external tools needed.
Ease of Use Simplifies testing with integrated tools. Requires separate libraries for assertions, spies, and mocks. Basic API, but can feel less modern.
Use Case Suitability Ideal for React, Node.js, and TypeScript projects. Best for highly customized testing setups. Good for legacy systems or simple unit tests.
Learning Curve Easier for beginners with simple APIs. Requires learning multiple tools (e.g., Mocha + Chai + Sinon). Moderate; fewer dependencies but limited features.

Summary

Jest excels in projects where simplicity and built-in features are essential. It’s especially powerful for React and Node.js applications, thanks to zero-config support and snapshot testing. While Mocha and Jasmine have their strengths, Jest offers an all-in-one testing solution that reduces the need for extra tools or libraries.


🔗 References


⚠️ **GitHub.com Fallback** ⚠️