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?
We found a much simpler way to mock out the date in puppeteer. Here is our example:
page.evaluate(() => {
Date.now = () => {
return 1539806611024;
};
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With