<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">"use strict";(self.webpackChunkreact_testing_library_docs=self.webpackChunkreact_testing_library_docs||[]).push([[2350],{3905:(e,t,n)=&gt;{n.d(t,{Zo:()=&gt;c,kt:()=&gt;f});var r=n(7294);function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&amp;&amp;(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function s(e){for(var t=1;t&lt;arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?a(Object(n),!0).forEach((function(t){i(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):a(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function o(e,t){if(null==e)return{};var n,r,i=function(e,t){if(null==e)return{};var n,r,i={},a=Object.keys(e);for(r=0;r&lt;a.length;r++)n=a[r],t.indexOf(n)&gt;=0||(i[n]=e[n]);return i}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r&lt;a.length;r++)n=a[r],t.indexOf(n)&gt;=0||Object.prototype.propertyIsEnumerable.call(e,n)&amp;&amp;(i[n]=e[n])}return i}var l=r.createContext({}),u=function(e){var t=r.useContext(l),n=t;return e&amp;&amp;(n="function"==typeof e?e(t):s(s({},t),e)),n},c=function(e){var t=u(e.components);return r.createElement(l.Provider,{value:t},e.children)},p="mdxType",m={inlineCode:"code",wrapper:function(e){var t=e.children;return r.createElement(r.Fragment,{},t)}},d=r.forwardRef((function(e,t){var n=e.components,i=e.mdxType,a=e.originalType,l=e.parentName,c=o(e,["components","mdxType","originalType","parentName"]),p=u(n),d=i,f=p["".concat(l,".").concat(d)]||p[d]||m[d]||a;return n?r.createElement(f,s(s({ref:t},c),{},{components:n})):r.createElement(f,s({ref:t},c))}));function f(e,t){var n=arguments,i=t&amp;&amp;t.mdxType;if("string"==typeof e||i){var a=n.length,s=new Array(a);s[0]=d;var o={};for(var l in t)hasOwnProperty.call(t,l)&amp;&amp;(o[l]=t[l]);o.originalType=e,o[p]="string"==typeof e?e:i,s[1]=o;for(var u=2;u&lt;a;u++)s[u]=n[u];return r.createElement.apply(null,s)}return r.createElement.apply(null,n)}d.displayName="MDXCreateElement"},154:(e,t,n)=&gt;{n.r(t),n.d(t,{assets:()=&gt;c,contentTitle:()=&gt;l,default:()=&gt;f,frontMatter:()=&gt;o,metadata:()=&gt;u,toc:()=&gt;p});var r=n(7462),i=n(3366),a=(n(7294),n(3905)),s=["components"],o={id:"using-fake-timers",title:"Using Fake Timers",sidebar_label:"Using Fake Timers"},l=void 0,u={unversionedId:"using-fake-timers",id:"using-fake-timers",title:"Using Fake Timers",description:"In some cases, when your code uses timers (setTimeout, setInterval,",source:"@site/docs/guides-using-fake-timers.mdx",sourceDirName:".",slug:"/using-fake-timers",permalink:"/docs/using-fake-timers",draft:!1,editUrl:"https://github.com/testing-library/testing-library-docs/edit/main/docs/guides-using-fake-timers.mdx",tags:[],version:"current",lastUpdatedBy:"Domantas Petrauskas",lastUpdatedAt:1715769819,formattedLastUpdatedAt:"May 15, 2024",frontMatter:{id:"using-fake-timers",title:"Using Fake Timers",sidebar_label:"Using Fake Timers"},sidebar:"docs",previous:{title:"Considerations for fireEvent",permalink:"/docs/guide-events"},next:{title:"Accessibility",permalink:"/docs/dom-testing-library/api-accessibility"}},c={},p=[],m={toc:p},d="wrapper";function f(e){var t=e.components,n=(0,i.Z)(e,s);return(0,a.kt)(d,(0,r.Z)({},m,n,{components:t,mdxType:"MDXLayout"}),(0,a.kt)("p",null,"In some cases, when your code uses timers (",(0,a.kt)("inlineCode",{parentName:"p"},"setTimeout"),", ",(0,a.kt)("inlineCode",{parentName:"p"},"setInterval"),",\n",(0,a.kt)("inlineCode",{parentName:"p"},"clearTimeout"),", ",(0,a.kt)("inlineCode",{parentName:"p"},"clearInterval"),"), your tests may become unpredictable, slow and\nflaky."),(0,a.kt)("p",null,"To solve these problems, or if you need to rely on specific timestamps in your\ncode, most testing frameworks offer the option to replace the real timers in\nyour tests with fake ones. This has a side effect - when using fake timers in\nyour tests, ",(0,a.kt)("em",{parentName:"p"},"all")," of the code inside your test uses fake timers."),(0,a.kt)("p",null,"The common pattern to setup fake timers is usually within the ",(0,a.kt)("inlineCode",{parentName:"p"},"beforeEach"),", for\nexample:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-js"},"// Fake timers using Jest\nbeforeEach(() =&gt; {\n  jest.useFakeTimers()\n})\n")),(0,a.kt)("p",null,"Since fake timers are mocking native timer functions, it is necessary to restore\nthe timers after your test runs, just like regular mocks. This prevents fake\ntimers leaking into other test cases and cleanup functions, where real timers\nare expected."),(0,a.kt)("p",null,"For that you usually call ",(0,a.kt)("inlineCode",{parentName:"p"},"useRealTimers")," in ",(0,a.kt)("inlineCode",{parentName:"p"},"afterEach"),"."),(0,a.kt)("p",null,"It's important to also call ",(0,a.kt)("inlineCode",{parentName:"p"},"runOnlyPendingTimers")," before switching to real\ntimers. This will ensure you flush all the pending timers before you switch to\nreal timers. If you don't progress the timers and just switch to real timers,\nthe scheduled tasks won't get executed and you'll get an unexpected behavior.\nThis is mostly important for 3rd parties that schedule tasks without you being\naware of it."),(0,a.kt)("p",null,"Here's an example of doing that using jest:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-js"},"// Running all pending timers and switching to real timers using Jest\nafterEach(() =&gt; {\n  jest.runOnlyPendingTimers()\n  jest.useRealTimers()\n})\n")),(0,a.kt)("admonition",{type:"note"},(0,a.kt)("p",{parentName:"admonition"},"Combining fake timers with ",(0,a.kt)("inlineCode",{parentName:"p"},"user-event")," may cause test timeouts. Refer to\n",(0,a.kt)("a",{parentName:"p",href:"/docs/user-event/options#advancetimers"},(0,a.kt)("inlineCode",{parentName:"a"},"advanceTimers"))," option to prevent this\nissue.")))}f.isMDXComponent=!0}}]);</pre></body></html>