Last active
July 22, 2022 13:53
-
-
Save luckylooke/ed812b6fe893d07bb7b22c8c6f3226e5 to your computer and use it in GitHub Desktop.
fake Date in devTools for testing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Context https://stackoverflow.com/a/72640597/861615 | |
// Save the original `Date` function | |
const OriginalDate = Date; | |
const fakeDateArgs = [2022, 5, 3]; // beware month is 0 based | |
let fakeDate; | |
// Replace it with our own | |
Date = function Date(...args) { | |
// Called via `new`? | |
if (!new.target) { | |
// No, just pass the call on | |
return OriginalDate(...args); | |
} | |
// Determine what constructor to call | |
const ctor = new.target === Date ? OriginalDate : new.target; | |
// Called via `new` | |
if (args.length !== 0) { | |
// Date constructor arguments were provided, just pass through | |
return Reflect.construct(ctor, args); | |
} | |
// It's a `new Date()` call, mock the date we want; in this | |
fakeDate = Reflect.construct(ctor, fakeDateArgs); | |
return fakeDate; | |
}; | |
// Make our replacement look like the original (which has `length = 7`) | |
// You can't assign to `length`, but you can redefine it | |
Object.defineProperty(Date, "length", { | |
value: OriginalDate.length, | |
configurable: true | |
}); | |
Object.defineProperty(Date, "now", { | |
value: () => fakeDate?.getTime(), | |
configurable: true | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment