0Pricing
Node.js Backend Development Bootcamp · Lección

Mocks y dobles de prueba en Node.js

Aprenda a aislar el código bajo prueba sustituyendo las dependencias reales por mocks, stubs y spies, para que sus pruebas unitarias sean rápidas y deterministas.

Mocks y dobles de prueba en Node.js es una lección gratuita de Node.js Backend Development Bootcamp en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Node.js Backend Development Bootcamp, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Node.js Backend Development Bootcamp incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

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 data
  • mockReset() 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.

Preguntas frecuentes

¿La lección «Mocks y dobles de prueba en Node.js» es gratis?

Sí — el texto completo de «Mocks y dobles de prueba en Node.js» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Node.js Backend Development Bootcamp, actualiza a CoddyKit PRO. El curso de Node.js Backend Development Bootcamp incluye 4 lecciones en total.

¿Qué aprenderé en «Mocks y dobles de prueba en Node.js»?

Aprenda a aislar el código bajo prueba sustituyendo las dependencias reales por mocks, stubs y spies, para que sus pruebas unitarias sean rápidas y deterministas. Practicas Node.js Backend Development Bootcamp con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Node.js Backend Development Bootcamp?

No se requiere experiencia previa. Node.js Backend Development Bootcamp en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Mocks y dobles de prueba en Node.js»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Node.js Backend Development Bootcamp?

Sí. Cada lección de Node.js Backend Development Bootcamp incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Pruebas unitarias con Jest
  2. Pruebas de integración de endpoints de API
  3. Técnicas eficaces de depuración
  4. Mocks y dobles de prueba en Node.js
← Volver a Node.js Backend Development Bootcamp