Skip to content

Commit

Permalink
Mock Date.now when using fake timers
Browse files Browse the repository at this point in the history
  • Loading branch information
fluiddot committed May 19, 2023
1 parent a0a1fd5 commit e418386
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions test/native/integration-test-helpers/with-fake-timers.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,18 @@ export async function withFakeTimers( fn ) {
jest.useFakeTimers( { legacyFakeTimers: true } );
}

// `Date.now` returns the real-time even when using fake timers.
// Some functions like `debounce` relies on the time returned by this function
// for its calculations, which can lead to wrong behaviors when executing timers.
// To avoid this, we mock this function and return the time provided Jest fake timers.
// Reference: https://jestjs.io/docs/jest-object#jestnow
let dateNowSpy;
if ( ! jest.isMockFunction( Date.now ) ) {
dateNowSpy = jest
.spyOn( Date, 'now' )
.mockImplementation( () => jest.now() );
}

const result = await fn();

if ( ! usingFakeTimers ) {
Expand All @@ -26,5 +38,9 @@ export async function withFakeTimers( fn ) {
global.requestAnimationFrame = requestAnimationFrameCopy;
global.cancelAnimationFrame = cancelAnimationFrameCopy;
}

if ( dateNowSpy ) {
dateNowSpy.mockRestore();
}
return result;
}

0 comments on commit e418386

Please sign in to comment.