Skip to content

Commit

Permalink
fix: use typeof type guard instead of instanceof to differentiate Mod…
Browse files Browse the repository at this point in the history
…ernFakeTimers and LegacyFakeTimers methods

Closes #11660 #11767 #11662
  • Loading branch information
minijus committed Oct 15, 2021
1 parent 3674bbf commit de211da
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -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

Expand Down
14 changes: 10 additions & 4 deletions packages/jest-runtime/src/index.ts
Expand Up @@ -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';
Expand Down Expand Up @@ -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(
Expand All @@ -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(
Expand All @@ -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(
Expand All @@ -2018,6 +2018,12 @@ export default class Runtime {
return jestObject;
}

private _areModernFakeTimers(
fakeTimers: ModernFakeTimers | LegacyFakeTimers<unknown>,
): 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))}.`
Expand Down

0 comments on commit de211da

Please sign in to comment.