1"use strict";(globalThis.webpackChunkjest_website||=[]).push([[1124],{23381(e,n,t){t.r(n),t.d(n,{assets:()=>m,contentTitle:()=>h,default:()=>p,frontMatter:()=>d,metadata:()=>s,toc:()=>u});const s=JSON.parse('{"id":"jest-object","title":"The Jest Object","description":"The jest object is automatically in scope within every test file. The methods in the jest object help create mocks and let you control Jest\'s overall behavior. It can also be imported explicitly by via import from \'@jest/globals\'.","source":"@site/versioned_docs/version-30.0/JestObjectAPI.md","sourceDirName":".","slug":"/jest-object","permalink":"/docs/30.0/jest-object","draft":false,"unlisted":false,"editUrl":"https://github.com/jestjs/jest/edit/main/website/versioned_docs/version-30.0/JestObjectAPI.md","tags":[],"version":"30.0","lastUpdatedBy":"Svyatoslav Zaytsev","lastUpdatedAt":1749521831000,"frontMatter":{"id":"jest-object","title":"The Jest Object"},"sidebar":"api","previous":{"title":"Mock Functions","permalink":"/docs/30.0/mock-function-api"},"next":{"title":"Configuring Jest","permalink":"/docs/30.0/configuration"}}');var o=t(62540),i=t(43023),l=t(49479),c=t(22491),r=t(74323),a=t(11038);const d={id:"jest-object",title:"The Jest Object"},h=void 0,m={},u=[...r.RM,{value:"Methods",id:"methods",level:2},{value:"Mock Modules",id:"mock-modules",level:2},{value:"<code>jest.disableAutomock()</code>",id:"jestdisableautomock",level:3},{value:"<code>jest.enableAutomock()</code>",id:"jestenableautomock",level:3},{value:"<code>jest.createMockFromModule(moduleName)</code>",id:"jestcreatemockfrommodulemodulename",level:3},{value:"<code>Function</code>",id:"function",level:4},{value:"<code>Class</code>",id:"class",level:4},{value:"<code>Object</code>",id:"object",level:4},{value:"<code>Array</code>",id:"array",level:4},{value:"<code>Primitives</code>",id:"primitives",level:4},{value:"<code>jest.mock(moduleName, factory, options)</code>",id:"jestmockmodulename-factory-options",level:3},{value:"<code>jest.Mocked<Source></code>",id:"jestmockedsource",level:3},{value:"<code>jest.mocked(source, options?)</code>",id:"jestmockedsource-options",level:3},{value:"<code>jest.unmock(moduleName)</code>",id:"jestunmockmodulename",level:3},{value:"<code>jest.deepUnmock(moduleName)</code>",id:"jestdeepunmockmodulename",level:3},{value:"<code>jest.doMock(moduleName, factory, options)</code>",id:"jestdomockmodulename-factory-options",level:3},{value:"<code>jest.dontMock(moduleName)</code>",id:"jestdontmockmodulename",level:3},{value:"<code>jest.setMock(moduleName, moduleExports)</code>",id:"jestsetmockmodulename-moduleexports",level:3},{value:"<code>jest.requireActual(moduleName)</code>",id:"jestrequireactualmodulename",level:3},{value:"<code>jest.requireMock(moduleName)</code>",id:"jestrequiremockmodulename",level:3},{value:"<code>jest.onGenerateMock(cb)</code>",id:"jestongeneratemockcb",level:3},{value:"<code>jest.resetModules()</code>",id:"jestresetmodules",level:3},{value:"<code>jest.isolateModules(fn)</code>",id:"jestisolatemodulesfn",level:3},{value:"<code>jest.isolateModulesAsync(fn)</code>",id:"jestisolatemodulesasyncfn",level:3},{value:"Mock Functions",id:"mock-functions",level:2},{value:"<code>jest.fn(implementation?)</code>",id:"jestfnimplementation",level:3},{value:"<code>jest.isMockFunction(fn)</code>",id:"jestismockfunctionfn",level:3},{value:"<code>jest.replaceProperty(object, propertyKey, value)</code>",id:"jestreplacepropertyobject-propertykey-value",level:3},{value:"<code>jest.spyOn(object, methodName)</code>",id:"jestspyonobject-methodname",level:3},{value:"Spied methods and the <code>using</code> keyword",id:"spied-methods-and-the-using-keyword",level:4},{value:"<code>jest.spyOn(object, methodName, accessType?)</code>",id:"jestspyonobject-methodname-accesstype",level:3},{value:"<code>jest.Replaced<Source></code>",id:"jestreplacedsource",level:3},{value:"<code>jest.Spied<Source></code>",id:"jestspiedsource",level:3},{value:"<code>jest.clearAllMocks()</code>",id:"jestclearallmocks",level:3},{value:"<code>jest.resetAllMocks()</code>",id:"jestresetallmocks",level:3},{value:"<code>jest.restoreAllMocks()</code>
1",id:"jestrestoreallmocks",level:3},{value:"Fake Timers",id:"fake-timers",level:2},{value:"<code>jest.useFakeTimers(fakeTimersConfig?)</code>",id:"jestusefaketimersfaketimersconfig",level:3},{value:"<code>jest.useRealTimers()</code>",id:"jestuserealtimers",level:3},{value:"<code>jest.runAllTicks()</code>",id:"jestrunallticks",level:3},{value:"<code>jest.runAllTimers()</code>",id:"jestrunalltimers",level:3},{value:"<code>jest.runAllTimersAsync()</code>",id:"jestrunalltimersasync",level:3},{value:"<code>jest.runAllImmediates()</code>",id:"jestrunallimmediates",level:3},{value:"<code>jest.advanceTimersByTime(msToRun)</code>",id:"jestadvancetimersbytimemstorun",level:3},{value:"<code>jest.advanceTimersByTimeAsync(msToRun)</code>",id:"jestadvancetimersbytimeasyncmstorun",level:3},{value:"<code>jest.runOnlyPendingTimers()</code>",id:"jestrunonlypendingtimers",level:3},{value:"<code>jest.runOnlyPendingTimersAsync()</code>",id:"jestrunonlypendingtimersasync",level:3},{value:"<code>jest.advanceTimersToNextTimer(steps)</code>",id:"jestadvancetimerstonexttimersteps",level:3},{value:"<code>jest.advanceTimersToNextTimerAsync(steps)</code>",id:"jestadvancetimerstonexttimerasyncsteps",level:3},{value:"<code>jest.advanceTimersToNextFrame()</code>",id:"jestadvancetimerstonextframe",level:3},{value:"<code>jest.clearAllTimers()</code>",id:"jestclearalltimers",level:3},{value:"<code>jest.getTimerCount()</code>",id:"jestgettimercount",level:3},{value:"<code>jest.now()</code>",id:"jestnow",level:3},{value:"<code>jest.setSystemTime(now?: number | Date)</code>",id:"jestsetsystemtimenow-number--date",level:3},{value:"<code>jest.getRealSystemTime()</code>",id:"jestgetrealsystemtime",level:3},{value:"Misc",id:"misc",level:2},{value:"<code>jest.getSeed()</code>",id:"jestgetseed",level:3},{value:"<code>jest.isEnvironmentTornDown()</code>",id:"jestisenvironmenttorndown",level:3},{value:"<code>jest.retryTimes(numRetries, options?)</code>",id:"jestretrytimesnumretries-options",level:3},{value:"<code>jest.setTimeout(timeout)</code>",id:"jestsettimeouttimeout",level:3}];function j(e){const n={a:"a",admonition:"admonition",code:"code",em:"em",h2:"h2",h3:"h3",h4:"h4",hr:"hr",li:"li",ol:"ol",p:"p",pre:"pre",strong:"strong",ul:"ul",...(0,i.R)(),...e.components};return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)(n.p,{children:["The ",(0,o.jsx)(n.code,{children:"jest"})," object is automatically in scope within every test file. The methods in the ",(0,o.jsx)(n.code,{children:"jest"})," object help create mocks and let you control Jest's overall behavior. It can also be imported explicitly by via ",(0,o.jsx)(n.code,{children:"import {jest} from '@jest/globals'"}),"."]}),"\n","\n",(0,o.jsx)(r.Ay,{}),"\n",(0,o.jsx)(n.h2,{id:"methods",children:"Methods"}),"\n","\n",(0,o.jsx)(a.A,{toc:u.slice(1)}),"\n",(0,o.jsx)(n.hr,{}),"\n",(0,o.jsx)(n.h2,{id:"mock-modules",children:"Mock Modules"}),"\n",(0,o.jsx)(n.h3,{id:"jestdisableautomock",children:(0,o.jsx)(n.code,{children:"jest.disableAutomock()"})}),"\n",(0,o.jsx)(n.p,{children:"Disables automatic mocking in the module loader."}),"\n",(0,o.jsxs)(n.admonition,{type:"info",children:[(0,o.jsxs)(n.p,{children:["Automatic mocking should be enabled via ",(0,o.jsx)(n.a,{href:"/docs/30.0/configuration#automock-boolean",children:(0,o.jsx)(n.code,{children:"automock"})})," configuration option for this method to have any effect. Also see documentation of the configuration option for more details."]}),(0,o.jsxs)(l.A,{groupId:"code-examples",children:[(0,o.jsx)(c.A,{value:"js",label:"JavaScript",children:(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",metastring:"tab",children:"/** @type {import('jest').Config} */\nconst config = {\n automock: true,\n};\n\nmodule.exports = config;\n"})})}),(0,o.jsx)(c.A,{value:"ts",label:"TypeScript",children:(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-ts",metastring:"tab",children:"import type {Config} from 'jest';\n\nconst config: Config = {\n automock: true,\n};\n\nexport default config;\n"})})})]})]}),"\n",(0,o.jsxs)(n.p,{children:["After ",(0,o.jsx)(n.code,{children:"disableAutomock()"})," is called, all ",(0,o.jsx)(n.code,{children:"require()"}),"s will return the real versions of each module (rather than a mocked version)."]}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",metastring:'title="utils.js"',children:"export default {\n authorize: () => {\n return 'token';\n },\n};\n"})}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",metastring:'title="__tests__/disableAutomocking.js"',children:"import utils from '../utils';\n\njest.disableAutomock();\n\ntest('original implementation', () => {\n // now we have the original implementation,\n // even if we set the automocking in a jest configuration\n expect(utils.authorize()).toBe('token');\n});\n"})}),"\n",(0,o.jsx)(n.p,{children:"This is usually useful when you have a scenario where the number of dependencies you want to mock is far less than the number of dependencies that you don't. For example, if you're writing a test for a module that uses a large number of dependencies that can be reasonably classified as \"implementation details\" of the module, then you likely do not want to mock them."}),"\n",(0,o.jsxs)(n.p,{children:['Examples of dependencies that might be considered "implementation details" are things ranging from language built-ins (e.g. ',(0,o.jsx)(n.code,{children:"Array.prototype"})," methods) to highly common utility methods (e.g. ",(0,o.jsx)(n.code,{children:"underscore"}),", ",(0,o.jsx)(n.code,{children:"lodash"}),", array utilities, etc) and entire libraries like ",(0,o.jsx)(n.code,{children:"React.js"}),"."]}),"\n",(0,o.jsxs)(n.p,{children:["Returns the ",(0,o.jsx)(n.code,{children:"jest"})," object for chaining."]}),"\n",(0,o.jsx)(n.admonition,{type:"tip",children:(0,o.jsxs)(n.p,{children:["When using ",(0,o.jsx)(n.code,{children:"babel-jest"}),", calls to ",(0,o.jsx)(n.code,{children:"disableAutomock()"})," will automatically be hoisted to the top of the code block. Use ",(0,o.jsx)(n.code,{children:"autoMockOff()"})," if you want to explicitly avoid this behavior."]})}),"\n",(0,o.jsx)(n.h3,{id:"jestenableautomock",children:(0,o.jsx)(n.code,{children:"jest.enableAutomock()"})}),"\n",(0,o.jsx)(n.p,{children:"Enables automatic mocking in the module loader."}),"\n",(0,o.jsx)(n.admonition,{type:"info",children:(0,o.jsxs)(n.p,{children:["For more details on automatic mocking see documentation of ",(0,o.jsx)(n.a,{href:"/docs/30.0/configuration#automock-boolean",children:(0,o.jsx)(n.code,{children:"automock"})})," configuration option."]})}),"\n",(0,o.jsx)(n.p,{children:"Example:"}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",metastring:'title="utils.js"',children:"export default {\n authorize: () => {\n return 'token';\n },\n isAuthorized: secret => secret === 'wizard',\n};\n"})}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",metastring:'title="__tests__/enableAutomocking.js"',children:"jest.enableAutomock();\n\nimport utils from '../utils';\n\ntest('original implementation', () => {\n // now we have the mocked implementation,\n expect(utils.authorize._isMockFunction).toBeTruthy();\n expect(utils.isAuthorized._isMockFunction).toBeTruthy();\n});\n"})}),"\n",(0,o.jsxs)(n.p,{children:["Returns the ",(0,o.jsx)(n.code,{children:"jest"})," object for chaining."]}),"\n",(0,o.jsx)(n.admonition,{type:"tip",children:(0,o.jsxs)(n.p,{children:["When using ",(0,o.jsx)(n.code,{children:"babel-jest"}),", calls to ",(0,o.jsx)(n.code,{children:"enableAutomock"})," will automatically be hoisted to the top of the code block. Use ",(0,o.jsx)(n.code,{children:"autoMockOn"})," if you want to explicitly avoid this behavior."]})}),"\n",(0,o.jsx)(n.h3,{id:"jestcreatemockfrommodulemodulename",children:(0,o.jsx)(n.code,{children:"jest.createMockFromModule(moduleName)"})}),"\n",(0,o.jsx)(n.p,{children:"Given the name of a module, use the automatic mocking system to generate a mocked version of the module for you."}),"\n",(0,o.jsxs)(n.p,{children:["This is useful when you want to create a ",(0,o.jsx)(n.a,{href:"/docs/30.0/manual-mocks",children:"manual mock"})," that extends the automatic mock's behavior:"]}),"\n",(0,o.jsxs)(l.A,{groupId:"code-examples",children:[(0,o.jsxs)(c.A,{value:"js",label:"JavaScript",children:[(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",metastring:'tab={"span":2} title="utils.js"',children:"module.exports = {\n authorize: () => {\n return 'token';\n },\n isAuthorized: secret => secret === 'wizard',\n};\n"})}),(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",metastring:'title="__tests__/createMockFromModule.test.js"',children:"const utils = jest.createMockFromModule('../utils');\n\nutils.isAuthorized = jest.fn(secret => secret === 'not wizard');\n\ntest('implementation created by jest.createMockFromModule', () => {\n expect(jest.isMockFunction(utils.authorize)).toBe(true);\n expect(utils.isAuthorized('not wizard')).toBe(true);\n});\n"})})]}),(0,o.jsxs)(c.A,{value:"ts",label:"TypeScript",children:[(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-ts",metastring:'tab={"span":2} title="utils.ts"',children:"export const utils = {\n authorize: () => {\n return 'token';\n },\n isAuthorized: (secret: string) => secret === 'wizard',\n};\n"})}),(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-ts",metastring:'title="__tests__/createMockFromModule.test.ts"',children:"const {utils} =\n jest.createMockFromModule<typeof import('../utils')>
1('../utils');\n\nutils.isAuthorized = jest.fn((secret: string) => secret === 'not wizard');\n\ntest('implementation created by jest.createMockFromModule', () => {\n expect(jest.isMockFunction(utils.authorize)).toBe(true);\n expect(utils.isAuthorized('not wizard')).toBe(true);\n});\n"})})]})]}),"\n",(0,o.jsxs)(n.p,{children:["This is how ",(0,o.jsx)(n.code,{children:"createMockFromModule"})," will mock the following data types:"]}),"\n",(0,o.jsx)(n.h4,{id:"function",children:(0,o.jsx)(n.code,{children:"Function"})}),"\n",(0,o.jsxs)(n.p,{children:["Creates a new ",(0,o.jsx)(n.a,{href:"/docs/30.0/mock-function-api",children:"mock function"}),". The new function has no formal parameters and when called will return ",(0,o.jsx)(n.code,{children:"undefined"}),". This functionality also applies to ",(0,o.jsx)(n.code,{children:"async"})," functions."]}),"\n",(0,o.jsx)(n.h4,{id:"class",children:(0,o.jsx)(n.code,{children:"Class"})}),"\n",(0,o.jsx)(n.p,{children:"Creates a new class. The interface of the original class is maintained, all of the class member functions and properties will be mocked."}),"\n",(0,o.jsx)(n.h4,{id:"object",children:(0,o.jsx)(n.code,{children:"Object"})}),"\n",(0,o.jsx)(n.p,{children:"Creates a new deeply cloned object. The object keys are maintained and their values are mocked."}),"\n",(0,o.jsx)(n.h4,{id:"array",children:(0,o.jsx)(n.code,{children:"Array"})}),"\n",(0,o.jsx)(n.p,{children:"Creates a new empty array, ignoring the original."}),"\n",(0,o.jsx)(n.h4,{id:"primitives",children:(0,o.jsx)(n.code,{children:"Primitives"})}),"\n",(0,o.jsx)(n.p,{children:"Creates a new property with the same primitive value as the original property."}),"\n",(0,o.jsx)(n.p,{children:"Example:"}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",metastring:'title="example.js"',children:"module.exports = {\n function: function square(a, b) {\n return a * b;\n },\n asyncFunction: async function asyncSquare(a, b) {\n const result = (await a) * b;\n return result;\n },\n class: new (class Bar {\n constructor() {\n this.array = [1, 2, 3];\n }\n foo() {}\n })(),\n object: {\n baz: 'foo',\n bar: {\n fiz: 1,\n buzz: [1, 2, 3],\n },\n },\n array: [1, 2, 3],\n number: 123,\n string: 'baz',\n boolean: true,\n symbol: Symbol.for('a.b.c'),\n};\n"})}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",metastring:'title="__tests__/example.test.js"',children:"const example = jest.createMockFromModule('../example');\n\ntest('should run example code', () => {\n // creates a new mocked function with no formal arguments.\n expect(example.function.name).toBe('square');\n expect(example.function).toHaveLength(0);\n\n // async functions get the same treatment as standard synchronous functions.\n expect(example.asyncFunction.name).toBe('asyncSquare');\n expect(example.asyncFunction).toHaveLength(0);\n\n // creates a new class with the same interface, member functions and properties are mocked.\n expect(example.class.constructor.name).toBe('Bar');\n expect(example.class.foo.name).toBe('foo');\n expect(example.class.array).toHaveLength(0);\n\n // creates a deeply cloned version of the original object.\n expect(example.object).toEqual({\n baz: 'foo',\n bar: {\n fiz: 1,\n buzz: [],\n },\n });\n\n // creates a new empty array, ignoring the original array.\n expect(example.array).toHaveLength(0);\n\n // creates a new property with the same primitive value as the original property.\n expect(example.number).toBe(123);\n expect(example.string).toBe('baz');\n expect(example.boolean).toBe(true);\n expect(example.symbol).toEqual(Symbol.for('a.b.c'));\n});\n"})}),"\n",(0,o.jsx)(n.h3,{id:"jestmockmodulename-factory-options",children:(0,o.jsx)(n.code,{children:"jest.mock(moduleName, factory, options)"})}),"\n",(0,o.jsxs)(n.p,{children:["Mocks a module with an auto-mocked version when it is being required. ",(0,o.jsx)(n.code,{children:"factory"})," and ",(0,o.jsx)(n.code,{children:"options"})," are optional. For example:"]}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",metastring:'title="banana.js"',children:"module.exports = () => 'banana';\n"})}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",metastring:'title="__tests__/test.js"',children:"jest.mock('../banana');\n\nconst banana = require('../banana'); // banana will be explicitly mocked.\n\nbanana(); // will return 'undefined' because the function is auto-mocked.\n"})}),"\n",(0,o.jsx)(n.p,{children:"The second argument can be used to specify an explicit module factory that is being run instead of using Jest's automocking feature:"}),"\n",(0,o.jsxs)(l.A,{groupId:"code-examples",children:[(0,o.jsx)(c.A,{value:"js",label:"JavaScript",children:(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",metastring:"tab",children:"jest.mock('../moduleName', () => {\n return jest.fn(() => 42);\n});\n\n// This runs the function specified as second argument to `jest.mock`.\nconst moduleName = require('../moduleName');\nmoduleName(); // Will return '42';\n"})})}),(0,o.jsx)(c.A,{value:"ts",label:"TypeScript",children:(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-ts",metastring:"tab",children:"// The optional type argument provides typings for the module factory\njest.mock<typeof import('../moduleName')>('../moduleName', () => {\n return jest.fn(() => 42);\n});\n\n// This runs the function specified as second argument to `jest.mock`.\nconst moduleName = require('../moduleName');\nmoduleName(); // Will return '42';\n"})})})]}),"\n",(0,o.jsxs)(n.p,{children:["When using the ",(0,o.jsx)(n.code,{children:"factory"})," parameter for an ES6 module with a default export, the ",(0,o.jsx)(n.code,{children:"__esModule: true"})," property needs to be specified. This property is normally generated by Babel / TypeScript, but here it needs to be set manually. When importing a default export, it's an instruction to import the property named ",(0,o.jsx)(n.code,{children:"default"})," from the export object:"]}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",children:"import moduleName, {foo} from '../moduleName';\n\njest.mock('../moduleName', () => {\n return {\n __esModule: true,\n default: jest.fn(() => 42),\n foo: jest.fn(() => 43),\n };\n});\n\nmoduleName(); // Will return 42\nfoo(); // Will return 43\n"})}),"\n",(0,o.jsx)(n.p,{children:"The third argument can be used to create virtual mocks \u2013 mocks of modules that don't exist anywhere in the system:"}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",children:"jest.mock(\n '../moduleName',\n () => {\n /*\n * Custom implementation of a module that doesn't exist in JS,\n * like a generated module or a native module in react-native.\n */\n },\n {virtual: true},\n);\n"})}),"\n",(0,o.jsx)(n.admonition,{type:"caution",children:(0,o.jsxs)(n.p,{children:["Importing a module in a setup file (as specified by ",(0,o.jsx)(n.a,{href:"/docs/30.0/configuration#setupfilesafterenv-array",children:(0,o.jsx)(n.code,{children:"setupFilesAfterEnv"})}),") will prevent mocking for the module in question, as well as all the modules that it imports."]})}),"\n",(0,o.jsxs)(n.p,{children:["Modules that are mocked with ",(0,o.jsx)(n.code,{children:"jest.mock"})," are mocked only for the file that calls ",(0,o.jsx)(n.code,{children:"jest.mock"}),". Another file that imports the module will get the original implementation even if it runs after the test file that mocks the module."]}),"\n",(0,o.jsxs)(n.p,{children:["Returns the ",(0,o.jsx)(n.code,{children:"jest"})," object for chaining."]}),"\n",(0,o.jsx)(n.admonition,{type:"tip",children:(0,o.jsxs)(n.p,{children:["Writing tests in TypeScript? Use the ",(0,o.jsx)(n.a,{href:"/docs/30.0/mock-function-api#jestmockedsource",children:(0,o.jsx)(n.code,{children:"jest.Mocked"})})," utility type or the ",(0,o.jsx)(n.a,{href:"/docs/30.0/mock-function-api#jestmockedsource-options",children:(0,o.jsx)(n.code,{children:"jest.mocked()"})})," helper method to have your mocked modules typed."]})}),"\n",(0,o.jsx)(n.h3,{id:"jestmockedsource",children:(0,o.jsx)(n.code,{children:"jest.Mocked<Source>"})}),"\n",(0,o.jsxs)(n.p,{children:["See ",(0,o.jsx)(n.a,{href:"/docs/30.0/mock-function-api#jestmockedsource",children:"TypeScript Usage"})," chapter of Mock Functions page for documentation."]}),"\n",(0,o.jsx)(n.h3,{id:"jestmockedsource-options",children:(0,o.jsx)(n.code,{children:"jest.mocked(source, options?)"})}),"\n",(0,o.jsxs)(n.p,{children:["See ",(0,o.jsx)(n.a,{href:"/docs/30.0/mock-function-api#jestmockedsource-options",children:"TypeScript Usage"})," chapter of Mock Functions page for documentation."]}),"\n",(0,o.jsx)(n.h3,{id:"jestunmockmodulename",children:(0,o.jsx)(n.code,{children:"jest.unmock(moduleName)"})}),"\n",(0,o.jsxs)(n.p,{children:["Indicates that the module system should never return a mocked version of the specified module from ",(0,o.jsx)(n.code,{children:"require()"})," (e.g. that it should always return the real module)."]}),"\n",(0,o.jsx)(n.p,{children:"The most common use of this API is for specifying the module a given test intends to be testing (and thus doesn't want automatically mocked)."}),"\n",(0,o.jsxs)(n.p,{children:["Returns the ",(0,o.jsx)(n.code,{children:"jest"})," object for chaining."]}),"\n",(0,o.jsx)(n.h3,{id:"jestdeepunmockmodulename",children:(0,o.jsx)(n.code,{children:"jest.deepUnmock(moduleName)"})}),"\n",(0,o.jsx)(n.p,{children:"Indicates that the module system should never return a mocked version of the specified module and its dependencies."}),"\n",(0,o.jsxs)(n.p,{children:["Returns the ",(0,o.jsx)(n.code,{children:"jest"})," object for chaining."]}),"\n",(0,o.jsx)(n.h3,{id:"jestdomockmodulename-factory-options",children:(0,o.jsx)(n.code,{children:"jest.doMock(moduleName, factory, options)"})}),"\n",(0,o.jsxs)(n.p,{children:["When using ",(0,o.jsx)(n.code,{children:"babel-jest"}),", calls to ",(0,o.jsx)(n.code,{children:"mock"})," will automatically be hoisted to the top of the code block. Use this method if you want to explicitly avoid this behavior."]}),"\n",(0,o.jsx)(n.p,{children:"One example when this is useful is when you want to mock a module differently within the same file:"}),"\n",(0,o.jsxs)(l.A,{groupId:"code-examples",children:[(0,o.jsx)(c.A,{value:"js",label:"JavaScript",children:(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",metastring:"tab",children:"beforeEach(() =>
1 {\n jest.resetModules();\n});\n\ntest('moduleName 1', () => {\n jest.doMock('../moduleName', () => {\n return jest.fn(() => 1);\n });\n const moduleName = require('../moduleName');\n expect(moduleName()).toBe(1);\n});\n\ntest('moduleName 2', () => {\n jest.doMock('../moduleName', () => {\n return jest.fn(() => 2);\n });\n const moduleName = require('../moduleName');\n expect(moduleName()).toBe(2);\n});\n"})})}),(0,o.jsx)(c.A,{value:"ts",label:"TypeScript",children:(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-ts",metastring:"tab",children:"beforeEach(() => {\n jest.resetModules();\n});\n\ntest('moduleName 1', () => {\n // The optional type argument provides typings for the module factory\n jest.doMock<typeof import('../moduleName')>('../moduleName', () => {\n return jest.fn(() => 1);\n });\n const moduleName = require('../moduleName');\n expect(moduleName()).toBe(1);\n});\n\ntest('moduleName 2', () => {\n jest.doMock<typeof import('../moduleName')>('../moduleName', () => {\n return jest.fn(() => 2);\n });\n const moduleName = require('../moduleName');\n expect(moduleName()).toBe(2);\n});\n"})})})]}),"\n",(0,o.jsxs)(n.p,{children:["Using ",(0,o.jsx)(n.code,{children:"jest.doMock()"})," with ES6 imports requires additional steps. Follow these if you don't want to use ",(0,o.jsx)(n.code,{children:"require"})," in your tests:"]}),"\n",(0,o.jsxs)(n.ul,{children:["\n",(0,o.jsxs)(n.li,{children:["We have to specify the ",(0,o.jsx)(n.code,{children:"__esModule: true"})," property (see the ",(0,o.jsx)(n.a,{href:"#jestmockmodulename-factory-options",children:(0,o.jsx)(n.code,{children:"jest.mock()"})})," API for more information)."]}),"\n",(0,o.jsxs)(n.li,{children:["Static ES6 module imports are hoisted to the top of the file, so instead we have to import them dynamically using ",(0,o.jsx)(n.code,{children:"import()"}),"."]}),"\n",(0,o.jsxs)(n.li,{children:["Finally, we need an environment which supports dynamic importing. Please see ",(0,o.jsx)(n.a,{href:"/docs/30.0/getting-started#using-babel",children:"Using Babel"})," for the initial setup. Then add the plugin ",(0,o.jsx)(n.a,{href:"https://www.npmjs.com/package/babel-plugin-dynamic-import-node",children:"babel-plugin-dynamic-import-node"}),", or an equivalent, to your Babel config to enable dynamic importing in Node."]}),"\n"]}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",children:"beforeEach(() => {\n jest.resetModules();\n});\n\ntest('moduleName 1', () => {\n jest.doMock('../moduleName', () => {\n return {\n __esModule: true,\n default: 'default1',\n foo: 'foo1',\n };\n });\n return import('../moduleName').then(moduleName => {\n expect(moduleName.default).toBe('default1');\n expect(moduleName.foo).toBe('foo1');\n });\n});\n\ntest('moduleName 2', () => {\n jest.doMock('../moduleName', () => {\n return {\n __esModule: true,\n default: 'default2',\n foo: 'foo2',\n };\n });\n return import('../moduleName').then(moduleName => {\n expect(moduleName.default).toBe('default2');\n expect(moduleName.foo).toBe('foo2');\n });\n});\n"})}),"\n",(0,o.jsxs)(n.p,{children:["Returns the ",(0,o.jsx)(n.code,{children:"jest"})," object for chaining."]}),"\n",(0,o.jsx)(n.h3,{id:"jestdontmockmodulename",children:(0,o.jsx)(n.code,{children:"jest.dontMock(moduleName)"})}),"\n",(0,o.jsxs)(n.p,{children:["When using ",(0,o.jsx)(n.code,{children:"babel-jest"}),", calls to ",(0,o.jsx)(n.code,{children:"unmock"})," will automatically be hoisted to the top of the code block. Use this method if you want to explicitly avoid this behavior."]}),"\n",(0,o.jsxs)(n.p,{children:["Returns the ",(0,o.jsx)(n.code,{children:"jest"})," object for chaining."]}),"\n",(0,o.jsx)(n.h3,{id:"jestsetmockmodulename-moduleexports",children:(0,o.jsx)(n.code,{children:"jest.setMock(moduleName, moduleExports)"})}),"\n",(0,o.jsx)(n.p,{children:"Explicitly supplies the mock object that the module system should return for the specified module."}),"\n",(0,o.jsxs)(n.p,{children:["On occasion, there are times where the automatically generated mock the module system would normally provide you isn't adequate enough for your testing needs. Normally under those circumstances you should write a ",(0,o.jsx)(n.a,{href:"/docs/30.0/manual-mocks",children:"manual mock"})," that is more adequate for the module in question. However, on extremely rare occasions, even a manual mock isn't suitable for your purposes and you need to build the mock yourself inside your test."]}),"\n",(0,o.jsx)(n.p,{children:"In these rare scenarios you can use this API to manually fill the slot in the module system's mock-module registry."}),"\n",(0,o.jsxs)(n.p,{children:["Returns the ",(0,o.jsx)(n.code,{children:"jest"})," object for chaining."]}),"\n",(0,o.jsx)(n.admonition,{type:"info",children:(0,o.jsxs)(n.p,{children:["It is recommended to use ",(0,o.jsx)(n.a,{href:"#jestmockmodulename-factory-options",children:(0,o.jsx)(n.code,{children:"jest.mock()"})})," instead. The ",(0,o.jsx)(n.code,{children:"jest.mock"})," API's second argument is a module factory instead of the expected exported module object."]})}),"\n",(0,o.jsx)(n.h3,{id:"jestrequireactualmodulename",children:(0,o.jsx)(n.code,{children:"jest.requireActual(moduleName)"})}),"\n",(0,o.jsx)(n.p,{children:"Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not."}),"\n",(0,o.jsxs)(l.A,{groupId:"code-examples",children:[(0,o.jsx)(c.A,{value:"js",label:"JavaScript",children:(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",metastring:"tab",children:"jest.mock('../myModule', () => {\n // Require the original module to not be mocked...\n const originalModule = jest.requireActual('../myModule');\n\n return {\n __esModule: true, // Use it when dealing with esModules\n ...originalModule,\n getRandom: jest.fn(() => 10),\n };\n});\n\nconst getRandom = require('../myModule').getRandom;\n\ngetRandom(); // Always returns 10\n"})})}),(0,o.jsx)(c.A,{value:"ts",label:"TypeScript",children:(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-ts",metastring:"tab",children:"jest.mock('../myModule', () => {\n // Require the original module to not be mocked...\n const originalModule =\n jest.requireActual<typeof import('../myModule')>('../myModule');\n\n return {\n __esModule: true, // Use it when dealing with esModules\n ...originalModule,\n getRandom: jest.fn(() => 10),\n };\n});\n\nconst getRandom = require('../myModule').getRandom;\n\ngetRandom(); // Always returns 10\n"})})})]}),"\n",(0,o.jsx)(n.h3,{id:"jestrequiremockmodulename",children:(0,o.jsx)(n.code,{children:"jest.requireMock(moduleName)"})}),"\n",(0,o.jsx)(n.p,{children:"Returns a mock module instead of the actual module, bypassing all checks on whether the module should be required normally or not."}),"\n",(0,o.jsx)(n.h3,{id:"jestongeneratemockcb",children:(0,o.jsx)(n.code,{children:"jest.onGenerateMock(cb)"})}),"\n",(0,o.jsx)(n.p,{children:"Registers a callback function that is invoked whenever Jest generates a mock for a module. This callback allows you to modify the mock before it is returned to the rest of your tests."}),"\n",(0,o.jsx)(n.p,{children:"Parameters for callback:"}),"\n",(0,o.jsxs)(n.ol,{children:["\n",(0,o.jsxs)(n.li,{children:[(0,o.jsx)(n.code,{children:"modulePath: string"})," - The absolute path to the module that is being mocked."]}),"\n",(0,o.jsxs)(n.li,{children:[(0,o.jsx)(n.code,{children:"moduleMock: T"})," - The mock object that Jest has generated for the module. This object can be modified or replaced before returning."]}),"\n"]}),"\n",(0,o.jsx)(n.p,{children:"Behaviour:"}),"\n",(0,o.jsxs)(n.ul,{children:["\n",(0,o.jsxs)(n.li,{children:["If multiple callbacks are registered via consecutive ",(0,o.jsx)(n.code,{children:"onGenerateMock"})," calls, they will be invoked ",(0,o.jsx)(n.strong,{children:"in the order they were added"}),"."]}),"\n",(0,o.jsxs)(n.li,{children:["Each callback receives the output of the previous callback as its ",(0,o.jsx)(n.code,{children:"moduleMock"}),". This makes it possible to apply multiple layers of transformations to the same mock."]}),"\n"]}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",children:"jest.onGenerateMock((modulePath, moduleMock) =>
1 {\n // Inspect the module name and decide how to transform the mock\n if (modulePath.includes('Database')) {\n // For demonstration, let's replace a method with our own custom mock\n moduleMock.connect = jest.fn().mockImplementation(() => {\n console.log('Connected to mock DB');\n });\n }\n\n // Return the (potentially modified) mock\n return moduleMock;\n});\n\n// Apply mock for module\njest.mock('./Database');\n\n// Later in your tests\nimport Database from './Database';\n// The `Database` mock now has any transformations applied by our callback\n"})}),"\n",(0,o.jsxs)(n.admonition,{type:"note",children:[(0,o.jsxs)(n.p,{children:["The ",(0,o.jsx)(n.code,{children:"onGenerateMock"})," callback is not called for manually created mocks, such as:"]}),(0,o.jsxs)(n.ul,{children:["\n",(0,o.jsxs)(n.li,{children:["Mocks defined in a ",(0,o.jsx)(n.code,{children:"__mocks__"})," folder"]}),"\n",(0,o.jsxs)(n.li,{children:["Explicit factories provided via ",(0,o.jsx)(n.code,{children:"jest.mock('moduleName', () => { ... })"})]}),"\n"]})]}),"\n",(0,o.jsx)(n.h3,{id:"jestresetmodules",children:(0,o.jsx)(n.code,{children:"jest.resetModules()"})}),"\n",(0,o.jsx)(n.p,{children:"Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests."}),"\n",(0,o.jsx)(n.p,{children:"Example:"}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",children:"const sum1 = require('../sum');\njest.resetModules();\nconst sum2 = require('../sum');\nsum1 === sum2;\n// > false (Both sum modules are separate \"instances\" of the sum module.)\n"})}),"\n",(0,o.jsx)(n.p,{children:"Example in a test:"}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",children:"beforeEach(() => {\n jest.resetModules();\n});\n\ntest('works', () => {\n const sum = require('../sum');\n});\n\ntest('works too', () => {\n const sum = require('../sum');\n // sum is a different copy of the sum module from the previous test.\n});\n"})}),"\n",(0,o.jsxs)(n.p,{children:["Returns the ",(0,o.jsx)(n.code,{children:"jest"})," object for chaining."]}),"\n",(0,o.jsx)(n.h3,{id:"jestisolatemodulesfn",children:(0,o.jsx)(n.code,{children:"jest.isolateModules(fn)"})}),"\n",(0,o.jsxs)(n.p,{children:[(0,o.jsx)(n.code,{children:"jest.isolateModules(fn)"})," goes a step further than ",(0,o.jsx)(n.code,{children:"jest.resetModules()"})," and creates a sandbox registry for the modules that are loaded inside the callback function. This is useful to isolate specific modules for every test so that local module state doesn't conflict between tests."]}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",children:"let myModule;\njest.isolateModules(() => {\n myModule = require('myModule');\n});\n\nconst otherCopyOfMyModule = require('myModule');\n"})}),"\n",(0,o.jsx)(n.h3,{id:"jestisolatemodulesasyncfn",children:(0,o.jsx)(n.code,{children:"jest.isolateModulesAsync(fn)"})}),"\n",(0,o.jsxs)(n.p,{children:[(0,o.jsx)(n.code,{children:"jest.isolateModulesAsync()"})," is the equivalent of ",(0,o.jsx)(n.code,{children:"jest.isolateModules()"}),", but for async callbacks. The caller is expected to ",(0,o.jsx)(n.code,{children:"await"})," the completion of ",(0,o.jsx)(n.code,{children:"isolateModulesAsync"}),"."]}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",children:"let myModule;\nawait jest.isolateModulesAsync(async () => {\n myModule = await import('myModule');\n // do async stuff here\n});\n\nconst otherCopyOfMyModule = await import('myModule');\n"})}),"\n",(0,o.jsx)(n.h2,{id:"mock-functions",children:"Mock Functions"}),"\n",(0,o.jsx)(n.h3,{id:"jestfnimplementation",children:(0,o.jsx)(n.code,{children:"jest.fn(implementation?)"})}),"\n",(0,o.jsxs)(n.p,{children:["Returns a new, unused ",(0,o.jsx)(n.a,{href:"/docs/30.0/mock-function-api",children:"mock function"}),". Optionally takes a mock implementation."]}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",children:"const mockFn = jest.fn();\nmockFn();\nexpect(mockFn).toHaveBeenCalled();\n\n// With a mock implementation:\nconst returnsTrue = jest.fn(() => true);\nconsole.log(returnsTrue()); // true;\n"})}),"\n",(0,o.jsx)(n.admonition,{type:"tip",children:(0,o.jsxs)(n.p,{children:["See the ",(0,o.jsx)(n.a,{href:"/docs/30.0/mock-function-api#jestfnimplementation",children:"Mock Functions"})," page for details on TypeScript usage."]})}),"\n",(0,o.jsx)(n.h3,{id:"jestismockfunctionfn",children:(0,o.jsx)(n.code,{children:"jest.isMockFunction(fn)"})}),"\n",(0,o.jsx)(n.p,{children:"Determines if the given function is a mocked function."}),"\n",(0,o.jsx)(n.h3,{id:"jestreplacepropertyobject-propertykey-value",children:(0,o.jsx)(n.code,{children:"jest.replaceProperty(object, propertyKey, value)"})}),"\n",(0,o.jsxs)(n.p,{children:["Replace ",(0,o.jsx)(n.code,{children:"object[propertyKey]"})," with a ",(0,o.jsx)(n.code,{children:"value"}),". The property must already exist on the object. The same property might be replaced multiple times. Returns a Jest ",(0,o.jsx)(n.a,{href:"/docs/30.0/mock-function-api#replaced-properties",children:"replaced property"}),"."]}),"\n",(0,o.jsx)(n.admonition,{type:"note",children:(0,o.jsxs)(n.p,{children:["To mock properties that are defined as getters or setters, use ",(0,o.jsx)(n.a,{href:"#jestspyonobject-methodname-accesstype",children:(0,o.jsx)(n.code,{children:"jest.spyOn(object, methodName, accessType)"})})," instead. To mock functions, use ",(0,o.jsx)(n.a,{href:"#jestspyonobject-methodname",children:(0,o.jsx)(n.code,{children:"jest.spyOn(object, methodName)"})})," instead."]})}),"\n",(0,o.jsx)(n.admonition,{type:"tip",children:(0,o.jsxs)(n.p,{children:["All properties replaced with ",(0,o.jsx)(n.code,{children:"jest.replaceProperty"})," could be restored to the original value by calling ",(0,o.jsx)(n.a,{href:"#jestrestoreallmocks",children:"jest.restoreAllMocks"})," on ",(0,o.jsx)(n.a,{href:"/docs/30.0/api#aftereachfn-timeout",children:"afterEach"})," method."]})}),"\n",(0,o.jsx)(n.p,{children:"Example:"}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",children:"const utils = {\n isLocalhost() {\n return process.env.HOSTNAME === 'localhost';\n },\n};\n\nmodule.exports = utils;\n"})}),"\n",(0,o.jsx)(n.p,{children:"Example test:"}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",children:"const utils = require('./utils');\n\nafterEach(() =>
1 {\n // restore replaced property\n jest.restoreAllMocks();\n});\n\ntest('isLocalhost returns true when HOSTNAME is localhost', () => {\n jest.replaceProperty(process, 'env', {HOSTNAME: 'localhost'});\n expect(utils.isLocalhost()).toBe(true);\n});\n\ntest('isLocalhost returns false when HOSTNAME is not localhost', () => {\n jest.replaceProperty(process, 'env', {HOSTNAME: 'not-localhost'});\n expect(utils.isLocalhost()).toBe(false);\n});\n"})}),"\n",(0,o.jsx)(n.h3,{id:"jestspyonobject-methodname",children:(0,o.jsx)(n.code,{children:"jest.spyOn(object, methodName)"})}),"\n",(0,o.jsxs)(n.p,{children:["Creates a mock function similar to ",(0,o.jsx)(n.code,{children:"jest.fn"})," but also tracks calls to ",(0,o.jsx)(n.code,{children:"object[methodName]"}),". Returns a Jest ",(0,o.jsx)(n.a,{href:"/docs/30.0/mock-function-api",children:"mock function"}),"."]}),"\n",(0,o.jsx)(n.admonition,{type:"note",children:(0,o.jsxs)(n.p,{children:["By default, ",(0,o.jsx)(n.code,{children:"jest.spyOn"})," also calls the ",(0,o.jsx)(n.strong,{children:"spied"})," method. This is different behavior from most other test libraries. If you want to overwrite the original function, you can use ",(0,o.jsx)(n.code,{children:"jest.spyOn(object, methodName).mockImplementation(() => customImplementation)"})," or ",(0,o.jsx)(n.code,{children:"object[methodName] = jest.fn(() => customImplementation)"}),"."]})}),"\n",(0,o.jsx)(n.admonition,{type:"tip",children:(0,o.jsxs)(n.p,{children:["Since ",(0,o.jsx)(n.code,{children:"jest.spyOn"})," is a mock, you could restore the initial state by calling ",(0,o.jsx)(n.a,{href:"#jestrestoreallmocks",children:(0,o.jsx)(n.code,{children:"jest.restoreAllMocks"})})," in the body of the callback passed to the ",(0,o.jsx)(n.a,{href:"/docs/30.0/api#aftereachfn-timeout",children:"afterEach"})," hook."]})}),"\n",(0,o.jsx)(n.p,{children:"Example:"}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",children:"const video = {\n play() {\n return true;\n },\n};\n\nmodule.exports = video;\n"})}),"\n",(0,o.jsx)(n.p,{children:"Example test:"}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",children:"const video = require('./video');\n\nafterEach(() => {\n // restore the spy created with spyOn\n jest.restoreAllMocks();\n});\n\ntest('plays video', () => {\n const spy = jest.spyOn(video, 'play');\n const isPlaying = video.play();\n\n expect(spy).toHaveBeenCalled();\n expect(isPlaying).toBe(true);\n});\n"})}),"\n",(0,o.jsxs)(n.h4,{id:"spied-methods-and-the-using-keyword",children:["Spied methods and the ",(0,o.jsx)(n.code,{children:"using"})," keyword"]}),"\n",(0,o.jsxs)(n.p,{children:["If your codebase is set up to transpile the ",(0,o.jsx)(n.a,{href:"https://github.com/tc39/proposal-explicit-resource-management",children:'"explicit resource management"'})," (e.g. if you are using TypeScript >= 5.2 or the ",(0,o.jsx)(n.code,{children:"@babel/plugin-proposal-explicit-resource-management"})," plugin), you can use ",(0,o.jsx)(n.code,{children:"spyOn"})," in combination with the ",(0,o.jsx)(n.code,{children:"using"})," keyword:"]}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",children:"test('logs a warning', () => {\n using spy = jest.spyOn(console, 'warn');\n doSomeThingWarnWorthy();\n expect(spy).toHaveBeenCalled();\n});\n"})}),"\n",(0,o.jsx)(n.p,{children:"That code is semantically equal to"}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",children:"test('logs a warning', () => {\n let spy;\n try {\n spy = jest.spyOn(console, 'warn');\n doSomeThingWarnWorthy();\n expect(spy).toHaveBeenCalled();\n } finally {\n spy.mockRestore();\n }\n});\n"})}),"\n",(0,o.jsx)(n.p,{children:"That way, your spy will automatically be restored to the original value once the current code block is left."}),"\n",(0,o.jsx)(n.p,{children:"You can even go a step further and use a code block to restrict your mock to only a part of your test without hurting readability."}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",children:"test('testing something', () => {\n {\n using spy = jest.spyOn(console, 'warn');\n setupStepThatWillLogAWarning();\n }\n // here, console.warn is already restored to the original value\n // your test can now continue normally\n});\n"})}),"\n",(0,o.jsxs)(n.admonition,{type:"note",children:[(0,o.jsxs)(n.p,{children:["If you get a warning that ",(0,o.jsx)(n.code,{children:"Symbol.dispose"})," does not exist, you might need to polyfill that, e.g. with this code:"]}),(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",children:"if (!Symbol.dispose) {\n Object.defineProperty(Symbol, 'dispose', {\n get() {\n return Symbol.for('nodejs.dispose');\n },\n });\n}\n"})})]}),"\n",(0,o.jsx)(n.h3,{id:"jestspyonobject-methodname-accesstype",children:(0,o.jsx)(n.code,{children:"jest.spyOn(object, methodName, accessType?)"})}),"\n",(0,o.jsxs)(n.p,{children:["Since Jest 22.1.0+, the ",(0,o.jsx)(n.code,{children:"jest.spyOn"})," method takes an optional third argument of ",(0,o.jsx)(n.code,{children:"accessType"})," that can be either ",(0,o.jsx)(n.code,{children:"'get'"})," or ",(0,o.jsx)(n.code,{children:"'set'"}),", which proves to be useful when you want to spy on a getter or a setter, respectively."]}),"\n",(0,o.jsx)(n.p,{children:"Example:"}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",children:"const video = {\n // it's a getter!\n get play() {\n return true;\n },\n};\n\nmodule.exports = video;\n\nconst audio = {\n _volume: false,\n // it's a setter!\n set volume(value) {\n this._volume = value;\n },\n get volume() {\n return this._volume;\n },\n};\n\nmodule.exports = audio;\n"})}),"\n",(0,o.jsx)(n.p,{children:"Example test:"}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",children:"const audio = require('./audio');\nconst video = require('./video');\n\nafterEach(() =>
1 {\n // restore the spy created with spyOn\n jest.restoreAllMocks();\n});\n\ntest('plays video', () => {\n const spy = jest.spyOn(video, 'play', 'get'); // we pass 'get'\n const isPlaying = video.play;\n\n expect(spy).toHaveBeenCalled();\n expect(isPlaying).toBe(true);\n});\n\ntest('plays audio', () => {\n const spy = jest.spyOn(audio, 'volume', 'set'); // we pass 'set'\n audio.volume = 100;\n\n expect(spy).toHaveBeenCalled();\n expect(audio.volume).toBe(100);\n});\n"})}),"\n",(0,o.jsx)(n.h3,{id:"jestreplacedsource",children:(0,o.jsx)(n.code,{children:"jest.Replaced<Source>"})}),"\n",(0,o.jsxs)(n.p,{children:["See ",(0,o.jsx)(n.a,{href:"/docs/30.0/mock-function-api#replacedpropertyreplacevaluevalue",children:"TypeScript Usage"})," chapter of Mock Functions page for documentation."]}),"\n",(0,o.jsx)(n.h3,{id:"jestspiedsource",children:(0,o.jsx)(n.code,{children:"jest.Spied<Source>"})}),"\n",(0,o.jsxs)(n.p,{children:["See ",(0,o.jsx)(n.a,{href:"/docs/30.0/mock-function-api#jestspiedsource",children:"TypeScript Usage"})," chapter of Mock Functions page for documentation."]}),"\n",(0,o.jsx)(n.h3,{id:"jestclearallmocks",children:(0,o.jsx)(n.code,{children:"jest.clearAllMocks()"})}),"\n",(0,o.jsxs)(n.p,{children:["Clears the ",(0,o.jsx)(n.code,{children:"mock.calls"}),", ",(0,o.jsx)(n.code,{children:"mock.instances"}),", ",(0,o.jsx)(n.code,{children:"mock.contexts"})," and ",(0,o.jsx)(n.code,{children:"mock.results"})," properties of all mocks. Equivalent to calling ",(0,o.jsx)(n.a,{href:"/docs/30.0/mock-function-api#mockfnmockclear",children:(0,o.jsx)(n.code,{children:".mockClear()"})})," on every mocked function."]}),"\n",(0,o.jsxs)(n.p,{children:["Returns the ",(0,o.jsx)(n.code,{children:"jest"})," object for chaining."]}),"\n",(0,o.jsx)(n.h3,{id:"jestresetallmocks",children:(0,o.jsx)(n.code,{children:"jest.resetAllMocks()"})}),"\n",(0,o.jsxs)(n.p,{children:["Resets the state of all mocks. Equivalent to calling ",(0,o.jsx)(n.a,{href:"/docs/30.0/mock-function-api#mockfnmockreset",children:(0,o.jsx)(n.code,{children:".mockReset()"})})," on every mocked function."]}),"\n",(0,o.jsxs)(n.p,{children:["Returns the ",(0,o.jsx)(n.code,{children:"jest"})," object for chaining."]}),"\n",(0,o.jsx)(n.h3,{id:"jestrestoreallmocks",children:(0,o.jsx)(n.code,{children:"jest.restoreAllMocks()"})}),"\n",(0,o.jsxs)(n.p,{children:["Restores all mocks and replaced properties back to their original value. Equivalent to calling ",(0,o.jsx)(n.a,{href:"/docs/30.0/mock-function-api#mockfnmockrestore",children:(0,o.jsx)(n.code,{children:".mockRestore()"})})," on every mocked function and ",(0,o.jsx)(n.a,{href:"/docs/30.0/mock-function-api#replacedpropertyrestore",children:(0,o.jsx)(n.code,{children:".restore()"})})," on every replaced property. Beware that ",(0,o.jsx)(n.code,{children:"jest.restoreAllMocks()"})," only works for mocks created with ",(0,o.jsx)(n.a,{href:"#jestspyonobject-methodname",children:(0,o.jsx)(n.code,{children:"jest.spyOn()"})})," and properties replaced with ",(0,o.jsx)(n.a,{href:"#jestreplacepropertyobject-propertykey-value",children:(0,o.jsx)(n.code,{children:"jest.replaceProperty()"})}),"; other mocks will require you to manually restore them."]}),"\n",(0,o.jsx)(n.h2,{id:"fake-timers",children:"Fake Timers"}),"\n",(0,o.jsx)(n.h3,{id:"jestusefaketimersfaketimersconfig",children:(0,o.jsx)(n.code,{children:"jest.useFakeTimers(fakeTimersConfig?)"})}),"\n",(0,o.jsxs)(n.p,{children:["Instructs Jest to use fake versions of the global date, performance, time and timer APIs. Fake timers implementation is backed by ",(0,o.jsx)(n.a,{href:"https://github.com/sinonjs/fake-timers",children:(0,o.jsx)(n.code,{children:"@sinonjs/fake-timers"})}),"."]}),"\n",(0,o.jsxs)(n.p,{children:["Fake timers will swap out ",(0,o.jsx)(n.code,{children:"Date"}),", ",(0,o.jsx)(n.code,{children:"performance.now()"}),", ",(0,o.jsx)(n.code,{children:"queueMicrotask()"}),", ",(0,o.jsx)(n.code,{children:"setImmediate()"}),", ",(0,o.jsx)(n.code,{children:"clearImmediate()"}),", ",(0,o.jsx)(n.code,{children:"setInterval()"}),", ",(0,o.jsx)(n.code,{children:"clearInterval()"}),", ",(0,o.jsx)(n.code,{children:"setTimeout()"}),", ",(0,o.jsx)(n.code,{children:"clearTimeout()"})," with an implementation that gets its time from the fake clock."]}),"\n",(0,o.jsxs)(n.p,{children:["In Node environment ",(0,o.jsx)(n.code,{children:"process.hrtime"}),", ",(0,o.jsx)(n.code,{children:"process.nextTick()"})," and in JSDOM environment ",(0,o.jsx)(n.code,{children:"requestAnimationFrame()"}),", ",(0,o.jsx)(n.code,{children:"cancelAnimationFrame()"}),", ",(0,o.jsx)(n.code,{children:"requestIdleCallback()"}),", ",(0,o.jsx)(n.code,{children:"cancelIdleCallback()"})," will be replaced as well."]}),"\n",(0,o.jsx)(n.p,{children:"Configuration options:"}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-ts",children:"type FakeableAPI =\n | 'Date'\n | 'hrtime'\n | 'nextTick'\n | 'performance'\n | 'queueMicrotask'\n | 'requestAnimationFrame'\n | 'cancelAnimationFrame'\n | 'requestIdleCallback'\n | 'cancelIdleCallback'\n | 'setImmediate'\n | 'clearImmediate'\n | 'setInterval'\n | 'clearInterval'\n | 'setTimeout'\n | 'clearTimeout';\n\ntype FakeTimersConfig = {\n /**\n * If set to `true` all timers will be advanced automatically by 20 milliseconds\n * every 20 milliseconds. A custom time delta may be provided by passing a number.\n * The default is `false`.\n */\n advanceTimers?: boolean | number;\n /**\n * List of names of APIs that should not be faked. The default is `[]`, meaning\n * all APIs are faked.\n */\n doNotFake?: Array<FakeableAPI>;\n /**\n * Use the old fake timers implementation instead of one backed by `@sinonjs/fake-timers`.\n * The default is `false`.\n */\n legacyFakeTimers?: boolean;\n /** Sets current system time to be used by fake timers, in milliseconds. The default is `Date.now()`. */\n now?: number | Date;\n /**\n * The maximum number of recursive timers that will be run when calling `jest.runAllTimers()`.\n * The default is `100_000` timers.\n */\n timerLimit?: number;\n};\n"})}),"\n",(0,o.jsxs)(n.p,{children:["Calling ",(0,o.jsx)(n.code,{children:"jest.useFakeTimers()"})," will use fake timers for all tests within the file, until original timers are restored with ",(0,o.jsx)(n.code,{children:"jest.useRealTimers()"}),"."]}),"\n",(0,o.jsxs)(n.p,{children:["You can call ",(0,o.jsx)(n.code,{children:"jest.useFakeTimers()"})," or ",(0,o.jsx)(n.code,{children:"jest.useRealTimers()"})," from anywhere: top level, inside an ",(0,o.jsx)(n.code,{children:"test"})," block, etc. Keep in mind that this is a ",(0,o.jsx)(n.strong,{children:"global operation"})," and will affect other tests within the same file. Calling ",(0,o.jsx)(n.code,{children:"jest.useFakeTimers()"})," once again in the same test file would reset the internal state (e.g. timer count) and reinstall fake timers using the provided options:"]}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",children:"test('advance the timers automatically', () => {\n jest.useFakeTimers({advanceTimers: true});\n // ...\n});\n\ntest('do not advance the timers and do not fake `performance`', () => {\n jest.useFakeTimers({doNotFake: ['performance']});\n // ...\n});\n\ntest('uninstall fake timers for the rest of tests in the file', () => {\n jest.useRealTimers();\n // ...\n});\n"})}),"\n",(0,o.jsxs)(n.admonition,{title:"Legacy Fake Timers",type:"info",children:[(0,o.jsx)(n.p,{children:"For some reason you might have to use legacy implementation of fake timers. It can be enabled like this (additional options are not supported):"}),(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",children:"jest.useFakeTimers({\n legacyFakeTimers: true,\n});\n"})}),(0,o.jsxs)(n.p,{children:["Legacy fake timers will swap out ",(0,o.jsx)(n.code,{children:"setImmediate()"}),", ",(0,o.jsx)(n.code,{children:"clearImmediate()"}),", ",(0,o.jsx)(n.code,{children:"setInterval()"}),", ",(0,o.jsx)(n.code,{children:"clearInterval()"}),", ",(0,o.jsx)(n.code,{children:"setTimeout()"}),", ",(0,o.jsx)(n.code,{children:"clearTimeout()"})," with Jest ",(0,o.jsx)(n.a,{href:"/docs/30.0/mock-function-api",children:"mock functions"}),". In Node environment ",(0,o.jsx)(n.code,{children:"process.nextTick()"})," and in JSDOM environment ",(0,o.jsx)(n.code,{children:"requestAnimationFrame()"}),", ",(0,o.jsx)(n.code,{children:"cancelAnimationFrame()"})," will be also replaced."]})]}),"\n",(0,o.jsxs)(n.p,{children:["Returns the ",(0,o.jsx)(n.code,{children:"jest"})," object for chaining."]}),"\n",(0,o.jsx)(n.h3,{id:"jestuserealtimers",children:(0,o.jsx)(n.code,{children:"jest.useRealTimers()"})}),"\n",(0,o.jsxs)(n.p,{children:["Instructs Jest to restore the original implementations of the global date, performance, time and timer APIs. For example, you may call ",(0,o.jsx)(n.code,{children:"jest.useRealTimers()"})," inside ",(0,o.jsx)(n.code,{children:"afterEach"})," hook to restore timers after each test:"]}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",children:"afterEach(() =>
1 {\n jest.useRealTimers();\n});\n\ntest('do something with fake timers', () => {\n jest.useFakeTimers();\n // ...\n});\n\ntest('do something with real timers', () => {\n // ...\n});\n"})}),"\n",(0,o.jsxs)(n.p,{children:["Returns the ",(0,o.jsx)(n.code,{children:"jest"})," object for chaining."]}),"\n",(0,o.jsx)(n.h3,{id:"jestrunallticks",children:(0,o.jsx)(n.code,{children:"jest.runAllTicks()"})}),"\n",(0,o.jsxs)(n.p,{children:["Exhausts the ",(0,o.jsx)(n.strong,{children:"micro"}),"-task queue (usually interfaced in node via ",(0,o.jsx)(n.code,{children:"process.nextTick"}),")."]}),"\n",(0,o.jsxs)(n.p,{children:["When this API is called, all pending micro-tasks that have been queued via ",(0,o.jsx)(n.code,{children:"process.nextTick"})," will be executed. Additionally, if those micro-tasks themselves schedule new micro-tasks, those will be continually exhausted until there are no more micro-tasks remaining in the queue."]}),"\n",(0,o.jsx)(n.h3,{id:"jestrunalltimers",children:(0,o.jsx)(n.code,{children:"jest.runAllTimers()"})}),"\n",(0,o.jsxs)(n.p,{children:["Exhausts both the ",(0,o.jsx)(n.strong,{children:"macro"}),"-task queue (i.e., all tasks queued by ",(0,o.jsx)(n.code,{children:"setTimeout()"}),", ",(0,o.jsx)(n.code,{children:"setInterval()"}),", and ",(0,o.jsx)(n.code,{children:"setImmediate()"}),") and the ",(0,o.jsx)(n.strong,{children:"micro"}),"-task queue (usually interfaced in node via ",(0,o.jsx)(n.code,{children:"process.nextTick"}),")."]}),"\n",(0,o.jsx)(n.p,{children:"When this API is called, all pending macro-tasks and micro-tasks will be executed. If those tasks themselves schedule new tasks, those will be continually exhausted until there are no more tasks remaining in the queue."}),"\n",(0,o.jsxs)(n.p,{children:["This is often useful for synchronously executing setTimeouts during a test in order to synchronously assert about some behavior that would only happen after the ",(0,o.jsx)(n.code,{children:"setTimeout()"})," or ",(0,o.jsx)(n.code,{children:"setInterval()"})," callbacks executed. See the ",(0,o.jsx)(n.a,{href:"/docs/30.0/timer-mocks",children:"Timer mocks"})," doc for more information."]}),"\n",(0,o.jsx)(n.h3,{id:"jestrunalltimersasync",children:(0,o.jsx)(n.code,{children:"jest.runAllTimersAsync()"})}),"\n",(0,o.jsxs)(n.p,{children:["Asynchronous equivalent of ",(0,o.jsx)(n.code,{children:"jest.runAllTimers()"}),". It allows any scheduled promise callbacks to execute ",(0,o.jsx)(n.em,{children:"before"})," running the timers."]}),"\n",(0,o.jsx)(n.admonition,{type:"info",children:(0,o.jsx)(n.p,{children:"This function is not available when using legacy fake timers implementation."})}),"\n",(0,o.jsx)(n.h3,{id:"jestrunallimmediates",children:(0,o.jsx)(n.code,{children:"jest.runAllImmediates()"})}),"\n",(0,o.jsxs)(n.p,{children:["Exhausts all tasks queued by ",(0,o.jsx)(n.code,{children:"setImmediate()"}),"."]}),"\n",(0,o.jsx)(n.admonition,{type:"info",children:(0,o.jsx)(n.p,{children:"This function is only available when using legacy fake timers implementation."})}),"\n",(0,o.jsx)(n.h3,{id:"jestadvancetimersbytimemstorun",children:(0,o.jsx)(n.code,{children:"jest.advanceTimersByTime(msToRun)"})}),"\n",(0,o.jsxs)(n.p,{children:["Executes only the macro task queue (i.e. all tasks queued by ",(0,o.jsx)(n.code,{children:"setTimeout()"})," or ",(0,o.jsx)(n.code,{children:"setInterval()"})," and ",(0,o.jsx)(n.code,{children:"setImmediate()"}),")."]}),"\n",(0,o.jsxs)(n.p,{children:["When this API is called, all timers are advanced by ",(0,o.jsx)(n.code,{children:"msToRun"}),' milliseconds. All pending "macro-tasks" that have been queued via ',(0,o.jsx)(n.code,{children:"setTimeout()"})," or ",(0,o.jsx)(n.code,{children:"setInterval()"}),", and would be executed within this time frame will be executed. Additionally, if those macro-tasks schedule new macro-tasks that would be executed within the same time frame, those will be executed until there are no more macro-tasks remaining in the queue, that should be run within ",(0,o.jsx)(n.code,{children:"msToRun"})," milliseconds."]}),"\n",(0,o.jsx)(n.h3,{id:"jestadvancetimersbytimeasyncmstorun",children:(0,o.jsx)(n.code,{children:"jest.advanceTimersByTimeAsync(msToRun)"})}),"\n",(0,o.jsxs)(n.p,{children:["Asynchronous equivalent of ",(0,o.jsx)(n.code,{children:"jest.advanceTimersByTime(msToRun)"}),". It allows any scheduled promise callbacks to execute ",(0,o.jsx)(n.em,{children:"before"})," running the timers."]}),"\n",(0,o.jsx)(n.admonition,{type:"info",children:(0,o.jsx)(n.p,{children:"This function is not available when using legacy fake timers implementation."})}),"\n",(0,o.jsx)(n.h3,{id:"jestrunonlypendingtimers",children:(0,o.jsx)(n.code,{children:"jest.runOnlyPendingTimers()"})}),"\n",(0,o.jsxs)(n.p,{children:["Executes only the macro-tasks that are currently pending (i.e., only the tasks that have been queued by ",(0,o.jsx)(n.code,{children:"setTimeout()"})," or ",(0,o.jsx)(n.code,{children:"setInterval()"})," up to this point). If any of the currently pending macro-tasks schedule new macro-tasks, those new tasks will not be executed by this call."]}),"\n",(0,o.jsxs)(n.p,{children:["This is useful for scenarios such as one where the module being tested schedules a ",(0,o.jsx)(n.code,{children:"setTimeout()"})," whose callback schedules another ",(0,o.jsx)(n.code,{children:"setTimeout()"})," recursively (meaning the scheduling never stops). In these scenarios, it's useful to be able to run forward in time by a single step at a time."]}),"\n",(0,o.jsx)(n.h3,{id:"jestrunonlypendingtimersasync",children:(0,o.jsx)(n.code,{children:"jest.runOnlyPendingTimersAsync()"})}),"\n",(0,o.jsxs)(n.p,{children:["Asynchronous equivalent of ",(0,o.jsx)(n.code,{children:"jest.runOnlyPendingTimers()"}),". It allows any scheduled promise callbacks to execute ",(0,o.jsx)(n.em,{children:"before"})," running the timers."]}),"\n",(0,o.jsx)(n.admonition,{type:"info",children:(0,o.jsx)(n.p,{children:"This function is not available when using legacy fake timers implementation."})}),"\n",(0,o.jsx)(n.h3,{id:"jestadvancetimerstonexttimersteps",children:(0,o.jsx)(n.code,{children:"jest.advanceTimersToNextTimer(steps)"})}),"\n",(0,o.jsx)(n.p,{children:"Advances all timers by the needed milliseconds so that only the next timeouts/intervals will run."}),"\n",(0,o.jsxs)(n.p,{children:["Optionally, you can provide ",(0,o.jsx)(n.code,{children:"steps"}),", so it will run ",(0,o.jsx)(n.code,{children:"steps"})," amount of next timeouts/intervals."]}),"\n",(0,o.jsx)(n.h3,{id:"jestadvancetimerstonexttimerasyncsteps",children:(0,o.jsx)(n.code,{children:"jest.advanceTimersToNextTimerAsync(steps)"})}),"\n",(0,o.jsxs)(n.p,{children:["Asynchronous equivalent of ",(0,o.jsx)(n.code,{children:"jest.advanceTimersToNextTimer(steps)"}),". It allows any scheduled promise callbacks to execute ",(0,o.jsx)(n.em,{children:"before"})," running the timers."]}),"\n",(0,o.jsx)(n.admonition,{type:"info",children:(0,o.jsx)(n.p,{children:"This function is not available when using legacy fake timers implementation."})}),"\n",(0,o.jsx)(n.h3,{id:"jestadvancetimerstonextframe",children:(0,o.jsx)(n.code,{children:"jest.advanceTimersToNextFrame()"})}),"\n",(0,o.jsxs)(n.p,{children:["Advances all timers by the needed milliseconds to execute callbacks currently sc
1heduled with ",(0,o.jsx)(n.code,{children:"requestAnimationFrame"}),". ",(0,o.jsx)(n.code,{children:"advanceTimersToNextFrame()"})," is a helpful way to execute code that is scheduled using ",(0,o.jsx)(n.code,{children:"requestAnimationFrame"}),"."]}),"\n",(0,o.jsx)(n.admonition,{type:"info",children:(0,o.jsx)(n.p,{children:"This function is not available when using legacy fake timers implementation."})}),"\n",(0,o.jsx)(n.h3,{id:"jestclearalltimers",children:(0,o.jsx)(n.code,{children:"jest.clearAllTimers()"})}),"\n",(0,o.jsx)(n.p,{children:"Removes any pending timers from the timer system."}),"\n",(0,o.jsx)(n.p,{children:"This means, if any timers have been scheduled (but have not yet executed), they will be cleared and will never have the opportunity to execute in the future."}),"\n",(0,o.jsx)(n.h3,{id:"jestgettimercount",children:(0,o.jsx)(n.code,{children:"jest.getTimerCount()"})}),"\n",(0,o.jsx)(n.p,{children:"Returns the number of fake timers still left to run."}),"\n",(0,o.jsx)(n.h3,{id:"jestnow",children:(0,o.jsx)(n.code,{children:"jest.now()"})}),"\n",(0,o.jsxs)(n.p,{children:["Returns the time in ms of the current clock. This is equivalent to ",(0,o.jsx)(n.code,{children:"Date.now()"})," if real timers are in use, or if ",(0,o.jsx)(n.code,{children:"Date"})," is mocked. In other cases (such as legacy timers) it may be useful for implementing custom mocks of ",(0,o.jsx)(n.code,{children:"Date.now()"}),", ",(0,o.jsx)(n.code,{children:"performance.now()"}),", etc."]}),"\n",(0,o.jsx)(n.h3,{id:"jestsetsystemtimenow-number--date",children:(0,o.jsx)(n.code,{children:"jest.setSystemTime(now?: number | Date)"})}),"\n",(0,o.jsxs)(n.p,{children:["Set the current system time used by fake timers. Simulates a user changing the system clock while your program is running. It affects the current time but it does not in itself cause e.g. timers to fire; they will fire exactly as they would have done without the call to ",(0,o.jsx)(n.code,{children:"jest.setSystemTime()"}),"."]}),"\n",(0,o.jsx)(n.admonition,{type:"info",children:(0,o.jsx)(n.p,{children:"This function is not available when using legacy fake timers implementation."})}),"\n",(0,o.jsx)(n.h3,{id:"jestgetrealsystemtime",children:(0,o.jsx)(n.code,{children:"jest.getRealSystemTime()"})}),"\n",(0,o.jsxs)(n.p,{children:["When mocking time, ",(0,o.jsx)(n.code,{children:"Date.now()"})," will also be mocked. If you for some reason need access to the real current time, you can invoke this function."]}),"\n",(0,o.jsx)(n.admonition,{type:"info",children:(0,o.jsx)(n.p,{children:"This function is not available when using legacy fake timers implementation."})}),"\n",(0,o.jsx)(n.h2,{id:"misc",children:"Misc"}),"\n",(0,o.jsx)(n.h3,{id:"jestgetseed",children:(0,o.jsx)(n.code,{children:"jest.getSeed()"})}),"\n",(0,o.jsx)(n.p,{children:"Every time Jest runs a seed value is randomly generated which you could use in a pseudorandom number generator or anywhere else."}),"\n",(0,o.jsx)(n.admonition,{type:"tip",children:(0,o.jsxs)(n.p,{children:["Use the ",(0,o.jsx)(n.a,{href:"/docs/30.0/cli#--showseed",children:(0,o.jsx)(n.code,{children:"--showSeed"})})," flag to print the seed in the test report summary. To manually set the value of the seed use ",(0,o.jsx)(n.a,{href:"/docs/30.0/cli#--seednum",children:(0,o.jsx)(n.code,{children:"--seed=<num>"})})," CLI argument."]})}),"\n",(0,o.jsx)(n.h3,{id:"jestisenvironmenttorndown",children:(0,o.jsx)(n.code,{children:"jest.isEnvironmentTornDown()"})}),"\n",(0,o.jsxs)(n.p,{children:["Returns ",(0,o.jsx)(n.code,{children:"true"})," if test environment has been torn down."]}),"\n",(0,o.jsx)(n.h3,{id:"jestretrytimesnumretries-options",children:(0,o.jsx)(n.code,{children:"jest.retryTimes(numRetries, options?)"})}),"\n",(0,o.jsx)(n.p,{children:"Runs failed tests n-times until they pass or until the max number of retries is exhausted."}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",children:"jest.retryTimes(3);\n\ntest('will fail', () => {\n expect(true).toBe(false);\n});\n"})}),"\n",(0,o.jsxs)(n.p,{children:["If ",(0,o.jsx)(n.code,{children:"logErrorsBeforeRetry"})," option is enabled, error(s) that caused the test to fail will be logged to the console."]}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",children:"jest.retryTimes(3, {logErrorsBeforeRetry: true});\n\ntest('will fail', () => {\n expect(true).toBe(false);\n});\n"})}),"\n",(0,o.jsxs)(n.p,{children:[(0,o.jsx)(n.code,{children:"waitBeforeRetry"})," is the number of milliseconds to wait before retrying."]}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",children:"jest.retryTimes(3, {waitBeforeRetry: 1000});\n\ntest('will fail', () => {\n expect(true).toBe(false);\n});\n"})}),"\n",(0,o.jsxs)(n.p,{children:[(0,o.jsx)(n.code,{children:"retryImmediately"})," option is used to retry the failed test immediately after the failure. If this option is not specified, the tests are retried after Jest is finished running all other tests in the file."]}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",children:"jest.retryTimes(3, {retryImmediately: true});\n\ntest('will fail', () => {\n expect(true).toBe(false);\n});\n"})}),"\n",(0,o.jsxs)(n.p,{children:["Returns the ",(0,o.jsx)(n.code,{children:"jest"})," object for chaining."]}),"\n",(0,o.jsx)(n.admonition,{type:"caution",children:(0,o.jsxs)(n.p,{children:[(0,o.jsx)(n.code,{children:"jest.retryTimes()"})," must be declared at the top level of a test file or in a ",(0,o.jsx)(n.code,{children:"describe"})," block."]})}),"\n",(0,o.jsx)(n.admonition,{type:"info",children:(0,o.jsxs)(n.p,{children:["This function is only available with the default ",(0,o.jsx)(n.a,{href:"https://github.com/jestjs/jest/tree/main/packages/jest-circus",children:"jest-circus"})," runner."]})}),"\n",(0,o.jsx)(n.h3,{id:"jestsettimeouttimeout",children:(0,o.jsx)(n.code,{children:"jest.setTimeout(timeout)"})}),"\n",(0,o.jsx)(n.p,{children:"Set the default timeout interval (in milliseconds) for all tests and before/after hooks in the test file. This only affects the test file from which this function is called. The default timeout interval is 5 seconds
1if this method is not called."}),"\n",(0,o.jsx)(n.p,{children:"Example:"}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-js",children:"jest.setTimeout(1000); // 1 second\n"})}),"\n",(0,o.jsxs)(n.admonition,{type:"tip",children:[(0,o.jsxs)(n.p,{children:["To set timeout intervals on different tests in the same file, use the ",(0,o.jsxs)(n.a,{href:"/docs/30.0/api#testname-fn-timeout",children:[(0,o.jsx)(n.code,{children:"timeout"})," option on each individual test"]}),"."]}),(0,o.jsxs)(n.p,{children:["If you want to set the timeout for all test files, use ",(0,o.jsx)(n.a,{href:"/docs/30.0/configuration#testtimeout-number",children:(0,o.jsx)(n.code,{children:"testTimeout"})})," configuration option."]})]})]})}function p(e={}){const{wrapper:n}={...(0,i.R)(),...e.components};return n?(0,o.jsx)(n,{...e,children:(0,o.jsx)(j,{...e})}):j(e)}},74323(e,n,t){t.d(n,{Ay:()=>l});var s=t(62540),o=t(43023);function i(e){const n={a:"a",admonition:"admonition",code:"code",p:"p",pre:"pre",...(0,o.R)(),...e.components};return(0,s.jsxs)(n.admonition,{type:"info",children:[(0,s.jsx)(n.p,{children:"The TypeScript examples from this page will only work as documented if you explicitly import Jest APIs:"}),(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-ts",children:"import {expect, jest, test} from '@jest/globals';\n"})}),(0,s.jsxs)(n.p,{children:["Consult the ",(0,s.jsx)(n.a,{href:"/docs/30.0/getting-started#using-typescript",children:"Getting Started"})," guide for details on how to setup Jest with TypeScript."]})]})}function l(e={}){const{wrapper:n}={...(0,o.R)(),...e.components};return n?(0,s.jsx)(n,{...e,children:(0,s.jsx)(i,{...e})}):i(e)}t.d(n,["RM",0,[]])}}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.