We use cookies to enhance your experience on the site
CodeWorlds

Jest -- The Rocket Engine of Tests

Jest is a testing framework created by Facebook (Meta) that forms the foundation of React application testing. Think of it as the main rocket engine -- without it, no test gets off the ground.

Test Structure -- describe and it/test

We organize tests in

describe
blocks (describing a group of tests) and
it
or
test
(individual tests):

1describe('SpaceShip', () => {
2  it('should have full fuel at start', () => {
3    const ship = createSpaceShip();
4    expect(ship.fuel).toBe(100);
5  });
6
7  it('should consume fuel during travel', () => {
8    const ship = createSpaceShip();
9    ship.travel(50);
10    expect(ship.fuel).toBeLessThan(100);
11  });
12
13  test('should not travel without fuel', () => {
14    const ship = createSpaceShip();
15    ship.fuel = 0;
16    expect(() => ship.travel(10)).toThrow('No fuel');
17  });
18});

it
and
test
are aliases -- they do exactly the same thing. Convention says:
it('should...')
or
test('returns...')
.

Matchers (Assertions) -- Diagnostic Sensors

Matchers are functions that check whether the result is what we expect. Jest offers a rich set:

Value Comparison

1// Exact equality
2expect(2 + 2).toBe(4);
3
4// Object comparison (deep equality)
5expect({ name: 'Apollo' }).toEqual({ name: 'Apollo' });
6
7// Negation
8expect(fuel).not.toBe(0);

Truthiness

1expect(null).toBeNull();
2expect(undefined).toBeUndefined();
3expect('Apollo').toBeDefined();
4expect(true).toBeTruthy();
5expect(0).toBeFalsy();

Numbers

1expect(speed).toBeGreaterThan(0);
2expect(fuel).toBeLessThanOrEqual(100);
3expect(0.1 + 0.2).toBeCloseTo(0.3);

Strings

1expect('Mission Control').toMatch(/mission/i);
2expect('Apollo 13').toContain('Apollo');

Arrays and Objects

1expect(['Earth', 'Mars', 'Jupiter']).toContain('Mars');
2expect(crewMembers).toHaveLength(5);
3expect(spaceship).toHaveProperty('engine');
4expect(spaceship).toHaveProperty('crew.captain', 'Nova');

Exceptions

1expect(() => launchWithoutFuel()).toThrow();
2expect(() => divideByZero()).toThrow('Division by zero');
3expect(() => invalidInput()).toThrow(ValidationError);

Setup and Teardown -- Pre-Launch Preparation

Tests often require environment setup and cleanup:

1describe('MissionControl', () => {
2  let missionControl;
3
4  // Before EACH test
5  beforeEach(() => {
6    missionControl = new MissionControl();
7    missionControl.initialize();
8  });
9
10  // After EACH test
11  afterEach(() => {
12    missionControl.shutdown();
13  });
14
15  // Before ALL tests in the group
16  beforeAll(() => {
17    console.log('Starting mission control tests');
18  });
19
20  // After ALL tests in the group
21  afterAll(() => {
22    console.log('All tests completed');
23  });
24
25  it('should have zero active missions at start', () => {
26    expect(missionControl.activeMissions).toBe(0);
27  });
28});

Asynchronous Testing in Jest

Many operations in space take time -- same in code:

1// Returning a Promise
2test('fetches crew data', () => {
3  return fetchCrewData().then(data => {
4    expect(data).toHaveLength(5);
5  });
6});
7
8// Async/await (preferred)
9test('fetches crew data', async () => {
10  const data = await fetchCrewData();
11  expect(data).toHaveLength(5);
12});
13
14// Testing rejected Promise
15test('throws on invalid mission', async () => {
16  await expect(fetchMission(-1)).rejects.toThrow('Invalid mission ID');
17});

Jest Mock Functions -- Flight Simulators

Mock functions allow you to simulate function behavior without actually calling them:

1// Creating a mock function
2const mockLaunch = jest.fn();
3
4// Calling it
5mockLaunch('Apollo', 'Moon');
6
7// Checking
8expect(mockLaunch).toHaveBeenCalled();
9expect(mockLaunch).toHaveBeenCalledTimes(1);
10expect(mockLaunch).toHaveBeenCalledWith('Apollo', 'Moon');
11
12// Mock with return value
13const mockFuel = jest.fn().mockReturnValue(100);
14expect(mockFuel()).toBe(100);
15
16// Mock with implementation
17const mockCalculateRoute = jest.fn((from, to) => {
18  return { distance: 1000, estimatedTime: '2h' };
19});

Running Tests

Jest offers several useful commands for running tests:

1# Run all tests
2npm test
3
4# Run tests in watch mode (automatically after changes)
5npm test -- --watch
6
7# Run tests from a specific file
8npm test -- SpaceShip.test.js
9
10# Run tests matching a pattern
11npm test -- --testPathPattern="mission"
12
13# Run with code coverage report
14npm test -- --coverage

Best Practices for Testing with Jest

  1. One test = one assertion -- each test should check one specific thing
  2. Descriptive names --
    it('should calculate fuel consumption for 100km trip')
    instead of
    it('test fuel')
  3. Arrange-Act-Assert -- prepare data, perform action, check result
  4. Isolation -- tests should not depend on each other or on execution order

Jest is a powerful rocket engine for tests -- mastering it will give you confidence that your application works correctly in all cosmic conditions!

Go to CodeWorlds