Wat zijn Matchers?

Matchers zijn functies waarmee je verwachtingen kunt checken. Je gebruikt ze altijd samen met expect().

De basis structuur:

expect(waarde).matcher(verwachting);

Voorbeelden:

expect(2 + 2).toBe(4);
expect(naam).toContain("Jan");
expect(button).toBeInTheDocument();

In deze les leer je de meest gebruikte matchers die je in 90% van je tests nodig hebt.

Gelijkheid Matchers

toBe() - Exacte gelijkheid

Gebruik toBe() voor simpele waarden zoals getallen, strings en booleans.

test('toBe voorbeelden', () => {
  expect(2 + 2).toBe(4);
  expect('hello').toBe('hello');
  expect(true).toBe(true);
  expect(null).toBe(null);
});

Let op: toBe() checkt of het EXACT hetzelfde object is. Gebruik het NIET voor arrays en objecten!

toEqual() - Diepe gelijkheid

Gebruik toEqual() voor arrays en objecten. Het checkt de inhoud, niet het geheugenadres.

test('toEqual voorbeelden', () => {
  // Objecten
  const user = { name: 'Jan', age: 17 };
  expect(user).toEqual({ name: 'Jan', age: 17 });
  
  // Arrays
  const getallen = [1, 2, 3];
  expect(getallen).toEqual([1, 2, 3]);
});

toBe() vs toEqual() - Wanneer wat gebruiken?

  • toBe() - Voor: getallen, strings, booleans, null, undefined
  • toEqual() - Voor: objecten, arrays

Getal Matchers

test('getal matchers', () => {
  const leeftijd = 17;
  
  // Groter dan
  expect(leeftijd).toBeGreaterThan(16);
  
  // Groter of gelijk aan
  expect(leeftijd).toBeGreaterThanOrEqual(17);
  
  // Kleiner dan
  expect(leeftijd).toBeLessThan(18);
  
  // Kleiner of gelijk aan
  expect(leeftijd).toBeLessThanOrEqual(17);
});

Praktisch voorbeeld

// Functie om kortingsprijs te berekenen
function berekenKorting(prijs, percentage) {
  return prijs - (prijs * percentage / 100);
}

test('korting is minder dan originele prijs', () => {
  const origineel = 100;
  const metKorting = berekenKorting(100, 20);
  
  expect(metKorting).toBeLessThan(origineel);
  expect(metKorting).toBe(80);
});

String Matchers

toContain() - Bevat een stukje tekst

test('string bevat tekst', () => {
  const bericht = 'Welkom op onze website!';
  
  expect(bericht).toContain('Welkom');
  expect(bericht).toContain('website');
  expect(bericht).toContain('onze');
});

toMatch() - Regex matching

test('string matcht patroon', () => {
  const email = 'jan@example.com';
  
  // Check of het een @ bevat
  expect(email).toMatch(/@/);
  
  // Check of het eindigt op .com
  expect(email).toMatch(/\.com$/);
});

Praktisch voorbeeld - Email validatie

function isGeldigeEmail(email) {
  return email.includes('@') && email.includes('.');
}

test('valideert email correct', () => {
  expect(isGeldigeEmail('jan@test.com')).toBe(true);
  expect(isGeldigeEmail('jantest.com')).toBe(false);
  expect(isGeldigeEmail('jan@test')).toBe(false);
});

Array Matchers

toContain() - Array bevat een item

test('array bevat item', () => {
  const fruit = ['appel', 'peer', 'banaan'];
  
  expect(fruit).toContain('appel');
  expect(fruit).toContain('banaan');
});

toHaveLength() - Array lengte

test('array lengte', () => {
  const getallen = [1, 2, 3, 4, 5];
  
  expect(getallen).toHaveLength(5);
  
  // Ook werkt voor strings!
  expect('hello').toHaveLength(5);
});

Praktisch voorbeeld - Todo lijst

function voegTodoToe(lijst, item) {
  return [...lijst, item];
}

