<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dragan Smiljanic on Medium]]></title>
        <description><![CDATA[Stories by Dragan Smiljanic on Medium]]></description>
        <link>https://medium.com/@dragansmiljanic?source=rss-44d4cdbb0001------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*L4P74KUHp4B7QOfT.jpg</url>
            <title>Stories by Dragan Smiljanic on Medium</title>
            <link>https://medium.com/@dragansmiljanic?source=rss-44d4cdbb0001------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 06:37:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dragansmiljanic/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Jest’s Timer Mocks Deep Dive — Part 1]]></title>
            <link>https://medium.com/@dragansmiljanic/jests-timer-mocks-deep-dive-part-1-a2e879ae6ec2?source=rss-44d4cdbb0001------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2e879ae6ec2</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Dragan Smiljanic]]></dc:creator>
            <pubDate>Fri, 11 Nov 2022 12:14:12 GMT</pubDate>
            <atom:updated>2022-11-11T12:14:12.440Z</atom:updated>
            <content:encoded><![CDATA[<h3>Jest’s Timer Mocks Deep Dive — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3t4zLF2kT6NDaPrEee5nsg.jpeg" /></figure><blockquote>Beware of bugs in the above code; I have only proved it correct, not tried it.<br> — Donald Knuth, March 29th 1977 [<a href="https://staff.fnwi.uva.nl/p.vanemdeboas/knuthnote.pdf">pg. 5</a>]</blockquote><p>Timeouts are a really nice feature of Javascript and they are broadly used by developers. Everything changes when we come to the point when we need to cover them with unit tests. Testing the functionality involved in asynchronous operations can be a challenge.</p><h3>Introduction</h3><p>Let’s start with a simple example. The class Elevator has a single method openDoor and a single state member isDoorOpen.</p><pre>class Elevator {<br>  isDoorOpen: boolean;<br>  constructor() {<br>    this.isDoorOpen = false;<br>  }<br><br>  openDoor()  {<br>    this.isDoorOpen = true<br>    setTimeout(() =&gt; { this.isDoorOpen = false; }, 5 * 1000);<br>  }<br>}</pre><p>A naive approach to write an unit test might be something like:</p><pre>describe(&#39;elevator&#39;, () =&gt; {<br>  test(&#39;Should close door&#39;, () =&gt; {<br>    const elevator = new Elevator();<br>    elevator.openDoor();<br><br>    expect(elevator.isDoorOpen).toBe(true);<br><br>    setTimeout(() =&gt; {<br>      expect(elevator.isDoorOpen).toBe(false);<br>    }, 5000)<br>  })<br>}</pre><p>This test passes as the second assert enclosed in setTimeout function is ignored by the test runner: the test result is generated immediately as the test closure is executed.</p><p>The test suite’s method test expects an argument of type ProvidesFeedback. This can be a function that returnsPromise or a function that accepts an optional parameter — callback function.</p><blockquote>As a reminder, each asynchronous function returns a promise:<br>const asyncFn: Promise&lt;void&gt; = async () =&gt; {};</blockquote><p>When a callback function (done) is provided, the test result will be generated after callback function is invoked:</p><pre>test(&#39;Should close door&#39;, (done) =&gt; {<br>  ...<br>  setTimeout(() =&gt; {<br>    expect(elevator.isDoorOpen).toBe(false);<br>    done();<br>  }, 5000)<br>})</pre><p>Still, the callback function won’t solve the problem. Before the setTimer handler is executed, the test runner will throw a timeout exception. The error message:</p><pre>thrown: &quot;Exceeded timeout of 5000 ms for a test.<br>    Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test.&quot;</pre><p>The jest.setTimeout method can temporarily solve the broken test. If we decide to keep the door of elevator opened for a longer period we will need to tweak timeout again. There should be a better approach.</p><h3>setTimeout mock function</h3><p>If there is mechanism to control the passage of time in order to immediately force execution of callback provided to setTimeout, our test can have a simple form. The solution is not related to the physics — we just used the fancy name “<a href="https://en.wikipedia.org/wiki/Hendrik_Lorentz">time dilation</a>”.</p><pre>test(&#39;Should close door&#39;, () =&gt; {<br>    const elevator = new Elevator();<br>    elevator.openDoor();<br>    expect(elevator.isDoorOpen).toBe(true);<br>    timeDilation(5000);<br>    expect(elevator.isDoorOpen).toBe(false);<br>});</pre><p>Let’s implement the functionality:</p><pre>type Timer = {<br>  id: number;<br>  fn: () =&gt; void,<br>  executeAt: number;<br>}<br><br>export const fakeTimers = () =&gt; {<br>  let timerId = 1e9;<br>  const originalSetTimeout = global.setTimeout;<br>  let now = +(new Date());<br><br>  let timers = [] as Timer[];<br><br>  const fakeSetTimeout = (fn: () =&gt; void, delay: number) =&gt; {<br>    const timer = {<br>      id: ++timerId,<br>      fn,<br>      executeAt: now + (delay ?? 0)<br>    };<br>    timers.push(timer);<br>    return timerId;<br>  };<br><br>  // @ts-ignore<br>  global.setTimeout = fakeSetTimeout;<br><br>  const executeTimer = (timer: Timer) =&gt; {<br>    timer.fn();<br>  };<br><br>  const tick = (tickValue: number) =&gt; {<br>    const currentTS = now;<br>    now += tickValue;<br><br>    while (timers.length) {<br>      const timer = timers[0];<br>      if (timer.executeAt &lt;= currentTS + tickValue) {<br>        executeTimer(timer);<br>        timers = timers.slice(1);<br>      } else {<br>        return;<br>      }<br>    }<br>    if (timers.length) {<br>      tick(tickValue);<br>    }<br>  };<br><br>  const uninstall = () =&gt; {<br>    global.setTimeout = originalSetTimeout;<br>  };<br><br>  return {<br>    tick,<br>    uninstall<br>  };<br>};</pre><p>Now, we can change our test (there is no need for done callback anymore):</p><pre>test(&#39;Should close door&#39;, () =&gt; {<br>  const { tick, uninstall } = fakeTimers();<br><br>  const elevator = new Elevator();<br>  elevator.openDoor();<br><br>  expect(elevator.isDoorOpen).toBe(true);<br><br>  tick(5000);<br><br>  expect(elevator.isDoorOpen).toBe(false);<br>})</pre><p>The given implementation of fakeTimer function is far from general solution: once the fakeTimer is called, a reference to original setTimeout function is saved and native setTimeout function is replaced to a mock function. Once, the function is invoked, a new entry of type Timer is added to execution queue timers and id of created timer is returned.</p><blockquote>Please note, in the Node.js environment, setTimeout returns an object of type <a href="https://nodejs.org/dist/latest-v19.x/docs/api/timers.html#class-timeout">Timeout</a>; in browser the returned value is <a href="https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#return_value">a positive integer</a>. Ideally, if you need to save the result of setTimeout function, I would suggest to use the following type let timerId: ReturnType&lt;typeof setTimeout&gt;;.</blockquote><p>The tick method executes all timers for which the field executeAt is in the time interval [now, now + tickValue]. As it might happen that some setTimeout spawn another timer, tick is executed recursively, as long as the execution queue (field timers) contains any task whose execution time is in the give time interval.</p><h3>Sinon.JS Fake Timers</h3><p>The fake timers used by Jest are provided by <a href="https://github.com/sinonjs">Sinon.JS</a> library. The source code of Sinon.JS Fake Timers can be found <a href="https://github.com/sinonjs/fake-timers">here</a> (<a href="https://www.npmjs.com/package/lolex">ex Lolex</a>).</p><blockquote><a href="http://twitter.com/sinonjs/fake-timers">@sinonjs/fake-timers</a> can be used to simulate passing time in automated tests and other situations where you want the scheduling semantics, but don’t want to actually wait. (<a href="https://github.com/sinonjs/fake-timers">https://github.com/sinonjs/fake-timers</a>)</blockquote><p>The main entry point createClock creates a clock object. From the aspect of testing, more important factory method is install. It replaces native javascript objects and asynchronous methods (check hijackMethod) in a way that we can control the flow of time:</p><blockquote>setTimeout, clearTimeout<br>setImmediate, clearImmediate<br>setInterval, clearInterval<br>requestAnimationFrame, cancelAnimationFrame<br>requestIdleCallback, cancelIdleCallback<br>nextTick (node.js only)<br>Date<br>hrtime (node.js only)<br>performance</blockquote><p>and returns an instance of the clock same as createClock.</p><p>A quick look on implementation: the instance of clock object keeps the collection of timers in timers object. The mock of asynchronous methods like setInterval or requestIdleCallback adds timer structure describing what, when and how some task should be executed (defines the execution time, handler and possible arguments of the handler).</p><p>In Node.js environment jobs array is used to hold the handlers of the deferred executors <a href="https://nodejs.org/dist/latest-v19.x/docs/api/all.html#all_process_processnexttickcallback-args">nextTick</a> and <a href="https://nodejs.org/dist/latest-v19.x/docs/api/all.html#all_globals_queuemicrotaskcallback">queueMicrotask</a>.</p><p>The signature of setTimeout method:</p><pre>setTimeout(code: string)<br>setTimeout(code: string, delay: number)<br><br>setTimeout(functionRef: (...args: any[]) =&gt; void)<br>setTimeout(functionRef, delay)<br>setTimeout(functionRef, delay, param1: any)<br>setTimeout(functionRef, delay, param1: any, param2: any)<br>setTimeout(functionRef, delay, param1, param2, /* … ,*/ paramN) <br>// setTimeout(&quot;x = 3&quot;, 100)<br>// setTimeout((x, y) =&gt; x + y, 100, 2, 3);</pre><blockquote>As setTimeout can accept a string parameter, an eval method can be found in the task executor function callTimer.</blockquote><h3>clock.next*</h3><p>The first scheduled timer can be executed by clock.next method. Before the task assigned to timer is executed, all scheduled jobs are executed. During the execution, new jobs might be created. They will be executed synchronously after the timer task is done.</p><p>The method clock.next* advances internal timer to moment when the first task is executed.</p><p>If we need to deal with promises, we can use asynchronous variant clock.nextAsync. For the following tests order of “exit task” and “end” logs is different:</p><pre>// yarn add -D @sinonjs/fake-timers<br>// yarn add -D @types/sinonjs__fake-timers<br>import { install } from &#39;@sinonjs/fake-timers&#39;;<br>test(&#39;next&#39;, async () =&gt; {<br>    const mock = jest.fn();<br>    const clock = install(150);<br><br>    expect(clock.now, 150);<br><br>    console.log(&#39;start&#39;);<br>    setTimeout(task(mock), 100);<br><br>    expect(mock).not.toBeCalled();<br><br>    expect(clock.next()).toBe(250);<br><br>    expect(mock).not.toBeCalled();<br><br>    console.log(&#39;end&#39;);<br><br>    clock.uninstall();<br>});<br><br>// stdout:<br>// start<br>// start task<br>// Promise resolved<br>// end<br>// exit task<br><br>test(&#39;nextAsync&#39;, async () =&gt; {<br>    const mock = jest.fn();<br>    const clock = install()<br>    console.log(&#39;start&#39;);<br>    setTimeout(task(mock), 100);<br><br>    expect(mock).not.toBeCalled();<br><br>    expect(await clock.nextAsync()).toBe(100); // async variant !!!<br><br>    expect(mock).toBeCalled();<br><br>    console.log(&#39;end&#39;);<br><br>    clock.uninstall();<br>});<br><br>// stdout:<br>// start<br>// start task<br>// Promise resolved<br>// exit task<br>// end</pre><h3>clock.tick(tickValue)*</h3><p>Pair of clock.tick/clock.tickAsync executes all scheduled jobs, then synchronously execute all tasks whose execution time is in the time period [now, now + tickValue] and advances the clock’s internal time by tickValue. On the exit, if additional jobs are added they will be synchronously executed too (we should use clock.tickAsync if we need to “roll” the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop">event loop</a> before the execution). Once, the method is done, we are sure that there is no more pending jobs nor timers whose execution time is before now + tickValue.</p><h3>clock.runToLast*/clock.runAll*</h3><p>Let’s say a few asynchronous tasks are add to execution queue such that the last timer is scheduled for time tLast. If a method from a group clock.runToLast/clock.runToLastAsync and clock.runAll/clock.runAllAsync is called, all current tasks will be executed. During the execution, new tasks can be spawned. If their execution time t &lt;= tLast they will be executed too.<br>If the execution time is t &gt; tLast the method clock.runToLast* will ignore them. The method clock.runAll* will extend the execution time window as long as there is no new tasks in the queue:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*apmQYJOazMEMl9Xiy1tPvg.png" /><figcaption>Tasks T3 and T4 haven’t yet been created at the moment when the “time dilation“ is required (YOU ARE HERE)</figcaption></figure><p>The job execution is the same as for clock.next* method: we are sure that job queue will be empty after the clock.next* method is finished; the current time is updated to execution time of the last recent executed task.</p><h3>Configuration parameters</h3><p>Let’s check a few configuration parameters used during the creation of clock. If shouldAdvanceTime value is true it will be generated an internal timer that will advice time automatically by period given by advanceTimeDelta (check [<a href="https://github.com/sinonjs/fake-timers/pull/189">1</a>] and <a href="https://github.com/sinonjs/fake-timers/pull/102">[2</a>]). An example how can we use this feature:</p><pre>test(&#39;shouldAdvanceTime&#39;, (done) =&gt; {<br>        const clock = install({ shouldAdvanceTime: true });<br><br>        const time = Date.now();<br><br>        setTimeout(function () {<br>            expect(Date.now() - time).toBe(100);<br><br>            done();<br>        }, 100);<br>    })</pre><p>Again, we need done callback or assertion in setTimeout handler will be ignored. In the given test we didn’t need to advance timer manually.</p><p>We can explicitly specify which of methods and objects from the global space should be replaced by the fake version. The param toFake accepts an array of the object/method names from the following list: setTimeout, clearTimeout, setImmediate, clearImmediate, setInterval, clearInterval, requestAnimationFrame, cancelAnimationFrame, requestIdleCallback, cancelIdleCallback, Date, hrtime and performance. If the parameter is not specified, the corresponding fake variant is used for all methods and objects.</p><p>For example, we can keep original <a href="https://nodejs.org/api/process.html#processhrtimebigint">hrtime</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/API/Performance_API/Using_the_Performance_API">performance</a> object if we need to measure the actual time of execution of our code.</p><p>In some extreme cases it my happen that a large number of asynchronous handlers are scheduled for the execution:</p><pre>test(&#39;loopLimit&#39;, () =&gt; {<br>    const clock = install();<br><br>    let sum = 0;<br><br>    for (let i = 0; i &lt; 10000; ++i) {<br>        setTimeout(() =&gt; {<br>            sum += 1;<br>        });<br>    }<br><br>    clock.runAll();<br><br>    expect(sum).toBe(10000);<br>});</pre><p>The test fails:</p><pre>Aborting after running 1000 timers, assuming an infinite loop!<br>      10 |     }<br>      11 |<br>    &gt; 12 |     clock.runAll();</pre><p>The Fake timers library limits the maximal number of active timers to value specified by loopLimit parameter (default is 1000). We can specify the loopLimit parameter in order to fix the test:</p><pre>// ...<br>const clock = install({ loopLimit: 10001 });<br>// ...</pre><p>We are just halfway to our goal to deep dive to the Jest’s fake timers. This will be the theme of the next article.</p><p>I would like to thanks to my dear friends and colleagues <a href="https://www.linkedin.com/in/aliaksei-dudarau-55940549/">Aliaksei Dudarau</a> and <a href="https://www.linkedin.com/in/nagavendra-bandaru-6217b6110/">Nagavendra Bandaru</a> who reviewed draft versions of this document and provided useful suggestions in order to better shape this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2e879ae6ec2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>