diff --git a/CHANGELOG.md b/CHANGELOG.md index b706156bc4b3..5a125dcf0f58 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### Fixes - `[jest-runtime]` Ensure absolute paths can be resolved within test modules ([11943](https://github.com/facebook/jest/pull/11943)) +- `[jest-runtime]` Use typeof type guard instead of instanceof to differentiate ModernFakeTimers and LegacyFakeTimers methods ([#11946](https://github.com/facebook/jest/pull/11946)) ### Chore & Maintenance diff --git a/packages/jest-runtime/src/index.ts b/packages/jest-runtime/src/index.ts index c8cfa5c17246..b55ec85b4e77 100644 --- a/packages/jest-runtime/src/index.ts +++ b/packages/jest-runtime/src/index.ts @@ -30,7 +30,7 @@ import type { Module, ModuleWrapper, } from '@jest/environment'; -import {LegacyFakeTimers, ModernFakeTimers} from '@jest/fake-timers'; +import type {LegacyFakeTimers, ModernFakeTimers} from '@jest/fake-timers'; import type * as JestGlobals from '@jest/globals'; import type {SourceMapRegistry} from '@jest/source-map'; import type {RuntimeTransformResult, V8CoverageResult} from '@jest/test-result'; @@ -1963,7 +1963,7 @@ export default class Runtime { getRealSystemTime: () => { const fakeTimers = _getFakeTimers(); - if (fakeTimers instanceof ModernFakeTimers) { + if (this._areModernFakeTimers(fakeTimers)) { return fakeTimers.getRealSystemTime(); } else { throw new TypeError( @@ -1984,7 +1984,7 @@ export default class Runtime { runAllImmediates: () => { const fakeTimers = _getFakeTimers(); - if (fakeTimers instanceof LegacyFakeTimers) { + if (!this._areModernFakeTimers(fakeTimers)) { fakeTimers.runAllImmediates(); } else { throw new TypeError( @@ -2000,7 +2000,7 @@ export default class Runtime { setSystemTime: (now?: number | Date) => { const fakeTimers = _getFakeTimers(); - if (fakeTimers instanceof ModernFakeTimers) { + if (this._areModernFakeTimers(fakeTimers)) { fakeTimers.setSystemTime(now); } else { throw new TypeError( @@ -2018,6 +2018,12 @@ export default class Runtime { return jestObject; } + private _areModernFakeTimers( + fakeTimers: ModernFakeTimers | LegacyFakeTimers, + ): fakeTimers is ModernFakeTimers { + return typeof (fakeTimers as ModernFakeTimers).setSystemTime === 'function'; + } + private _logFormattedReferenceError(errorMessage: string) { const testPath = this._testPath ? ` From ${slash(path.relative(this._config.rootDir, this._testPath))}.`