Skip to content

Instantly share code, notes, and snippets.

@Tallyb
Created August 11, 2023 05:32
Show Gist options
  • Save Tallyb/22188ea6dfa980ce3c03262e80294ffc to your computer and use it in GitHub Desktop.
Save Tallyb/22188ea6dfa980ce3c03262e80294ffc to your computer and use it in GitHub Desktop.
fake time fixture in playwright
import { test as base } from '@playwright/test';
const setFakeTime = async (dateTime: string, page: Page): Promise<void> => {
const fakeNow = new Date(dateTime).valueOf();
const setFakeTime = async (dateTime: string, page: Page): Promise<void> => {
const fakeNow = new Date(dateTime).valueOf();
await page.addInitScript(`{
// Extend Date constructor to default to fakeNow
Date = class extends Date {
constructor(...args) {
if (args.length === 0) {
super(${fakeNow});
} else {
super(...args);
}
}
}
// Override Date.now() to start from fakeNow
const __DateNowOffset = ${fakeNow} - Date.now();
const __DateNow = Date.now;
Date.now = () => __DateNow() + __DateNowOffset;
}`);
};
export const test = base.extend({
fakeTime?: string;
page: async ({ fakeTime, page }, use) => {
if (fakeTime) {
await setFakeTime(fakeTime, page);
}
await use(page);
},
});
// use it in your tests by specifying:
test.use({fakeTime: 'March 14 2022 13:37:11 UTC'});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment