Angular Blog | Medium
Follow
Handling Time and Mock Clocks in Tests
Mock clocks are valuable in software testing for faking dates, speeding up time-consuming operations, and preventing timer leakage between tests. They also help execute all pending timers to stabilize test environments. Traditional mock clocks, however, can introduce complexity and anti-patterns, especially with modern JavaScript's asynchronous capabilities. Forcing synchronous tests for asynchronous logic can lead to unrealistic execution orders and obscure timing bugs. Tests often become cluttered with arbitrary hard-coded timer advancements, making them brittle. Some test utilities might also interfere with the intended timing of a mock clock. To address these issues, the concept of "auto-advancing" mock clocks is being explored. The goal is for mock clocks to advance time realistically, simplifying tests and making them more predictable. This feature aims to allow tests to run with mock clocks without requiring significant changes to existing code. Examples demonstrate how auto-advancing mock clocks seamlessly handle asynchronous functions and waiting for conditions. Test framework authors are being engaged to support this functionality. Libraries like Jasmine and @sinonjs/fake-timers are already incorporating auto-advancing capabilities. This advancement promises faster and more predictable asynchronous tests across various web frameworks.