Search code examples
javascriptplaywright

Can I set the date for playwright browser


When I write tests to run in playwright, I would like to be able to set the date that the browser believes it to be at the start of the test. Is there a way to achieve this using playwright?


Solution

  • Update (2024): Built-in support in Playwright

    From playwright v1.45.0 onward, we can use the new Clock API.

    await page.clock.setFixedTime(new Date('2024-02-02T10:00:00'));
    

    It also supports use cases like pausing and fast-forwarding times:

    // Initialize clock with some time before the test time and let the page load
    // naturally. `Date.now` will progress as the timers fire.
    await page.clock.install({ time: new Date('2024-02-02T08:00:00') });
    
    // Pretend that the user closed the laptop lid and opened it again at 10am,
    // Pause the time once reached that point.
    await page.clock.pauseAt(new Date('2024-02-02T10:00:00'));
    
    // Assert the page state.
    await expect(page.getByTestId('current-time')).toHaveText('2/2/2024, 10:00:00 AM');
    
    // Close the laptop lid again and open it at 10:30am.
    await page.clock.fastForward('30:00');
    

    See the clock guide for more details.