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?

2 thoughts on “Can I set the date for playwright browser”

  1. You can use mocking tools like TimeShift.
    This piece of code would inject the timeshift library and then then the date to Feb 02 2012:

    const playwright = require("playwright");
    
    (async () => {
    
        let removed = false;
        const browser = await playwright["chromium"].launch({headless: false});
        const page = await browser.newPage();
        await page.setContent('<a href="#" onclick="document.querySelector(\'span\').innerText = new Date().toString()">Test me</a><span></span>');
        await page.click('a');
        console.log(await page.innerText('span'));
        await page.addScriptTag({ url: 'https://cdn.jsdelivr.net/npm/timeshift-js@1.1.1/timeshift.js'});
        await page.evaluate(() => {
            Date = TimeShift.Date; 
            TimeShift.setTime(1328230923000); 
        });
        await page.click('a');
        console.log(await page.innerText('span'));
        browser.close();
    })();
    

    Output:

    Fri Sep 18 2020 15:06:58 GMT-0300 (Argentina Standard Time)
    Thu Feb 02 2012 22:02:03 GMT-0300
    
    Reply

Leave a Comment