Welcome to the Jest Testing Tutorial! Jest is a delightful JavaScript Testing Framework with a focus on simplicity. This guide will help you get started with Jest and writing tests for your JavaScript projects.

Table of Contents


Why Test?

Testing is an essential part of software development. It helps you ensure that your code works as expected and catches bugs early. By writing tests, you can have confidence in your codebase and make changes with peace of mind.

👉 Learn more about the importance of testing


Setting Up Jest

To get started with Jest, you'll need to install it in your project. Follow these steps:

  1. Create a new project or navigate to your existing project directory.
  2. Run npm install --save-dev jest.
  3. Add a test script to your package.json file:
    "scripts": {
      "test": "jest"
    }
    

Writing Tests

Once Jest is set up, you can start writing tests for your code. Here's an example of a simple test for a function:

// myFunction.js
function add(a, b) {
  return a + b;
}

// myFunction.test.js
const { add } = require('./myFunction');

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

To run the test, execute npm test in your terminal.


Test Suite Structure

A Jest test suite consists of one or more test cases. Test cases are defined using the test function. Here's an example of a test suite with multiple test cases:

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

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

Common Jest Features

Jest provides a variety of features to make testing easier. Some of the common features include:

  • Mocking functions and modules
  • Mocking timers
  • Snapshots for testing UI components
  • Parallel test execution
  • Test coverage reports

👉 Explore more Jest features


Resources


[center] Testing [center]