We use cookies to enhance your experience on the site
CodeWorlds

Matchers in Jest

Matchers are methods that allow you to check values in different ways. In the context of Jurassic Park - they are different types of sensors, each detecting a different kind of threat.

Basic Comparison Matchers

toBe - Strict Comparison (===)

toBe
uses strict comparison. It checks identity - ideal for primitive types.

1test('toBe - comparing primitives', () => {
2  const dinoCount = 15;
3  expect(dinoCount).toBe(15);      // number
4
5  const species = 'T-Rex';
6  expect(species).toBe('T-Rex');    // string
7
8  const isAlive = true;
9  expect(isAlive).toBe(true);       // boolean
10});

toEqual - Structural Comparison

toEqual
checks structural equality of objects. It compares contents, not references.

1test('toEqual - comparing objects', () => {
2  const dino1 = { name: 'Rex', species: 'T-Rex' };
3  const dino2 = { name: 'Rex', species: 'T-Rex' };
4
5  // toBe FAIL - different references (objects in memory)
6  // expect(dino1).toBe(dino2); // This won't work!
7
8  // toEqual PASS - same contents
9  expect(dino1).toEqual(dino2); // This works!
10
11  // Also works with nested objects
12  const enclosure = {
13    name: 'Zone A',
14    dinosaurs: [
15      { name: 'Rex', diet: 'carnivore' }
16    ]
17  };
18
19  expect(enclosure).toEqual({
20    name: 'Zone A',
21    dinosaurs: [
22      { name: 'Rex', diet: 'carnivore' }
23    ]
24  });
25});

Matchers for Arrays and Strings

toContain - Does It Contain an Element?

1test('toContain - checking contents', () => {
2  const dinosaurs = ['T-Rex', 'Velociraptor', 'Triceratops'];
3
4  expect(dinosaurs).toContain('T-Rex');
5  expect(dinosaurs).toContain('Velociraptor');
6
7  // For strings
8  const report = 'Dinosaur T-Rex in zone A';
9  expect(report).toContain('T-Rex');
10  expect(report).toContain('zone A');
11});

toHaveLength - Checking Length

1test('toHaveLength - checking count', () => {
2  const carnivores = ['T-Rex', 'Velociraptor', 'Spinosaurus'];
3  expect(carnivores).toHaveLength(3);
4
5  const emptyEnclosure = [];
6  expect(emptyEnclosure).toHaveLength(0);
7
8  // Also works with strings
9  const code = 'DINO-001';
10  expect(code).toHaveLength(8);
11});

Matchers for Truthy/Falsy Values

toBeTruthy and toBeFalsy

1test('checking truthiness', () => {
2  // Truthy values
3  expect(1).toBeTruthy();
4  expect('text').toBeTruthy();
5  expect([]).toBeTruthy();      // empty array is truthy!
6  expect({}).toBeTruthy();      // empty object is truthy!
7
8  // Falsy values
9  expect(0).toBeFalsy();
10  expect('').toBeFalsy();
11  expect(null).toBeFalsy();
12  expect(undefined).toBeFalsy();
13  expect(false).toBeFalsy();
14});

toBeNull, toBeUndefined, toBeDefined

1test('checking null and undefined', () => {
2  const activeDino = getDinosaur('Rex-001');
3  const extinctDino = getDinosaur('Unknown');
4
5  expect(activeDino).toBeDefined();
6  expect(activeDino).not.toBeNull();
7
8  expect(extinctDino).toBeNull();
9  expect(extinctDino).toBeDefined(); // null is defined!
10
11  let uninitializedDino;
12  expect(uninitializedDino).toBeUndefined();
13});

Numeric Matchers

1test('numeric comparisons', () => {
2  const health = 85;
3
4  expect(health).toBeGreaterThan(80);
5  expect(health).toBeGreaterThanOrEqual(85);
6  expect(health).toBeLessThan(100);
7  expect(health).toBeLessThanOrEqual(85);
8
9  // For floating point numbers - DO NOT use toBe!
10  expect(0.1 + 0.2).toBeCloseTo(0.3);
11});

Testing Exceptions - toThrow

toThrow
checks whether a function throws an exception. NOTE: you must wrap the call in a function!

1function releaseDinosaur(dinosaur, securityLevel) {
2  if (securityLevel < 5) {
3    throw new Error('Security level too low!');
4  }
5  if (dinosaur.species === 'T-Rex' && securityLevel < 9) {
6    throw new Error('T-Rex requires security level 9!');
7  }
8  return { released: true };
9}
10
11test('toThrow - testing exceptions', () => {
12  const rex = { name: 'Rex', species: 'T-Rex' };
13
14  // CORRECT - wrap in an arrow function
15  expect(() => releaseDinosaur(rex, 3)).toThrow();
16  expect(() => releaseDinosaur(rex, 3)).toThrow('Security level too low!');
17  expect(() => releaseDinosaur(rex, 7)).toThrow('T-Rex requires security level 9!');
18
19  // Check that it does NOT throw an exception
20  expect(() => releaseDinosaur(rex, 9)).not.toThrow();
21});

The not Modifier

Every matcher can be negated using

.not
:

1test('the not modifier', () => {
2  const dinosaurs = ['T-Rex', 'Triceratops'];
3
4  expect(dinosaurs).not.toContain('Stegosaurus');
5  expect(dinosaurs.length).not.toBe(0);
6  expect(dinosaurs).not.toEqual([]);
7
8  const health = 85;
9  expect(health).not.toBeLessThan(50);
10});
Go to CodeWorlds