Skip to content

Commit

Permalink
fix: use typeof assertion instead of instanceof to differentiate Mode…
Browse files Browse the repository at this point in the history
…rnFakeTimers and LegacyFakeTimers methods

Closes #11660 #11767 #11662
  • Loading branch information
minijus committed Oct 10, 2021
1 parent 03f4a69 commit 74d39f3
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
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` assertion instead of `instanceof` to differentiate ModernFakeTimers and LegacyFakeTimers methods ([#11946](https://github.com/facebook/jest/pull/11946))

### Chore & Maintenance

Expand Down
22 changes: 15 additions & 7 deletions packages/jest-runtime/src/index.ts
Original file line number Diff line number Diff line change
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 @@ -1961,8 +1961,11 @@ export default class Runtime {
getRealSystemTime: () => {
const fakeTimers = _getFakeTimers();

if (fakeTimers instanceof ModernFakeTimers) {
return fakeTimers.getRealSystemTime();
if (
typeof (fakeTimers as ModernFakeTimers).getRealSystemTime ===
'function'
) {
return (fakeTimers as ModernFakeTimers).getRealSystemTime();
} else {
throw new TypeError(
'getRealSystemTime is not available when not using modern timers',
Expand All @@ -1982,8 +1985,11 @@ export default class Runtime {
runAllImmediates: () => {
const fakeTimers = _getFakeTimers();

if (fakeTimers instanceof LegacyFakeTimers) {
fakeTimers.runAllImmediates();
if (
typeof (fakeTimers as LegacyFakeTimers<unknown>).runAllImmediates ===
'function'
) {
(fakeTimers as LegacyFakeTimers<unknown>).runAllImmediates();
} else {
throw new TypeError(
'runAllImmediates is not available when using modern timers',
Expand All @@ -1998,8 +2004,10 @@ export default class Runtime {
setSystemTime: (now?: number | Date) => {
const fakeTimers = _getFakeTimers();

if (fakeTimers instanceof ModernFakeTimers) {
fakeTimers.setSystemTime(now);
if (
typeof (fakeTimers as ModernFakeTimers).setSystemTime === 'function'
) {
(fakeTimers as ModernFakeTimers).setSystemTime(now);
} else {
throw new TypeError(
'setSystemTime is not available when not using modern timers',
Expand Down

0 comments on commit 74d39f3

Please sign in to comment.