Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override the browser date with puppeteer

I'm trying to setup puppeteer to run a few performance tests. I'd like to override the date to a specific value so that I can mock the data my app needs without needing to generate content dynamically based on the date.

How to override the date of the puppeteer browser?

like image 428
Rémi Gebski Avatar asked Jan 03 '23 17:01

Rémi Gebski


2 Answers

We found a much simpler way to mock out the date in puppeteer. Here is our example:

page.evaluate(() => {
  Date.now = () => {
    return 1539806611024;
  };
});
like image 110
athornburg Avatar answered Jan 13 '23 23:01

athornburg


I ended up having the same problem. This is how I managed to solve it:

// mock date of document
if (!page.dateIsMocked) {
    page.dateIsMocked = true
    await page.evaluateOnNewDocument(() => {
        var _Date = Date,
            _getTimezoneOffset = Date.prototype.getTimezoneOffset,
            now = null
        function MockDate(y, m, d, h, M, s, ms) {
            var date
            switch (arguments.length) {
                case 0:
                    if (now !== null) {
                        date = new _Date(now)
                    } else {
                        date = new _Date()
                    }
                    break
                case 1:
                    date = new _Date(y)
                    break
                default:
                    d = typeof d === 'undefined' ? 1 : d
                    h = h || 0
                    M = M || 0
                    s = s || 0
                    ms = ms || 0
                    date = new _Date(y, m, d, h, M, s, ms)
                    break
            }

            return date
        }
        MockDate.UTC = _Date.UTC
        MockDate.now = function() {
            return new MockDate().valueOf()
        }
        MockDate.parse = function(dateString) {
            return _Date.parse(dateString)
        }
        MockDate.toString = function() {
            return _Date.toString()
        }
        MockDate.prototype = _Date.prototype

        function set(date, timezoneOffset) {
            var dateObj = new Date(date)
            if (isNaN(dateObj.getTime())) {
                throw new TypeError(
                    'mockdate: The time set is an invalid date: ' + date
                )
            }
            if (typeof timezoneOffset === 'number') {
                MockDate.prototype.getTimezoneOffset = function() {
                    return timezoneOffset
                }
            }
            Date = MockDate
            now = dateObj.valueOf()
        }

        // mock date
        set(1577840400000)
    })
}

The actual logic for mocking the Date is borrowed from the MockDate library.

like image 33
gergof Avatar answered Jan 13 '23 22:01

gergof