Kurs JavaScript i TypeScript · Moduł 11: Testowanie z Jest
Projekt: Kompletny zestaw testów dla systemu Parku Jurajskiego
W tej lekcji2
Park działa, dinozaury są nakarmione, ale nikt nie wie, czy jutrzejsza poprawka w systemie karmienia nie wyłączy ogrodzenia w strefie raptorów. Dlatego piszemy zestaw testów: żeby każda zmiana przechodziła przez te same czujniki, zanim trafi do parku.
Czas na finalne wyzwanie! Zbudujesz kompletny zestaw testów dla systemu zarządzania Parkiem Jurajskim. Ten projekt łączy wszystkie koncepcje z modułu: Jest, matchery, setup/teardown, mockowanie, testowanie asynchroniczne, TDD i TypeScript.
System do przetestowania
Poniżej znajdziesz kompletny system zarządzania parkiem. Twoim zadaniem jest napisanie testów dla każdego modułu. Kod jest długi, ale nie musisz go zapamiętywać. Czytaj go jak specyfikację, w której każda instrukcja if i każdy throw to kandydat na osobny test.
Moduł 1: Zarządzanie dinozaurami
DinosaurManager przechowuje okazy w Map, czyli kolekcji par klucz-wartość, i nadaje im identyfikatory DINO-001, DINO-002 i kolejne. Zwróć uwagę na wyjątek przy braku imienia albo gatunku oraz na wszystkożerców, którzy przyjmują dwa rodzaje pokarmu:
// dinosaurManager.js
class DinosaurManager {
constructor() {
this.dinosaurs = new Map();
this.nextId = 1;
}
addDinosaur(name, species, diet, zone) {
if (!name || !species) {
throw new Error('Name and species are required');
}
const id = `DINO-${String(this.nextId).padStart(3, '0')}`;
this.nextId++;
const dinosaur = {
id,
name,
species,
diet,
zone,
health: 100,
fed: false,
lastFed: null,
};
this.dinosaurs.set(id, dinosaur);
return dinosaur;
}
getDinosaur(id) {
return this.dinosaurs.get(id) || null;
}
feedDinosaur(id, food) {
const dino = this.getDinosaur(id);
if (!dino) throw new Error('Dinosaur not found');
const correctFood = {
carnivore: 'meat',
herbivore: 'plants',
omnivore: ['meat', 'plants'],
};
const expected = correctFood[dino.diet];
const isCorrect = Array.isArray(expected)
? expected.includes(food)
: expected === food;
if (!isCorrect) {
return { success: false, message: 'Wrong food type' };
}
dino.health = Math.min(100, dino.health + 10);
dino.fed = true;
dino.lastFed = new Date();
return { success: true, health: dino.health };
}
getByZone(zone) {
return [...this.dinosaurs.values()].filter(d => d.zone === zone);
}
getByDiet(diet) {
return [...this.dinosaurs.values()].filter(d => d.diet === diet);
}
getTotalCount() {
return this.dinosaurs.size;
}
}Zacznij od beforeEach, który tworzy świeżego menedżera, bo inaczej licznik nextId przeniesie się między testami i drugi test dostanie DINO-002 zamiast DINO-001. Pole lastFed dostaje new Date(), czyli wartość, której nie przewidzisz. Sprawdź je przez expect.any(Date) albo zamroź czas sztucznym zegarem i jest.setSystemTime. Przy złym pokarmie upewnij się też, że zdrowie się nie zmieniło.
Moduł 2: System bezpieczeństwa
SecuritySystem dostaje alertService w konstruktorze. To wstrzykiwanie zależności i najlepsza wiadomość dla testera, bo zamiast jest.mock wystarczy przekazać obiekt z mockiem. Metoda reportBreach po trzecim naruszeniu włącza lockdown i podwaja napięcie ogrodzenia:
// securitySystem.js
class SecuritySystem {
constructor(alertService) {
this.alertService = alertService; // zależność do mockowania
this.zones = new Map();
this.logs = [];
}
registerZone(name, fenceVoltage, securityLevel) {
this.zones.set(name, {
name,
fenceVoltage,
securityLevel,
status: 'active',
breachCount: 0,
});
}
async reportBreach(zoneName) {
const zone = this.zones.get(zoneName);
if (!zone) throw new Error('Zone not found');
zone.breachCount++;
zone.status = 'breached';
this.logs.push({
type: 'BREACH',
zone: zoneName,
timestamp: Date.now(),
});
await this.alertService.sendAlert(zoneName, 'Security breach detected');
if (zone.breachCount >= 3) {
await this.activateLockdown(zoneName);
}
return { status: 'reported', breachCount: zone.breachCount };
}
async activateLockdown(zoneName) {
const zone = this.zones.get(zoneName);
zone.status = 'lockdown';
zone.fenceVoltage *= 2;
await this.alertService.sendAlert(
zoneName,
'LOCKDOWN ACTIVATED'
);
this.logs.push({
type: 'LOCKDOWN',
zone: zoneName,
timestamp: Date.now(),
});
}
getZoneStatus(zoneName) {
const zone = this.zones.get(zoneName);
return zone ? zone.status : null;
}
}Tak może wyglądać początek Twoich testów. Mock sendAlert od razu zwraca spełnioną obietnicę, a strefa dostaje napięcie 10000 i poziom zabezpieczeń 9:
const alertService = {
sendAlert: jest.fn().mockResolvedValue({ status: 'sent' }),
};
const security = new SecuritySystem(alertService);
security.registerZone('Raptor Pen', 10000, 9);Po trzech wywołaniach await security.reportBreach('Raptor Pen') strefa powinna mieć status lockdown, a sendAlert powinien zostać wywołany cztery razy: trzy alerty o naruszeniu i jeden "LOCKDOWN ACTIVATED". Nieznana strefa to odrzucona obietnica, więc sprawdzisz ją przez rejects.toThrow('Zone not found').
Moduł 3: System monitoringu (asynchroniczny)
MonitoringService łączy obietnicę z timerem: checkSensor odpowiada po sekundzie, a startMonitoring co intervalMs milisekund przekazuje odczyty do callbacku przez setInterval:
// monitoringService.js
class MonitoringService {
constructor() {
this.sensors = [];
this.interval = null;
}
addSensor(zoneId, type) {
this.sensors.push({
zoneId,
type,
status: 'online',
lastReading: null,
});
}
async checkSensor(index) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (index < 0 || index >= this.sensors.length) {
reject(new Error('Sensor not found'));
return;
}
const sensor = this.sensors[index];
sensor.lastReading = Date.now();
resolve({
zoneId: sensor.zoneId,
type: sensor.type,
status: sensor.status,
reading: Math.random() * 100,
});
}, 1000);
});
}
startMonitoring(callback, intervalMs) {
this.interval = setInterval(() => {
const readings = this.sensors.map(s => ({
zone: s.zoneId,
status: s.status,
}));
callback(readings);
}, intervalMs);
}
stopMonitoring() {
if (this.interval) {
clearInterval(this.interval);
this.interval = null;
}
}
}Tu przydadzą się sztuczne zegary. Wywołaj checkSensor, przewiń czas o 1000 ms i dopiero wtedy poczekaj na obietnicę przez await. Bez przewinięcia obietnica nigdy by się nie spełniła, a test utknąłby do timeoutu. Pole reading pochodzi z Math.random(), więc sprawdzaj je przez expect.any(Number). Dla startMonitoring przewiń czas o kilka interwałów i policz wywołania callbacku przez toHaveBeenCalledTimes, a po stopMonitoring upewnij się, że kolejne przewinięcie niczego już nie dodaje.
Twoje zadanie
Napisz kompletny zestaw testów obejmujący:
- DinosaurManager - testy jednostkowe z beforeEach, testowanie wyjątków
- SecuritySystem - mockowanie alertService, testowanie async
- MonitoringService - fake timers, testowanie callbacków i Promise
- Testy integracyjne - współpraca między modułami
Pamiętaj o wzorcu AAA (Arrange-Act-Assert) i zasadach TDD! Test integracyjny może na przykład dodać raptora do strefy w DinosaurManager, zarejestrować tę samą strefę w SecuritySystem i sprawdzić, że po serii naruszeń raptor wciąż jest na liście, a strefa ma status lockdown.
Moja rada: zacznij od jednego describe na moduł i jednego testu na każdą gałąź if. Dopiero gdy wszystkie ścieżki są zielone, dopisuj przypadki brzegowe, takie jak karmienie dinozaura, którego nie ma w rejestrze. Gotowy projekt wyślij mentorowi w następnym zadaniu.
W laboratorium poniżej czekają uproszczone testy DinosaurManager i komentarze TODO dla dwóch pozostałych modułów. Potraktuj je jako rozgrzewkę przed prawdziwym zestawem w Jeście.
Pamiętaj: kompletny zestaw testów to sieć czujników całego parku - dopiero gdy każdy wybieg ma swój czujnik, możesz spać spokojnie.
Kod do tej lekcji: index.js
// Projekt: Kompletny zestaw testow - Park Jurajski
console.log("=== Park Jurajski - Kompletny System Testow ===\n");
let passed = 0, failed = 0;
function assert(cond, msg) {
if (cond) { passed++; console.log(" [PASS] " + msg); }
else { failed++; console.log(" [FAIL] " + msg); }
}
function assertThrows(fn, expected) {
try { fn(); failed++; console.log(" [FAIL] Expected throw"); }
catch (e) {
if (expected && !e.message.includes(expected)) {
failed++; console.log(" [FAIL] Wrong error: " + e.message);
} else { passed++; console.log(" [PASS] Threw: " + e.message); }
}
}
// =============================================
// KOD PRODUKCYJNY
// =============================================
class DinosaurManager {
constructor() { this.dinosaurs = new Map(); this.nextId = 1; }
addDinosaur(name, species, diet, zone) {
if (!name || !species) throw new Error("Name and species are required");
const id = "DINO-" + String(this.nextId).padStart(3, "0");
this.nextId++;
const dino = { id, name, species, diet, zone, health: 100, fed: false, lastFed: null };
this.dinosaurs.set(id, dino);
return dino;
}
getDinosaur(id) { return this.dinosaurs.get(id) || null; }
feedDinosaur(id, food) {
const dino = this.getDinosaur(id);
if (!dino) throw new Error("Dinosaur not found");
const correct = { carnivore: "meat", herbivore: "plants", omnivore: ["meat", "plants"] };
const expected = correct[dino.diet];
const ok = Array.isArray(expected) ? expected.includes(food) : expected === food;
if (!ok) return { success: false, message: "Wrong food type" };
dino.health = Math.min(100, dino.health + 10);
dino.fed = true;
dino.lastFed = new Date();
return { success: true, health: dino.health };
}
getByZone(zone) { return [...this.dinosaurs.values()].filter(d => d.zone === zone); }
getByDiet(diet) { return [...this.dinosaurs.values()].filter(d => d.diet === diet); }
getTotalCount() { return this.dinosaurs.size; }
}
// TODO: Napisz testy dla SecuritySystem i MonitoringService
// Uzyj wzorca AAA, mockowania i fake timerow
// =============================================
// TESTY
// =============================================
console.log("Suite: DinosaurManager\n");
// beforeEach equivalent
function setup() { return new DinosaurManager(); }
console.log(" describe: addDinosaur");
let mgr = setup();
let rex = mgr.addDinosaur("Rex", "T-Rex", "carnivore", "Zone A");
assert(rex.id === "DINO-001", "first dino has ID DINO-001");
assert(rex.name === "Rex", "has correct name");
assert(rex.health === 100, "starts with 100 health");
assert(rex.fed === false, "starts not fed");
mgr = setup();
assertThrows(() => mgr.addDinosaur("", "T-Rex", "carnivore", "A"), "Name and species");
assertThrows(() => mgr.addDinosaur("Rex", "", "carnivore", "A"), "Name and species");
console.log("\n describe: feedDinosaur");
mgr = setup();
rex = mgr.addDinosaur("Rex", "T-Rex", "carnivore", "Zone A");
let feedResult = mgr.feedDinosaur(rex.id, "meat");
assert(feedResult.success === true, "carnivore eats meat");
assert(rex.fed === true, "marked as fed");
assert(rex.health === 100, "health capped at 100");
mgr = setup();
rex = mgr.addDinosaur("Rex", "T-Rex", "carnivore", "A");
feedResult = mgr.feedDinosaur(rex.id, "plants");
assert(feedResult.success === false, "carnivore rejects plants");
assert(feedResult.message === "Wrong food type", "correct error message");
mgr = setup();
assertThrows(() => mgr.feedDinosaur("FAKE-ID", "meat"), "not found");
console.log("\n describe: queries");
mgr = setup();
mgr.addDinosaur("Rex", "T-Rex", "carnivore", "Zone A");
mgr.addDinosaur("Blue", "Velociraptor", "carnivore", "Zone A");
mgr.addDinosaur("Brachio", "Brachiosaurus", "herbivore", "Zone B");
assert(mgr.getTotalCount() === 3, "total count is 3");
assert(mgr.getByZone("Zone A").length === 2, "2 in Zone A");
assert(mgr.getByZone("Zone B").length === 1, "1 in Zone B");
assert(mgr.getByDiet("carnivore").length === 2, "2 carnivores");
assert(mgr.getByDiet("herbivore").length === 1, "1 herbivore");
assert(mgr.getDinosaur("FAKE") === null, "null for missing dino");
// TODO: Dodaj wlasne testy ponizej!
// - Przetestuj SecuritySystem z mockowanym alertService
// - Przetestuj MonitoringService z fake timerami
// - Napisz testy integracyjne
console.log(`\n=== Wyniki: ${passed} passed, ${failed} failed ===`);
console.log("\nDodaj wiecej testow w edytorze powyzej!");Hasła z dokumentacji w tej lekcji
Widzisz błąd w tej lekcji?