JavaScript and TypeScript course ยท Module 11: Testing with Jest

Jest Framework - Basics

7 min read ยท
In this lesson5

In the previous lesson, a test appeared like a ready-made sensor. But who runs it, collects the results and raises the alarm when something goes wrong? You need a control center that finds the test files by itself, runs them and reports what passed and what did not.

Jest is one of the most popular tools for testing JavaScript and TypeScript. It was created at Facebook (now Meta), and since 2022 it has been developed under the OpenJS Foundation. In our Jurassic Park, Jest will be the main tool for verifying security systems - in this module we rely on version 30.

Installation and Configuration

You install Jest as a development dependency: it goes into the devDependencies section of package.json, because you need it while working on the code, not in production. Here are the commands every project starts with:

# Installing Jest
npm install --save-dev jest

# For TypeScript
npm install --save-dev jest ts-jest @types/jest

# Initializing configuration
npm init jest@latest

The first command is enough for testing JavaScript, and the second adds the packages for TypeScript - we will come back to them in the lesson on testing TS. The last one starts a wizard that asks a few questions and writes a configuration file. Older versions used the npx jest --init command for this, but Jest 30 removed it. It is also worth adding a "test": "jest" script to package.json - then you can run the whole test battery with npm test.

Test Structure

Every test in Jest consists of three key elements: describe, it (or test), and expect. You do not need to import them, because Jest provides them as global functions in every test file. It finds the files without your help, too: by default it runs everything ending in .test.js or .spec.js (TypeScript variants included), plus files inside a __tests__ folder.

describe - Grouping Tests

describe is a block that groups related tests. Think of it as an enclosure in the park - it groups dinosaurs of the same species. The first argument is the group's name, and the second is a function where you place the tests:

describe('DinosaurEnclosure', () => {
  // All tests related to the dinosaur enclosure
});

describe itself checks nothing. It organizes the report: in the results you will see the name DinosaurEnclosure with all the tests from that enclosure underneath. Blocks can be nested, as you will see shortly in the full example.

it / test - Individual Test Case

it and test are interchangeable - both define a single test. The Jest documentation describes it explicitly as an alias of test: it is the same function under two names. Convention: it reads like a sentence in English. You can even mix both forms within one describe:

describe('DinosaurEnclosure', () => {
  it('should have a fence', () => {
    // assertion
  });

  test('fence is electrified', () => {
    // assertion
  });
});

Both tests work identically. The first one reads like the sentence "it should have a fence". I recommend it inside describe and test for standalone tests, but consistency across the whole project matters most.

expect - Assertions

expect is the heart of every test. It compares the actual result with the expected one. The syntax always has two parts: expect(value) wraps the result, and a matcher such as toBe or toEqual states what you expect. createEnclosure is a factory that returns an enclosure object with a name, a capacity and an empty list of dinosaurs:

describe('DinosaurEnclosure', () => {
  it('should have correct capacity', () => {
    const enclosure = createEnclosure('T-Rex Zone', 5);
    expect(enclosure.capacity).toBe(5);
  });

  it('should start empty', () => {
    const enclosure = createEnclosure('Raptor Pen', 10);
    expect(enclosure.dinosaurs).toEqual([]);
    expect(enclosure.dinosaurs.length).toBe(0);
  });
});

When an assertion fails, Jest stops only that one test, shows the expected value (Expected) and the received one (Received), and then moves on to the next test. I will explain in the lesson on matchers why we used toEqual rather than toBe for the empty array.

Complete Example

Let's see a full example of testing a dinosaur management module. First, the production code: createDinosaur creates a specimen at full health, and feedDinosaur raises its health only when the food matches the diet, and never above 100:

// dinosaur.js - production code
function createDinosaur(name, species, diet) {
  return {
    name,
    species,
    diet,
    health: 100,
    isAlive: true,
  };
}

