-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
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
feat: add fake timers implementation backed by Lolex #8897
Merged
Merged
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,15 +5,16 @@ | |
jest.useFakeTimers(); | ||
|
||
it('schedules a 10-second timer after 1 second', () => { | ||
jest.spyOn(global, 'setTimeout'); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The reason for this change is that the fake timer functions in current implementation are mock functions, a feature I've purposefully not implemented in the Lolex version. |
||
const infiniteTimerGame = require('../infiniteTimerGame'); | ||
const callback = jest.fn(); | ||
|
||
infiniteTimerGame(callback); | ||
|
||
// At this point in time, there should have been a single call to | ||
// setTimeout to schedule the end of the game in 1 second. | ||
expect(setTimeout.mock.calls.length).toBe(1); | ||
expect(setTimeout.mock.calls[0][1]).toBe(1000); | ||
expect(setTimeout).toBeCalledTimes(1); | ||
expect(setTimeout).toHaveBeenNthCalledWith(1, expect.any(Function), 1000); | ||
|
||
// Fast forward and exhaust only currently pending timers | ||
// (but not any new timers that get created during that process) | ||
|
@@ -24,6 +25,6 @@ it('schedules a 10-second timer after 1 second', () => { | |
|
||
// And it should have created a new timer to start the game over in | ||
// 10 seconds | ||
expect(setTimeout.mock.calls.length).toBe(2); | ||
expect(setTimeout.mock.calls[1][1]).toBe(10000); | ||
expect(setTimeout).toBeCalledTimes(2); | ||
expect(setTimeout).toHaveBeenNthCalledWith(2, expect.any(Function), 10000); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,154 @@ | ||
/** | ||
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. | ||
* | ||
* This source code is licensed under the MIT license found in the | ||
* LICENSE file in the root directory of this source tree. | ||
*/ | ||
|
||
import { | ||
InstalledClock, | ||
LolexWithContext, | ||
withGlobal as lolexWithGlobal, | ||
} from 'lolex'; | ||
import {StackTraceConfig, formatStackTrace} from 'jest-message-util'; | ||
|
||
export default class FakeTimers { | ||
private _clock!: InstalledClock; | ||
private _config: StackTraceConfig; | ||
private _fakingTime: boolean; | ||
private _global: NodeJS.Global; | ||
private _lolex: LolexWithContext; | ||
private _maxLoops: number; | ||
|
||
constructor({ | ||
global, | ||
config, | ||
maxLoops, | ||
}: { | ||
global: NodeJS.Global; | ||
config: StackTraceConfig; | ||
maxLoops?: number; | ||
}) { | ||
this._global = global; | ||
this._config = config; | ||
this._maxLoops = maxLoops || 100000; | ||
|
||
this._fakingTime = false; | ||
this._lolex = lolexWithGlobal(global); | ||
} | ||
|
||
clearAllTimers() { | ||
if (this._fakingTime) { | ||
this._clock.reset(); | ||
} | ||
} | ||
|
||
dispose() { | ||
this.useRealTimers(); | ||
} | ||
|
||
runAllTimers() { | ||
if (this._checkFakeTimers()) { | ||
this._clock.runAll(); | ||
} | ||
} | ||
|
||
runOnlyPendingTimers() { | ||
if (this._checkFakeTimers()) { | ||
this._clock.runToLast(); | ||
} | ||
} | ||
|
||
advanceTimersToNextTimer(steps = 1) { | ||
if (this._checkFakeTimers()) { | ||
for (let i = steps; i > 0; i--) { | ||
this._clock.next(); | ||
// Fire all timers at this point: https://github.com/sinonjs/lolex/issues/250 | ||
this._clock.tick(0); | ||
|
||
if (this._clock.countTimers() === 0) { | ||
break; | ||
} | ||
} | ||
} | ||
} | ||
|
||
advanceTimersByTime(msToRun: number) { | ||
if (this._checkFakeTimers()) { | ||
this._clock.tick(msToRun); | ||
} | ||
} | ||
|
||
runAllTicks() { | ||
if (this._checkFakeTimers()) { | ||
// @ts-ignore | ||
this._clock.runMicrotasks(); | ||
} | ||
} | ||
|
||
useRealTimers() { | ||
if (this._fakingTime) { | ||
this._clock.uninstall(); | ||
this._fakingTime = false; | ||
} | ||
} | ||
|
||
useFakeTimers() { | ||
const toFake = Object.keys(this._lolex.timers) as Array< | ||
keyof LolexWithContext['timers'] | ||
>; | ||
|
||
if (!this._fakingTime) { | ||
this._clock = this._lolex.install({ | ||
loopLimit: this._maxLoops, | ||
now: Date.now(), | ||
target: this._global, | ||
toFake, | ||
}); | ||
|
||
this._fakingTime = true; | ||
} | ||
} | ||
|
||
reset() { | ||
if (this._checkFakeTimers()) { | ||
const {now} = this._clock; | ||
this._clock.reset(); | ||
this._clock.setSystemTime(now); | ||
} | ||
} | ||
|
||
setSystemTime(now?: number) { | ||
if (this._checkFakeTimers()) { | ||
this._clock.setSystemTime(now); | ||
} | ||
} | ||
|
||
getRealSystemTime() { | ||
return Date.now(); | ||
} | ||
|
||
getTimerCount() { | ||
if (this._checkFakeTimers()) { | ||
return this._clock.countTimers(); | ||
} | ||
|
||
return 0; | ||
} | ||
|
||
private _checkFakeTimers() { | ||
if (!this._fakingTime) { | ||
this._global.console.warn( | ||
'A function to advance timers was called but the timers API is not ' + | ||
'mocked with fake timers. Call `jest.useFakeTimers()` in this test or ' + | ||
'enable fake timers globally by setting `"timers": "fake"` in the ' + | ||
'configuration file\nStack Trace:\n' + | ||
formatStackTrace(new Error().stack!, this._config, { | ||
noStackTrace: false, | ||
}), | ||
); | ||
} | ||
|
||
return this._fakingTime; | ||
} | ||
} |
3 changes: 3 additions & 0 deletions
3
packages/jest-fake-timers/src/__tests__/__snapshots__/fakeTimersLolex.test.ts.snap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
// Jest Snapshot v1, https://goo.gl/fbAQLP | ||
|
||
exports[`FakeTimers runAllTimers warns when trying to advance timers while real timers are used 1`] = `"A function to advance timers was called but the timers API is not mocked with fake timers. Call \`jest.useFakeTimers()\` in this test or enable fake timers globally by setting \`\\"timers\\": \\"fake\\"\` in the configuration file"`; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
all of these changes does not strictly have to be here, but it's needed when we actually start using Lolex. Why not land the changes now 🤷♂
The reason for this change is that
runAllImmediates
is not supported in the Lolex implementation