diff options
author | GitLab Bot <gitlab-bot@gitlab.com> | 2021-02-18 13:34:06 +0300 |
---|---|---|
committer | GitLab Bot <gitlab-bot@gitlab.com> | 2021-02-18 13:34:06 +0300 |
commit | 859a6fb938bb9ee2a317c46dfa4fcc1af49608f0 (patch) | |
tree | d7f2700abe6b4ffcb2dcfc80631b2d87d0609239 /spec/frontend/__helpers__/fake_date/fake_date.js | |
parent | 446d496a6d000c73a304be52587cd9bbc7493136 (diff) |
Add latest changes from gitlab-org/gitlab@13-9-stable-eev13.9.0-rc42
Diffstat (limited to 'spec/frontend/__helpers__/fake_date/fake_date.js')
-rw-r--r-- | spec/frontend/__helpers__/fake_date/fake_date.js | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/spec/frontend/__helpers__/fake_date/fake_date.js b/spec/frontend/__helpers__/fake_date/fake_date.js new file mode 100644 index 00000000000..bc088ad96b6 --- /dev/null +++ b/spec/frontend/__helpers__/fake_date/fake_date.js @@ -0,0 +1,60 @@ +// Frida Kahlo's birthday (6 = July) +const DEFAULT_ARGS = [2020, 6, 6]; + +const RealDate = Date; + +const isMocked = (val) => Boolean(val.mock); + +const createFakeDateClass = (ctorDefaultParam = []) => { + const ctorDefault = ctorDefaultParam.length ? ctorDefaultParam : DEFAULT_ARGS; + + 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; + + return new RealDate(...ctorArgs).toString(); + }, + // 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]; + }, + getPrototypeOf: (target) => { + 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; +}; + +const setGlobalDateToFakeDate = (...args) => { + const FakeDate = createFakeDateClass(args); + global.Date = FakeDate; +}; + +const setGlobalDateToRealDate = () => { + global.Date = RealDate; +}; + +// 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, +}; |