Skip to content

Instantly share code, notes, and snippets.

@luckylooke
Last active July 22, 2022 13:53
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 luckylooke/ed812b6fe893d07bb7b22c8c6f3226e5 to your computer and use it in GitHub Desktop.
Save luckylooke/ed812b6fe893d07bb7b22c8c6f3226e5 to your computer and use it in GitHub Desktop.
fake Date in devTools for testing
// 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