codejump
MediumPro challengePythonJavaScriptTypeScript

Implement Fake Timers

TestingAsyncScheduling

jest.useFakeTimers() replaces the real clock with one the test controls: timers only fire when the test advances time.

solve(ops) runs a list of operations against a fresh fake clock (starting at 0) and returns their results:

OpResult
['setTimeout', label, delay]timer ID (0, 1, …). The timer is due at now + delay.
['clearTimeout', id]true if a pending timer was cancelled, false otherwise (unknown, already fired or already cleared)
['advance', ms]moves the clock forward by ms, fires every due timer, returns their labels in firing order
['runAll']fires every pending timer, returns their labels; the clock ends at the last fired timer's due time
['pending']number of timers still waiting
['now']current fake time

Timers fire in order of due time; timers due at the same time fire in creation order.

solve([
  ['setTimeout', 'late', 300],
  ['setTimeout', 'early', 100],
  ['advance', 150],
  ['pending'],
])
// → [0, 1, ['early'], 1]

Sample tests

Test #1timers fire in order of due time
Input: [[["setTimeout","late",300],["setTimeout","early",100],["advance",500]]]
Output: [0,1,["early","late"]]
Test #2clearTimeout cancels once
Input: [[["setTimeout","a",50],["clearTimeout",0],["clearTimeout",0],["advance",100]]]
Output: [0,true,false,[]]
Test #3setTimeout returns incrementing IDs
Input: [[["setTimeout","a",100],["setTimeout","b",200]]]
Output: [0,1]
Test #4pending counts waiting timers
Input: [[["setTimeout","a",100],["setTimeout","b",200],["pending"]]]
Output: [0,1,2]
Test #5advance fires only due timers
Input: [[["setTimeout","a",100],["setTimeout","b",200],["advance",150],["pending"]]]
Output: [0,1,["a"],1]
Test #6runAll fires everything and moves the clock
Input: [[["setTimeout","a",100],["setTimeout","b",50],["runAll"],["pending"],["now"]]]
Output: [0,1,["b","a"],0,100]