Mockowanie i obiekty testowe w Node.js
Proszę nauczyć się izolować testowany kod, zastępując rzeczywiste zależności obiektami mock, stubami i szpiegami, aby testy jednostkowe pozostały szybkie i deterministyczne.
Mockowanie i obiekty testowe w Node.js to bezpłatna lekcja Node.js Backend Development Bootcamp na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Node.js Backend Development Bootcamp, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Node.js Backend Development Bootcamp zawiera 4 lekcji w sumie.
Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.
The Problem with Real Dependencies
A unit test should check one piece of logic in isolation. But real code calls databases, APIs, the clock, and the file system — all slow, flaky, and unpredictable.
Test doubles replace those dependencies with controllable fakes.
Types of Test Doubles
Common terms you will hear:
- Stub: returns a canned value
- Spy: records how it was called
- Mock: a stub + spy with built-in expectations
- Fake: a lightweight working implementation
Creating a Mock Function
In Jest, jest.fn() creates a mock function. It records every call and lets you assert on them later.
const callback = jest.fn();
callback('hello');
expect(callback).toHaveBeenCalledWith('hello');Defining Return Values
Tell a mock what to return with mockReturnValue, or for async code use mockResolvedValue to resolve a promise.
const getUser = jest.fn().mockResolvedValue({ id: 1, name: 'Ada' });
const user = await getUser();
expect(user.name).toBe('Ada');Asserting on Calls
Spies let you verify interactions:
toHaveBeenCalled()toHaveBeenCalledTimes(n)toHaveBeenCalledWith(args)
const save = jest.fn();
save({ id: 1 });
expect(save).toHaveBeenCalledTimes(1);Mocking a Module
To replace an entire imported module, use jest.mock(). Every export becomes an auto-mock you can configure per test.
jest.mock('./mailer');
const mailer = require('./mailer');
mailer.send.mockResolvedValue(true);Spying on Existing Methods
Sometimes you want to watch a real method without replacing it. jest.spyOn() wraps an existing method so you can assert and optionally override it.
const spy = jest.spyOn(console, 'log');
console.log('hi');
expect(spy).toHaveBeenCalledWith('hi');Resetting Between Tests
Mocks accumulate state. Reset them between tests so calls from one test do not leak into another.
mockClear()clears call datamockReset()also clears implementations
afterEach(() => {
jest.clearAllMocks();
});Mocking Time
Tests that depend on the current time are flaky. Jest fake timers let you control the clock so timeouts and dates are deterministic.
jest.useFakeTimers();
const fn = jest.fn();
setTimeout(fn, 1000);
jest.advanceTimersByTime(1000);
expect(fn).toHaveBeenCalled();Dependency Injection Makes Mocking Easy
Code that receives its dependencies as arguments is far easier to test than code that imports them directly. Design for testability.
function createService(db) {
return { getUser: id => db.find(id) };
}
const fakeDb = { find: jest.fn().mockReturnValue({ id: 1 }) };
const svc = createService(fakeDb);Don't Over-Mock
Mocking too much produces tests that only confirm your mocks were called — not that the code works. Mock external boundaries (DB, network), but test real logic directly when you can.
Quick Check
Test your understanding of test doubles.
Recap
You learned to isolate code with test doubles:
- Create mocks with
jest.fn()and configure return values - Replace modules with
jest.mock() - Watch real methods with
jest.spyOn() - Reset mocks between tests and control time with fake timers
- Inject dependencies for testability and avoid over-mocking
Good mocking keeps unit tests fast, reliable, and focused.
Często zadawane pytania
Czy lekcja „Mockowanie i obiekty testowe w Node.js” jest bezpłatna?
Tak — pełny tekst „Mockowanie i obiekty testowe w Node.js” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Node.js Backend Development Bootcamp, przejdź na CoddyKit PRO. Kurs Node.js Backend Development Bootcamp zawiera 4 lekcji w sumie.
Co nauczysz się w „Mockowanie i obiekty testowe w Node.js”?
Proszę nauczyć się izolować testowany kod, zastępując rzeczywiste zależności obiektami mock, stubami i szpiegami, aby testy jednostkowe pozostały szybkie i deterministyczne. Ćwiczysz Node.js Backend Development Bootcamp z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.
Czy potrzebuję doświadczenia, aby zacząć Node.js Backend Development Bootcamp?
Nie wymagamy żadnego doświadczenia. Node.js Backend Development Bootcamp w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.
Ile czasu zajmuje lekcja „Mockowanie i obiekty testowe w Node.js”?
Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.
Czy mogę pisać i uruchamiać kod w tej lekcji Node.js Backend Development Bootcamp?
Tak. Każda lekcja Node.js Backend Development Bootcamp zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.
Wszystkie lekcje w tym kursie
- Testy jednostkowe za pomocą Jest
- Testy integracyjne endpointów API
- Skuteczne techniki debugowania
- Mockowanie i obiekty testowe w Node.js