Skip to content

Commit

Permalink
fix(clock): mock time in Event.prototype.timeStamp (microsoft#31986)
Browse files Browse the repository at this point in the history
Ideally we generate the timestamp when the Event gets created. This
patch adds a best-effort logic, since we can't override the constructor
of natively created events, e.g. `MouseEvent`.

Fixes microsoft#31924
  • Loading branch information
mxschmitt committed Aug 2, 2024
1 parent 878a6a4 commit d0c840f
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 0 deletions.
1 change: 1 addition & 0 deletions docs/src/clock.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ The recommended approach is to use `setFixedTime` to set the time to a specific
- `requestIdleCallback`
- `cancelIdleCallback`
- `performance`
- `Event.timeStamp`
:::

## Test with predefined time
Expand Down
8 changes: 8 additions & 0 deletions packages/playwright-core/src/server/injected/clock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -697,6 +697,14 @@ export function install(globalObject: WindowOrWorkerGlobalScope, config: Install
(globalObject as any).Intl = api[method]!;
} else if (method === 'performance') {
(globalObject as any).performance = api[method]!;
const kEventTimeStamp = Symbol('playwrightEventTimeStamp');
Object.defineProperty(Event.prototype, 'timeStamp', {
get() {
if (!this[kEventTimeStamp])
this[kEventTimeStamp] = api.performance?.now();
return this[kEventTimeStamp];
}
});
} else {
(globalObject as any)[method] = (...args: any[]) => {
return (api[method] as any).apply(api, args);
Expand Down
12 changes: 12 additions & 0 deletions tests/library/clock.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1060,6 +1060,18 @@ it.describe('stubTimers', () => {
expect(prev).toBe(0);
});

it('replace Event.prototype.timeStamp', async ({ install }) => {
it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/31924' });
const clock = install();
await clock.runFor(1000);
const event1 = new Event('foo');
expect(event1.timeStamp).toBe(1000);
await clock.runFor(1000);
const event2 = new Event('foo');
expect(event2.timeStamp).toBe(2000);
expect(event1.timeStamp).toBe(1000);
});

it('uninstalls global performance.now', async ({ install }) => {
const oldNow = performance.now;
const clock = install();
Expand Down

0 comments on commit d0c840f

Please sign in to comment.