hardConceptCodingMidSeniorStaffLead
How do you test code that finishes later or depends on the current time, without putting a sleep in the test?
5 min readUpdated 2026-08-15Target archetype: Big Tech, Enterprise Captive, Product Startup
Answer
Short answer
Make time and scheduling injectable. Clock as a dependency so a test can fix it, and replace a fixed sleep with a bounded poll on the observable outcome, so a fast machine does not wait and a slow one does not fail.
Was this answer helpful?
Likely follow-ups
- What would you assert to prove a scheduled job behaves correctly at midnight in another time zone?
- Where does a latch beat a polling wait, and where is it worse?
- If a test fails only in CI, how do you narrow that down?
- How do you test a retry with exponential backoff without waiting for the backoff?
Related questions
- A test passes on its own and fails when the whole suite runs. How do you track that down?mediumAlso on testing and flaky-tests5 min
- How do you test a service that calls a third-party API, without calling it?mediumAlso on testing4 min
- Where do you draw the line between a unit test and an integration test, and how do you keep a few thousand of them under ten minutes?hardAlso on junit6 min
- How do you test a Node service, and what do you refuse to mock?mediumAlso on testing6 min