Compare and contrast Spies and Fakes as types of test doubles. Provide a specific Node.js testing scenario where a Spy would be more appropriate than a Fake, and vice versa.

Node.js interview question for Advanced practice.

Answer

Comparison: Spies wrap a real object, allowing them to record how the object is used (e.g., which methods were called, how many times, with what arguments) while still executing the original implementation. They are used for observation without altering behavior. Fakes are simplified, working implementations of a dependency. They behave like the real thing but are made simpler for testing purposes (e.g., an in-memory database instead of a real one). They don't have the overhead of the real dependency but provide functional behavior. Scenario for a Spy: Imagine you have a cacheService with a getOrSet method that should call a logger.info method only when there is a cache miss. You want to verify this logging behavior without replacing the actual caching logic. Appropriate Choice: A Spy. You would spy on the logger.info method. Your test would then call getOrSet twice—once to populate the cache and a second time to get a cache hit—and assert that the logger.info spy was called only once. Scenario for a Fake: Imagine you have a complex data repository that interacts with a real database like PostgreSQL. For your unit tests of a business logic service that uses this repository, you don't want the overhead or complexity of connecting to a real database. Appropriate Choice: A Fake. You could create an in-memory FakeRepository class that implements the same interface as the real repository but uses a simple JavaScript array or Map to store data. This provides the functional behavior needed for the test (saving and retrieving data) without the external dependency, making tests fast and self-contained.

Explanation

Spies are often used for 'sociable' unit tests where you want to test the interaction with a real dependency, while Fakes are used for 'solitary' unit tests to completely isolate the component.

Related Questions