function feedDinosaur(dinosaur, food) {
  if (dinosaur.diet === 'carnivore' && food === 'meat') {
    dinosaur.health = Math.min(100, dinosaur.health + 20);
    return { success: true, message: 'Dinosaur fed!' };
  }
  if (dinosaur.diet === 'herbivore' && food === 'plants') {
    dinosaur.health = Math.min(100, dinosaur.health + 15);
    return { success: true, message: 'Dinosaur fed!' };
  }
  return { success: false, message: 'Wrong food!' };
}

Now the test file. Two nested describe blocks correspond to the two functions, and each it checks one scenario:

// dinosaur.test.js - tests
describe('Dinosaur Management', () => {
  describe('createDinosaur', () => {
    it('should create a dinosaur with correct properties', () => {
      const rex = createDinosaur('Rex', 'T-Rex', 'carnivore');

      expect(rex.name).toBe('Rex');
      expect(rex.species).toBe('T-Rex');
      expect(rex.diet).toBe('carnivore');
      expect(rex.health).toBe(100);
      expect(rex.isAlive).toBe(true);
    });
  });

  describe('feedDinosaur', () => {
    it('should feed carnivore with meat', () => {
      const rex = createDinosaur('Rex', 'T-Rex', 'carnivore');
      rex.health = 70;

      const result = feedDinosaur(rex, 'meat');

      expect(result.success).toBe(true);
      expect(rex.health).toBe(90);
    });

    it('should reject wrong food for carnivore', () => {
      const rex = createDinosaur('Rex', 'T-Rex', 'carnivore');

      const result = feedDinosaur(rex, 'plants');

      expect(result.success).toBe(false);
    });
  });
});

In a real project, the test file imports the functions, for example with require('./dinosaur'), and dinosaur.js has to export them. Also notice a gap: the rejected-food test does not check whether Rex's health stayed untouched. That is a good candidate for your first test of your own.

Running Tests

You run tests from the terminal. Here are the four variants you will use most often:

# Run all tests
npx jest

# Run a specific file
npx jest dinosaur.test.js

# Run in watch mode (reacts to changes)
npx jest --watch

# Run with code coverage reporting
npx jest --coverage

In --watch mode, every save reruns only the tests related to the changed files (it detects changes through Git), while --coverage produces a coverage report showing which lines of code at least one test executed and which ones no test ever visited.

AAA Pattern (Arrange-Act-Assert)

Every good test should be written according to the AAA pattern: Arrange (prepare), Act (execute), Assert (verify). Three parts separated by a blank line make the test read like an inspection report:

it('should increase health when fed correctly', () => {
  // Arrange - create the needed objects
  const dino = createDinosaur('Brachio', 'Brachiosaurus', 'herbivore');
  dino.health = 60;

  // Act - execute the tested operation
  const result = feedDinosaur(dino, 'plants');

  // Assert - verify the result
  expect(result.success).toBe(true);
  expect(dino.health).toBe(75);
});

The production code has not changed - only the order of the test has, and thanks to it you can instantly see what is preparation and what is the actual check. My advice: one action in the Act section. If you call three different functions there, you are probably writing three tests at once.

In the next lesson you will get to know the full arsenal of matchers. The lab below runs a simplified simulation of describe, it and expect written in plain JavaScript, because Sandpack does not run the real Jest.

Remember: describe is the enclosure, it is a single inspection, and expect is the sensor that reports PASS or FAIL.

Code for this lesson: index.js
// Jest - Testing framework basics
console.log("=== Jurassic Park - Jest Testing System ===\n");

// Simulation of the Jest framework (Sandpack does not run the real Jest)
// Shows the structure: describe, it/test, expect

// --- Mini Jest implementation ---
const results = { passed: 0, failed: 0, suites: [] };

function describe(name, fn) {
  const suite = { name, tests: [] };
  results.suites.push(suite);
  const prevSuite = results.currentSuite;
  results.currentSuite = suite;
  fn();
  results.currentSuite = prevSuite;
}

function it(name, fn) {
  try {
    fn();
    results.currentSuite.tests.push({ name, status: "PASS" });
    results.passed++;
  } catch (e) {
    results.currentSuite.tests.push({ name, status: "FAIL", error: e.message });
    results.failed++;
  }
}
const test = it; // test and it are interchangeable

