Spy vs Stub
Question
How does a spy differ from a stub?
Hint
Spies observe; stubs replace.
Explanation
A spy wraps an existing function and records how it was called (arguments, return value, call count) without changing its behavior. Use spies to verify interactions: expect(spy).toHaveBeenCalledWith(arg). A stub replaces a function with a canned response — it does not call the original. Use stubs to control what a dependency returns: stub.mockReturnValue(42). In Jest, jest.fn() can act as both spy and stub. jest.spyOn(obj, method) creates a spy on an existing method (keeps original behavior unless mockReturnValue is called).
Related Resources
Related Lessons
- Stubs & Spies
Learn stubs.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.