2020-10-04 03:57:07 +05:30
|
|
|
// Frida Kahlo's birthday (6 = July)
|
2021-03-11 19:13:27 +05:30
|
|
|
const DEFAULT_ARGS = [2020, 6, 6];
|
2020-10-04 03:57:07 +05:30
|
|
|
|
|
|
|
const RealDate = Date;
|
|
|
|
|
2021-03-08 18:12:59 +05:30
|
|
|
const isMocked = (val) => Boolean(val.mock);
|
2020-10-04 03:57:07 +05:30
|
|
|
|
2021-03-11 19:13:27 +05:30
|
|
|
const createFakeDateClass = (ctorDefaultParam = []) => {
|
|
|
|
const ctorDefault = ctorDefaultParam.length ? ctorDefaultParam : DEFAULT_ARGS;
|
|
|
|
|
2020-10-04 03:57:07 +05:30
|
|
|
const FakeDate = new Proxy(RealDate, {
|
|
|
|
construct: (target, argArray) => {
|
|
|
|
const ctorArgs = argArray.length ? argArray : ctorDefault;
|
|
|
|
|
|
|
|
return new RealDate(...ctorArgs);
|
|
|
|
},
|
|
|
|
apply: (target, thisArg, argArray) => {
|
|
|
|
const ctorArgs = argArray.length ? argArray : ctorDefault;
|
|
|
|
|
2021-01-29 00:20:46 +05:30
|
|
|
return new RealDate(...ctorArgs).toString();
|
2020-10-04 03:57:07 +05:30
|
|
|
},
|
|
|
|
// We want to overwrite the default 'now', but only if it's not already mocked
|
|
|
|
get: (target, prop) => {
|
|
|
|
if (prop === 'now' && !isMocked(target[prop])) {
|
|
|
|
return () => new RealDate(...ctorDefault).getTime();
|
|
|
|
}
|
|
|
|
|
|
|
|
return target[prop];
|
|
|
|
},
|
2021-03-08 18:12:59 +05:30
|
|
|
getPrototypeOf: (target) => {
|
2020-10-04 03:57:07 +05:30
|
|
|
return target.prototype;
|
|
|
|
},
|
|
|
|
// We need to be able to set props so that `jest.spyOn` will work.
|
|
|
|
set: (target, prop, value) => {
|
|
|
|
// eslint-disable-next-line no-param-reassign
|
|
|
|
target[prop] = value;
|
|
|
|
return true;
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
return FakeDate;
|
|
|
|
};
|
|
|
|
|
2021-03-11 19:13:27 +05:30
|
|
|
const setGlobalDateToFakeDate = (...args) => {
|
|
|
|
const FakeDate = createFakeDateClass(args);
|
2020-10-04 03:57:07 +05:30
|
|
|
global.Date = FakeDate;
|
|
|
|
};
|
|
|
|
|
2021-03-11 19:13:27 +05:30
|
|
|
const setGlobalDateToRealDate = () => {
|
2020-10-04 03:57:07 +05:30
|
|
|
global.Date = RealDate;
|
|
|
|
};
|
2021-03-11 19:13:27 +05:30
|
|
|
|
|
|
|
// We use commonjs so that the test environment module can pick this up
|
|
|
|
// eslint-disable-next-line import/no-commonjs
|
|
|
|
module.exports = {
|
|
|
|
setGlobalDateToFakeDate,
|
|
|
|
setGlobalDateToRealDate,
|
|
|
|
createFakeDateClass,
|
|
|
|
RealDate,
|
|
|
|
};
|