Mocking und Test-Doubles in Node.js
Lernen Sie, wie Sie den getesteten Code isolieren, indem Sie echte Abhängigkeiten durch Mocks, Stubs und Spies ersetzen, damit Ihre Unit-Tests schnell und deterministisch bleiben.
Mocking und Test-Doubles in Node.js ist eine kostenlose Node.js Backend Development Bootcamp-Lektion auf CoddyKit. Dies ist Lektion 4 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Node.js Backend Development Bootcamp-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Node.js Backend Development Bootcamp-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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.
Häufig gestellte Fragen
Ist die Lektion „Mocking und Test-Doubles in Node.js“ kostenlos?
Ja — der vollständige Text von „Mocking und Test-Doubles in Node.js“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Node.js Backend Development Bootcamp-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Node.js Backend Development Bootcamp-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Mocking und Test-Doubles in Node.js“?
Lernen Sie, wie Sie den getesteten Code isolieren, indem Sie echte Abhängigkeiten durch Mocks, Stubs und Spies ersetzen, damit Ihre Unit-Tests schnell und deterministisch bleiben. Du übst Node.js Backend Development Bootcamp mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Node.js Backend Development Bootcamp zu starten?
Keine Vorkenntnisse erforderlich. Node.js Backend Development Bootcamp auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 4 von 4.
Wie lange dauert die Lektion „Mocking und Test-Doubles in Node.js“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Node.js Backend Development Bootcamp-Lektion Code schreiben und ausführen?
Ja. Jede Node.js Backend Development Bootcamp-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Unit-Tests mit Jest
- Integrationstests für API-Endpunkte
- Effektive Debugging-Techniken
- Mocking und Test-Doubles in Node.js