Skip to content
Snippets Groups Projects

Step 2 - Setup `useFakeDate` by default in Jest

Merged Paul Slaughter requested to merge 236004-use-fake-date-everywhere into master
All threads resolved!
Compare and Show latest version
1 file
+ 10
6
Compare changes
  • Side-by-side
  • Inline
@@ -6,24 +6,28 @@ const RealDate = Date;
@@ -6,24 +6,28 @@ const RealDate = Date;
const isMocked = val => Boolean(val.mock);
const isMocked = val => Boolean(val.mock);
export const createFakeDateClass = ctorDefault => {
export const createFakeDateClass = ctorDefault => {
const defaultDate = new RealDate(...ctorDefault);
const defaultApplyDate = RealDate(...ctorDefault);
const FakeDate = new Proxy(RealDate, {
const FakeDate = new Proxy(RealDate, {
construct: (target, argArray) => {
construct: (target, argArray) => {
return argArray.length ? new RealDate(...argArray) : defaultDate;
const ctorArgs = argArray.length ? argArray : ctorDefault;
 
 
return new RealDate(...ctorArgs);
},
},
apply: (target, thisArg, argArray) => {
apply: (target, thisArg, argArray) => {
return argArray.length ? RealDate(...argArray) : defaultApplyDate;
const ctorArgs = argArray.length ? argArray : ctorDefault;
 
 
return RealDate(...ctorArgs);
},
},
// We want to overwrite the default 'now', but only if it's not already mocked
// We want to overwrite the default 'now', but only if it's not already mocked
get: (target, prop) => {
get: (target, prop) => {
if (prop === 'now' && !isMocked(target[prop])) {
if (prop === 'now' && !isMocked(target[prop])) {
return () => defaultDate.getTime();
return () => new RealDate(...ctorDefault).getTime();
}
}
return target[prop];
return target[prop];
},
},
 
getPrototypeOf: target => {
 
return target.prototype;
 
},
// We need to be able to set props so that `jest.spyOn` will work.
// We need to be able to set props so that `jest.spyOn` will work.
set: (target, prop, value) => {
set: (target, prop, value) => {
// eslint-disable-next-line no-param-reassign
// eslint-disable-next-line no-param-reassign
Loading