Skip to content

Instantly share code, notes, and snippets.

@brookjordan
Created January 2, 2019 05:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brookjordan/bbe67a9455cceff2f628ea72f18bda38 to your computer and use it in GitHub Desktop.
Save brookjordan/bbe67a9455cceff2f628ea72f18bda38 to your computer and use it in GitHub Desktop.
Set the Date object to assume the current date to be a fixed date. Useful for testing.
function fixCurrentDate(dateString = 'Tue Jan 01 2019 00:00:00 GMT+0800') {
let RealDate;
// Make sure we keep a reference to the orginal `Date`
if (window.Date.isFake && window.Date.RealDate) {
RealDate = window.Date.RealDate;
} else {
RealDate = window.Date;
}
// If we're fixing the date we'll no doubt be using it,
// so we may as well cache it.
let fixedDate = new RealDate(dateString);
if (isNaN(+fixedDate)) { throw Error('Provided date string is invalid. `window.Date` was not modified.'); }
// The `Date` object is quite complex so let's just copy everything across
Object.assign(
FakeDate,
RealDate,
{
RealDate,
isFake: true,
// `now` is the only static function that we'll need to modify
now: fixedDate.getTime.bind(fixedDate),
revertToDynamicDate() {
window.Date = RealDate;
},
},
);
window.Date = FakeDate;
function FakeDate(...args) {
// We need to keep the functionality where
// if `Date` is called without `new` it returns a string.
if (new.target) {
if (args.length) {
return new RealDate(...args);
} else {
return fixedDate;
}
} else {
if (args.length) {
return RealDate(...args);
} else {
return fixedDate.toString();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment