Blog>
Snippets

Implementing Unit Testing with Jest

Write a unit test using Jest for a JavaScript function, emphasizing the significance of testing in professional frontend development.
// calculator.js
export function add(a, b) {
    return a + b;
}

export function subtract(a, b) {
    return a - b;
}
This is a simple calculator module that exports an add function and a subtract function.
// calculator.test.js
import { add, subtract } from './calculator';

test('adds 1 + 2 to equal 3', () => {
    expect(add(1, 2)).toBe(3);
});

test('subtracts 5 - 2 to equal 3', () => {
    expect(subtract(5, 2)).toBe(3);
});
This is a test suite for the calculator module. It includes two tests: one for the add function and one for the subtract function. The tests use Jest's `expect` and `toBe` to assert that the functions work as expected.
// jest.config.js
module.exports = {
    // The test environment that will be used for testing
    testEnvironment: 'node',
    // The glob patterns Jest uses to detect test files
    testMatch: ['**/__tests__/**/*.js?(x)', '**/?(*.)+(spec|test).js?(x)'],
    // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
    testPathIgnorePatterns: ['/node_modules/'],
    // Indicates whether the coverage information should be collected while executing the test
    collectCoverage: true,
    // The directory where Jest should output its coverage files
    coverageDirectory: 'coverage',
};
This is the Jest configuration file which defines various options like the test environment, test match patterns, paths to ignore during testing, and coverage settings.