Welcome to mirror list, hosted at ThFree Co, Russian Federation.

fake_date.js « fake_date « __helpers__ « frontend « spec - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: bc088ad96b64e0952c9a1877fa21d9047d78f739 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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,
};