function expect(actual) {
  return {
    toBe(expected) {
      if (actual !== expected)
        throw new Error(`Expected ${expected}, got ${actual}`);
    },
    toEqual(expected) {
      if (JSON.stringify(actual) !== JSON.stringify(expected))
        throw new Error(`Expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`);
    },
    toHaveLength(expected) {
      if (actual.length !== expected)
        throw new Error(`Expected length ${expected}, got ${actual.length}`);
    },
    toBeTruthy() {
      if (!actual) throw new Error(`Expected truthy, got ${actual}`);
    },
    not: {
      toBe(expected) {
        if (actual === expected) throw new Error(`Expected not ${expected}`);
      }
    }
  };
}

// --- Production code ---
function createDinosaur(name, species, diet) {
  return { name, species, diet, health: 100, isAlive: true };
}

function feedDinosaur(dinosaur, food) {
  if (dinosaur.diet === "carnivore" && food === "meat") {
    dinosaur.health = Math.min(100, dinosaur.health + 20);
    return { success: true, message: "Dinosaur fed!" };
  }
  if (dinosaur.diet === "herbivore" && food === "plants") {
    dinosaur.health = Math.min(100, dinosaur.health + 15);
    return { success: true, message: "Dinosaur fed!" };
  }
  return { success: false, message: "Wrong food!" };
}

// --- Tests ---
describe("Dinosaur Management", () => {
  describe("createDinosaur", () => {
    it("should create a dinosaur with correct properties", () => {
      const rex = createDinosaur("Rex", "T-Rex", "carnivore");
      expect(rex.name).toBe("Rex");
      expect(rex.species).toBe("T-Rex");
      expect(rex.diet).toBe("carnivore");
      expect(rex.health).toBe(100);
      expect(rex.isAlive).toBe(true);
    });

    it("should create herbivore dinosaur", () => {
      const brachio = createDinosaur("Brachio", "Brachiosaurus", "herbivore");
      expect(brachio.diet).toBe("herbivore");
      expect(brachio.health).toBe(100);
    });
  });

  describe("feedDinosaur", () => {
    it("should feed carnivore with meat (AAA pattern)", () => {
      // Arrange
      const rex = createDinosaur("Rex", "T-Rex", "carnivore");
      rex.health = 70;

      // Act
      const result = feedDinosaur(rex, "meat");

      // Assert
      expect(result.success).toBe(true);
      expect(rex.health).toBe(90);
    });

    it("should reject wrong food for carnivore", () => {
      const rex = createDinosaur("Rex", "T-Rex", "carnivore");
      const result = feedDinosaur(rex, "plants");
      expect(result.success).toBe(false);
    });

    it("should feed herbivore with plants", () => {
      const brachio = createDinosaur("Brachio", "Brachiosaurus", "herbivore");
      brachio.health = 50;
      const result = feedDinosaur(brachio, "plants");
      expect(result.success).toBe(true);
      expect(brachio.health).toBe(65);
    });
  });
});

// --- Show results ---
console.log("Test Results:\n");
results.suites.forEach(suite => {
  console.log(`  ${suite.name}`);
  suite.tests.forEach(t => {
    const icon = t.status === "PASS" ? "PASS" : "FAIL";
    console.log(`    [${icon}] ${t.name}`);
    if (t.error) console.log(`           ${t.error}`);
  });
});
console.log(`\nTotal: ${results.passed} passed, ${results.failed} failed`);

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What does the AAA pattern used in unit testing stand for?

  2. 2. What is the purpose of the expect() function in Jest?

Hands-on tasks in the game

  • Code editor

    Complete the missing assertions in tests for the getDinosaurSpecies function.

  • Click in order

    Arrange the elements of a basic Jest test:

  • Code editor

    Write tests for a dinosaur health points system using describe, it, expect.

  1. QuestionAAA Pattern in Tests
  2. Coding taskFirst Test in Jest
  3. QuestionThe expect Function in Jest
  4. Click in orderTest Block Syntax
  5. Coding taskStructure of describe/it/expect

Useful articles