Simulações e substitutos de teste em Node.js
Aprenda a isolar o código em teste substituindo dependências reais por simulações, dublês e espiões, para que seus testes unitários permaneçam rápidos e determinísticos.
Simulações e substitutos de teste em Node.js é uma aula grátis de Node.js Backend Development Bootcamp no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Node.js Backend Development Bootcamp, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Node.js Backend Development Bootcamp inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em 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 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.
Perguntas Frequentes
A aula “Simulações e substitutos de teste em Node.js” é grátis?
Sim — o texto completo de “Simulações e substitutos de teste em Node.js” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Node.js Backend Development Bootcamp, atualize para CoddyKit PRO. O curso de Node.js Backend Development Bootcamp inclui 4 aulas no total.
O que vou aprender em “Simulações e substitutos de teste em Node.js”?
Aprenda a isolar o código em teste substituindo dependências reais por simulações, dublês e espiões, para que seus testes unitários permaneçam rápidos e determinísticos. Você pratica Node.js Backend Development Bootcamp com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Node.js Backend Development Bootcamp?
Nenhuma experiência prévia é necessária. Node.js Backend Development Bootcamp no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Simulações e substitutos de teste em Node.js”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Node.js Backend Development Bootcamp?
Sim. Cada aula de Node.js Backend Development Bootcamp inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Testes Unitários com Jest
- Testes de integração de endpoints de API
- Técnicas eficazes de depuração
- Simulações e substitutos de teste em Node.js