Jest

Language: JavaScript

Testing

Jest was created by Facebook to test React applications, but it has grown to support any JavaScript project. Its zero-configuration setup, powerful mocking capabilities, and snapshot testing features make it widely popular for testing modern web applications.

Jest is a delightful JavaScript testing framework with a focus on simplicity, correctness, and developer experience. It supports unit, integration, and snapshot testing for JavaScript and TypeScript projects.

Installation

npm: npm install --save-dev jest
yarn: yarn add --dev jest

Usage

Jest allows developers to write tests using simple syntax and run them in a fast and isolated environment. It supports features like mocks, spies, snapshot testing, code coverage, and parallel test execution.

Basic test example

function sum(a, b) {
  return a + b;
}

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

Defines a simple unit test that verifies the sum function returns the correct result.

Using beforeEach

let counter = 0;
beforeEach(() => {
  counter = 0;
});
test('counter starts at 0', () => {
  expect(counter).toBe(0);
});

Resets the counter before each test using `beforeEach`.

Mocking functions

const myFunc = jest.fn();
myFunc('hello');
expect(myFunc).toHaveBeenCalledWith('hello');

Demonstrates using Jest's `fn()` to create a mock function and assert it was called with specific arguments.

Snapshot testing

const user = { name: 'Alice', age: 25 };
test('user snapshot', () => {
  expect(user).toMatchSnapshot();
});

Uses snapshot testing to verify that the object structure does not change unexpectedly.

Testing asynchronous code

function fetchData() {
  return Promise.resolve('peanut butter');
}
test('the data is peanut butter', async () => {
  const data = await fetchData();
  expect(data).toBe('peanut butter');
});

Tests an asynchronous function using `async/await` syntax.

Mocking modules

jest.mock('./api');
import { fetchData } from './api';
fetchData.mockResolvedValue('mocked data');

Shows how to mock entire modules to control dependencies in tests.

Error Handling

Test failed due to unexpected value: Check the expected value, and ensure the function under test produces consistent outputs.
Cannot find module: Verify module paths and use `jest.mock()` appropriately when mocking dependencies.
Timeout - Async callback was not invoked: Ensure asynchronous tests call `done()` or return a promise, and adjust timeout if necessary.

Best Practices

Write small, focused tests for individual units of code.

Use mocks and spies to isolate the code under test.

Leverage snapshot testing for UI components and serializable objects.

Run tests in watch mode during development for faster feedback.

Organize test files alongside source files or in a __tests__ directory for clarity.