Unit Test - Durjoy01/Cholo_jai GitHub Wiki

Jset framewrok: https://jestjs.io/docs/testing-frameworks

Overview:

Jest is a powerful and flexible JavaScript testing framework developed by Facebook. It is widely used in modern web development for testing JavaScript and TypeScript applications, especially those built with React. Jest simplifies the testing process by providing an all-in-one solution for running tests, mocking dependencies, and generating reports.

Features of Jest:

Key Features:

Ease of Use: Works out of the box with minimal configuration.

Fast Performance:

Executes tests in parallel to improve speed.

Built-in Mocking:

Includes tools to mock functions, modules, and timers.

Snapshots:

Captures and compares snapshots of UI or data structures to test for unexpected changes.

Code Coverage:

Tracks how much of your code is exercised during tests.

Watch Mode:

Automatically reruns tests when code changes are detected.

Wide Ecosystem Support:

Works seamlessly with React, Angular, Node.js, and more.

Benefits of Jest:

No Extra Tools Required:

Contains mocking tools, assertion libraries, and test runners all in one package.

Community and Support:

Supported by a sizable developer community and Facebook.

Combining with CI/CD:

interacts with well-known continuous integration platforms like Travis CI, Jenkins, and GitHub Actions with ease.

Basic example of Jest:

UserService module with a function to calculate a user’s age based on their date of birth. // userService.js function calculateAge(dob) { if (!dob || !(dob instanceof Date)) { throw new Error('Invalid date of birth'); } const today = new Date(); let age = today.getFullYear() - dob.getFullYear(); const monthDiff = today.getMonth() - dob.getMonth(); if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < dob.getDate())) { age--; } return age; }

module.exports = calculateAge; Unit test using Jest: // userService.test.js const calculateAge = require('./userService');

describe('calculateAge', () => { test('calculates age correctly for a past date', () => { const dob = new Date(2000, 0, 1); // Jan 1, 2000 expect(calculateAge(dob)).toBe(new Date().getFullYear() - 2000); });

test('handles a birthday today correctly', () => {
    const today = new Date();
    const dob = new Date(today.getFullYear(), today.getMonth(), today.getDate());
    expect(calculateAge(dob)).toBe(0);
});

test('throws an error for invalid input', () => {
    expect(() => calculateAge(null)).toThrow('Invalid date of birth');
    expect(() => calculateAge('2000-01-01')).toThrow('Invalid date of birth');
    expect(() => calculateAge(12345)).toThrow('Invalid date of birth');
});

test('handles leap year birthdays', () => {
    const dob = new Date(2004, 1, 29); // Feb 29, 2004
    const today = new Date(2023, 1, 28); // Feb 28, 2023 (non-leap year)
    expect(calculateAge(dob)).toBe(19);
});

});

Running the test with Jest:

Installation method:

npm install --save-dev jest

Run the test:

npx jest

Output:

PASS ./userService.test.js calculateAge ✓ calculates age correctly for a past date (2 ms) ✓ handles a birthday today correctly ✓ throws an error for invalid input ✓ handles leap year birthdays

Test Suites: 1 passed, 1 total Tests: 4 passed, 4 total

Explanation:

describe Block: Groups all tests for the calculateAge function.

Valid Tests: Checks behavior with valid inputs (e.g., a past date, today’s date, leap year handling).

Error Tests: Verifies the function throws errors for invalid inputs using toThrow.

Edge Cases: Handles specific edge cases, like birthdays on leap years.