Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: correct instanceof for ModernFakeTimers and LegacyFakeTimers methods #11946

Merged
merged 4 commits into from Oct 15, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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