How does asynchronous code change the way automated tests should be written?
Answer
Synchronous code completes before the next statement, while asynchronous work may finish later or fail through a promise, callback, event or queue. Tests should await an observable completion condition, assert timeouts and errors, control clocks and dependencies where appropriate, and avoid fixed sleeps that create races and wasted time.
Strong answer includes
- waits for conditions rather than time
- tests rejection, timeout and ordering
- controls asynchronous dependencies
Practical example
A flaky UI test uses a hardcoded sleep(3000) after clicking 'Submit' to wait for a toast notification, which fails intermittently when the API is slow and wastes three seconds when it's fast. The fix replaces it with an explicit wait for the toast element to appear, adds a separate test that mocks a delayed API response to assert the loading spinner and timeout error, and controls the system clock in a unit test that checks a 30-second session-expiry callback fires exactly once.