Usamos cookies para mejorar tu experiencia en el sitio
CodeWorlds

Framework Jest - podstawy

Jest to najpopularniejszy framework do testowania JavaScript i TypeScript, stworzony przez Meta (dawniej Facebook). W naszym Parku Jurajskim Jest będzie głównym narzędziem do weryfikacji systemów bezpieczeństwa.

Instalacja i konfiguracja

1# Instalacja Jest
2npm install --save-dev jest
3
4# Dla TypeScript
5npm install --save-dev jest ts-jest @types/jest
6
7# Inicjalizacja konfiguracji
8npx jest --init

Struktura testu

Każdy test w Jest składa się z trzech kluczowych elementów:

describe
,
it
(lub
test
) oraz
expect
.

describe - grupowanie testów

describe
to blok grupujący powiązane testy. Pomyśl o nim jak o wybiegu w parku - grupuje dinozaury tego samego gatunku.

1describe('DinosaurEnclosure', () => {
2  // Wszystkie testy związane z wybiegiem dinozaurów
3});

it / test - pojedynczy przypadek testowy

it
i
test
są zamienne - oba definiują pojedynczy test. Konwencja:
it
czyta się jak zdanie w języku angielskim.

1describe('DinosaurEnclosure', () => {
2  it('should have a fence', () => {
3    // sprawdzenie
4  });
5
6  test('fence is electrified', () => {
7    // sprawdzenie
8  });
9});

expect - asercje

expect
to serce każdego testu. Porównuje rzeczywisty wynik z oczekiwanym.

1describe('DinosaurEnclosure', () => {
2  it('should have correct capacity', () => {
3    const enclosure = createEnclosure('T-Rex Zone', 5);
4    expect(enclosure.capacity).toBe(5);
5  });
6
7  it('should start empty', () => {
8    const enclosure = createEnclosure('Raptor Pen', 10);
9    expect(enclosure.dinosaurs).toEqual([]);
10    expect(enclosure.dinosaurs.length).toBe(0);
11  });
12});

Kompletny przykład

Zobaczmy pełny przykład testowania modułu zarządzania dinozaurami:

1// dinosaur.js - kod produkcyjny
2function createDinosaur(name, species, diet) {
3  return {
4    name,
5    species,
6    diet,
7    health: 100,
8    isAlive: true,
9  };
10}
11
12function feedDinosaur(dinosaur, food) {
13  if (dinosaur.diet === 'carnivore' && food === 'meat') {
14    dinosaur.health = Math.min(100, dinosaur.health + 20);
15    return { success: true, message: 'Dinozaur najedzony!' };
16  }
17  if (dinosaur.diet === 'herbivore' && food === 'plants') {
18    dinosaur.health = Math.min(100, dinosaur.health + 15);
19    return { success: true, message: 'Dinozaur najedzony!' };
20  }
21  return { success: false, message: 'Niewłaściwe jedzenie!' };
22}
23
24// dinosaur.test.js - testy
25describe('Dinosaur Management', () => {
26  describe('createDinosaur', () => {
27    it('should create a dinosaur with correct properties', () => {
28      const rex = createDinosaur('Rex', 'T-Rex', 'carnivore');
29
30      expect(rex.name).toBe('Rex');
31      expect(rex.species).toBe('T-Rex');
32      expect(rex.diet).toBe('carnivore');
33      expect(rex.health).toBe(100);
34      expect(rex.isAlive).toBe(true);
35    });
36  });
37
38  describe('feedDinosaur', () => {
39    it('should feed carnivore with meat', () => {
40      const rex = createDinosaur('Rex', 'T-Rex', 'carnivore');
41      rex.health = 70;
42
43      const result = feedDinosaur(rex, 'meat');
44
45      expect(result.success).toBe(true);
46      expect(rex.health).toBe(90);
47    });
48
49    it('should reject wrong food for carnivore', () => {
50      const rex = createDinosaur('Rex', 'T-Rex', 'carnivore');
51
52      const result = feedDinosaur(rex, 'plants');
53
54      expect(result.success).toBe(false);
55    });
56  });
57});

Uruchamianie testów

1# Uruchom wszystkie testy
2npx jest
3
4# Uruchom konkretny plik
5npx jest dinosaur.test.js
6
7# Uruchom w trybie watch (reaguje na zmiany)
8npx jest --watch
9
10# Uruchom z raportowaniem pokrycia kodu
11npx jest --coverage

Wzorzec AAA (Arrange-Act-Assert)

Każdy dobry test powinien być napisany według wzorca AAA:

1it('should increase health when fed correctly', () => {
2  // Arrange (Przygotowanie) - stwórz potrzebne obiekty
3  const dino = createDinosaur('Brachio', 'Brachiosaurus', 'herbivore');
4  dino.health = 60;
5
6  // Act (Akcja) - wykonaj testowaną operację
7  const result = feedDinosaur(dino, 'plants');
8
9  // Assert (Sprawdzenie) - zweryfikuj wynik
10  expect(result.success).toBe(true);
11  expect(dino.health).toBe(75);
12});
Ir a CodeWorlds