test('voegt todo toe aan lijst', () => {
  const todos = ['boodschappen', 'huiswerk'];
  const nieuweLijst = voegTodoToe(todos, 'sporten');
  
  expect(nieuweLijst).toHaveLength(3);
  expect(nieuweLijst).toContain('sporten');
  expect(nieuweLijst).toEqual(['boodschappen', 'huiswerk', 'sporten']);
});

DOM Matchers (voor React)

Deze matchers komen van @testing-library/jest-dom en zijn speciaal voor HTML/React.

toBeInTheDocument() - Element bestaat

import { render, screen } from '@testing-library/react';

test('button is zichtbaar', () => {
  render(<button>Klik</button>);
  
  const button = screen.getByText('Klik');
  expect(button).toBeInTheDocument();
});

toHaveClass() - Element heeft CSS class

test('button heeft active class', () => {
  render(<button className="btn active">Klik</button>);
  
  const button = screen.getByText('Klik');
  expect(button).toHaveClass('active');
  expect(button).toHaveClass('btn');
});

toBeDisabled() - Element is disabled

test('button is disabled', () => {
  render(<button disabled>Klik</button>);
  
  const button = screen.getByText('Klik');
  expect(button).toBeDisabled();
});

toHaveValue() - Input heeft waarde

test('input heeft waarde', () => {
  render(<input type="text" value="Jan" readOnly />);
  
  const input = screen.getByRole('textbox');
  expect(input).toHaveValue('Jan');
});

Praktisch voorbeeld - Login form

function LoginForm() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  
  const isValid = email && password.length >= 6;
  
  return (
    <form>
      <input 
        type="email" 
        placeholder="Email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
      <input 
        type="password"
        placeholder="Wachtwoord"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
      />
      <button disabled={!isValid}>Login</button>
    </form>
  );
}

test('login button is disabled als form leeg is', () => {
  render(<LoginForm />);
  
  const button = screen.getByText('Login');
  expect(button).toBeDisabled();
});

Overzicht - Meest Gebruikte Matchers

Gelijkheid

Matcher Gebruik Voorbeeld
toBe() Exacte gelijkheid expect(2+2).toBe(4)
toEqual() Diepe gelijkheid (objecten/arrays) expect(obj).toEqual({...})

Getallen

Matcher Gebruik Voorbeeld
toBeGreaterThan() Groter dan expect(10).toBeGreaterThan(5)
toBeLessThan() Kleiner dan expect(5).toBeLessThan(10)

Strings & Arrays

Matcher Gebruik Voorbeeld
toContain() Bevat item/tekst expect('hello').toContain('ell')
toHaveLength() Lengte checken expect([1,2,3]).toHaveLength(3)
toMatch() Regex matching expect(email).toMatch(/@/)

DOM (React)

Matcher Gebruik Voorbeeld
toBeInTheDocument() Element bestaat expect(button).toBeInTheDocument()
toHaveClass() CSS class checken expect(div).toHaveClass('active')
toBeDisabled() Element disabled expect(button).toBeDisabled()
toHaveValue() Input waarde expect(input).toHaveValue('test')

Pro tip: Deze matchers zijn genoeg voor 90% van je tests! Leer deze eerst goed voordat je meer complexe matchers gaat gebruiken.

Tips

1. Gebruik .not om het tegenovergestelde te checken

expect(5).not.toBe(10);
expect(button).not.toBeDisabled();
expect(array).not.toContain('test');

2. Kies de juiste matcher

Gebruik specifieke matchers waar mogelijk - ze geven betere error messages:

// SLECHT
expect(array.length).toBe(3);

// GOED
expect(array).toHaveLength(3);

Veelgemaakte fout: toBe() voor objecten

// FOUT - gebruikt toBe() voor object
const user = { name: 'Jan' };
expect(user).toBe({ name: 'Jan' }); // Faalt!

// GOED - gebruik toEqual()
expect(user).toEqual({ name: 'Jan' }); // Werkt!

Wat nu?

Nu je de basis matchers kent, kun je: