Commit 8ae398b8 authored by Paul Slaughter's avatar Paul Slaughter

Update useFakeDate to setup / teardown

- Also adds helper to watch when we are
  in a test execution. This way we can blow up
  if we are called in the wrong place.
parent 106479d0
......@@ -10,7 +10,7 @@ import TimeboxSummaryCards from 'ee/burndown_chart/components/timebox_summary_ca
import { useFakeDate } from 'helpers/fake_date';
import { day1, day2, day3, day4 } from '../mock_data';
function fakeDate({ date }) {
function useFakeDateFromDay({ date }) {
const [year, month, day] = date.split('-');
useFakeDate(year, month - 1, day);
......@@ -201,12 +201,12 @@ describe('burndown_chart', () => {
// some separate tests for the update function since it has a bunch of logic
describe('padSparseBurnupData function', () => {
useFakeDateFromDay(day4);
beforeEach(() => {
createComponent({
props: { startDate: day1.date, dueDate: day4.date },
});
fakeDate(day4);
});
it('pads data from startDate if no startDate values', () => {
......@@ -236,15 +236,17 @@ describe('burndown_chart', () => {
});
});
it('if dueDate is in the future, pad data up to current date using last existing value', () => {
fakeDate(day3);
describe('with day3', () => {
useFakeDateFromDay(day3);
const result = wrapper.vm.padSparseBurnupData([day1, day2]);
it('if dueDate is in the future, pad data up to current date using last existing value', () => {
const result = wrapper.vm.padSparseBurnupData([day1, day2]);
expect(result.length).toBe(3);
expect(result[2]).toEqual({
...day2,
date: day3.date,
expect(result.length).toBe(3);
expect(result[2]).toEqual({
...day2,
date: day3.date,
});
});
});
......
......@@ -47,8 +47,9 @@ describe('RotationsListSectionComponent', () => {
});
describe('when the timeframe includes today', () => {
useFakeDate(2021, 0, 14);
beforeEach(() => {
useFakeDate(2021, 0, 14);
createComponent();
});
......@@ -77,8 +78,9 @@ describe('RotationsListSectionComponent', () => {
});
describe('when the timeframe does not include today', () => {
useFakeDate(2021, 0, 31);
beforeEach(() => {
useFakeDate(2021, 0, 31);
createComponent();
});
......
......@@ -7,10 +7,14 @@ import * as dateTimeUtility from '~/lib/utils/datetime_utility';
describe('Schedule Common Mixins', () => {
// January 3rd, 2018
useFakeDate(2018, 0, 3);
const today = new Date();
let today;
let wrapper;
beforeEach(() => {
today = new Date();
});
const component = {
template: `<span></span>`,
props: {
......
......@@ -5,7 +5,9 @@ const RealDate = Date;
const isMocked = (val) => Boolean(val.mock);
const createFakeDateClass = (ctorDefault) => {
const createFakeDateClass = (ctorDefaultParam = []) => {
const ctorDefault = ctorDefaultParam.length ? ctorDefaultParam : DEFAULT_ARGS;
const FakeDate = new Proxy(RealDate, {
construct: (target, argArray) => {
const ctorArgs = argArray.length ? argArray : ctorDefault;
......@@ -39,20 +41,20 @@ const createFakeDateClass = (ctorDefault) => {
return FakeDate;
};
const useFakeDate = (...args) => {
const FakeDate = createFakeDateClass(args.length ? args : DEFAULT_ARGS);
const setGlobalDateToFakeDate = (...args) => {
const FakeDate = createFakeDateClass(args);
global.Date = FakeDate;
};
const useRealDate = () => {
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 = {
useFakeDate,
useRealDate,
DEFAULT_ARGS,
setGlobalDateToFakeDate,
setGlobalDateToRealDate,
createFakeDateClass,
RealDate,
};
import { createFakeDateClass, DEFAULT_ARGS, useRealDate } from './fake_date';
import { createFakeDateClass } from './fake_date';
describe('spec/helpers/fake_date', () => {
describe('createFakeDateClass', () => {
let FakeDate;
beforeAll(() => {
useRealDate();
});
beforeEach(() => {
FakeDate = createFakeDateClass(DEFAULT_ARGS);
FakeDate = createFakeDateClass();
});
it('should use default args', () => {
......
export * from './fake_date';
export * from './jest';
import { createJestExecutionWatcher } from '../jest_execution_watcher';
import { RealDate, createFakeDateClass } from './fake_date';
const throwInsideExecutionError = (fnName) => {
throw new Error(`Cannot call "${fnName}" during test execution (i.e. within "it", "beforeEach", "beforeAll", etc.).
Instead, please move the call to "${fnName}" inside the "describe" block itself.
describe('', () => {
+ ${fnName}();
it('', () => {
- ${fnName}();
})
})
`);
};
const isExecutingTest = createJestExecutionWatcher();
export const useDateInScope = (fnName, factory) => {
if (isExecutingTest()) {
throwInsideExecutionError(fnName);
}
let origDate;
beforeAll(() => {
origDate = global.Date;
global.Date = factory();
});
afterAll(() => {
global.Date = origDate;
});
};
export const useFakeDate = (...args) =>
useDateInScope('useFakeDate', () => createFakeDateClass(args));
export const useRealDate = () => useDateInScope('useRealDate', () => RealDate);
export const createJestExecutionWatcher = () => {
let isExecuting = false;
beforeAll(() => {
isExecuting = true;
});
afterAll(() => {
isExecuting = false;
});
return () => isExecuting;
};
......@@ -3,7 +3,6 @@ import { GlLineChart } from '@gitlab/ui/dist/charts';
import { GlAlert } from '@gitlab/ui';
import VueApollo from 'vue-apollo';
import createMockApollo from 'helpers/mock_apollo_helper';
import { useFakeDate } from 'helpers/fake_date';
import ProjectsAndGroupChart from '~/analytics/instance_statistics/components/projects_and_groups_chart.vue';
import ChartSkeletonLoader from '~/vue_shared/components/resizable_chart/skeleton_loader.vue';
import projectsQuery from '~/analytics/instance_statistics/graphql/queries/projects.query.graphql';
......@@ -45,8 +44,8 @@ describe('ProjectsAndGroupChart', () => {
return shallowMount(ProjectsAndGroupChart, {
props: {
startDate: useFakeDate(2020, 9, 26),
endDate: useFakeDate(2020, 10, 1),
startDate: new Date(2020, 9, 26),
endDate: new Date(2020, 10, 1),
totalDataPoints: mockCountsData2.length,
},
localVue,
......
......@@ -3,7 +3,6 @@ import { GlAreaChart } from '@gitlab/ui/dist/charts';
import { GlAlert } from '@gitlab/ui';
import VueApollo from 'vue-apollo';
import createMockApollo from 'helpers/mock_apollo_helper';
import { useFakeDate } from 'helpers/fake_date';
import UsersChart from '~/analytics/instance_statistics/components/users_chart.vue';
import ChartSkeletonLoader from '~/vue_shared/components/resizable_chart/skeleton_loader.vue';
import usersQuery from '~/analytics/instance_statistics/graphql/queries/users.query.graphql';
......@@ -31,8 +30,8 @@ describe('UsersChart', () => {
return shallowMount(UsersChart, {
props: {
startDate: useFakeDate(2020, 9, 26),
endDate: useFakeDate(2020, 10, 1),
startDate: new Date(2020, 9, 26),
endDate: new Date(2020, 10, 1),
totalDataPoints: mockCountsData2.length,
},
localVue,
......
......@@ -4,7 +4,7 @@ const path = require('path');
const { ErrorWithStack } = require('jest-util');
const JSDOMEnvironment = require('jest-environment-jsdom');
const { TEST_HOST } = require('./__helpers__/test_constants');
const { useFakeDate } = require('./__helpers__/fake_date');
const { setGlobalDateToFakeDate } = require('./__helpers__/fake_date/fake_date');
const ROOT_PATH = path.resolve(__dirname, '../..');
......@@ -13,8 +13,9 @@ class CustomEnvironment extends JSDOMEnvironment {
// Setup testURL so that window.location is setup properly
super({ ...config, testURL: TEST_HOST }, context);
// This lets jsdom use the fake date for things like document.cookie
useFakeDate();
// Fake the `Date` for `jsdom` which fixes things like document.cookie
// https://gitlab.com/gitlab-org/gitlab/-/merge_requests/39496#note_503084332
setGlobalDateToFakeDate();
Object.assign(context.console, {
error(...args) {
......
......@@ -3,6 +3,7 @@ import Vue from 'vue';
import { mountComponentWithStore } from 'helpers/vue_mount_component_helper';
import { useLocalStorageSpy } from 'helpers/local_storage_helper';
import waitForPromises from 'helpers/wait_for_promises';
import { useRealDate } from 'helpers/fake_date';
import axios from '~/lib/utils/axios_utils';
import appComponent from '~/frequent_items/components/app.vue';
import eventHub from '~/frequent_items/event_hub';
......@@ -93,23 +94,27 @@ describe('Frequent Items App Component', () => {
expect(projects.length).toBe(1);
});
it('should increase frequency of report if it was logged multiple times over the course of an hour', () => {
let projects;
const newTimestamp = Date.now() + HOUR_IN_MS + 1;
describe('with real date', () => {
useRealDate();
vm.logItemAccess(session.storageKey, session.project);
projects = JSON.parse(storage[session.storageKey]);
it('should increase frequency of report if it was logged multiple times over the course of an hour', () => {
let projects;
const newTimestamp = Date.now() + HOUR_IN_MS + 1;
expect(projects[0].frequency).toBe(1);
vm.logItemAccess(session.storageKey, session.project);
projects = JSON.parse(storage[session.storageKey]);
vm.logItemAccess(session.storageKey, {
...session.project,
lastAccessedOn: newTimestamp,
});
projects = JSON.parse(storage[session.storageKey]);
expect(projects[0].frequency).toBe(1);
expect(projects[0].frequency).toBe(2);
expect(projects[0].lastAccessedOn).not.toBe(session.project.lastAccessedOn);
vm.logItemAccess(session.storageKey, {
...session.project,
lastAccessedOn: newTimestamp,
});
projects = JSON.parse(storage[session.storageKey]);
expect(projects[0].frequency).toBe(2);
expect(projects[0].lastAccessedOn).not.toBe(session.project.lastAccessedOn);
});
});
it('should always update project metadata', () => {
......
......@@ -3,12 +3,12 @@ import 'jquery';
import * as jqueryMatchers from 'custom-jquery-matchers';
import { config as testUtilsConfig } from '@vue/test-utils';
import { setGlobalDateToFakeDate } from 'helpers/fake_date';
import Translate from '~/vue_shared/translate';
import { initializeTestTimeout } from './__helpers__/timeout';
import { getJSONFixture, loadHTMLFixture, setHTMLFixture } from './__helpers__/fixtures';
import { setupManualMocks } from './mocks/mocks_helper';
import customMatchers from './matchers';
import { useFakeDate } from './helpers/fake_date';
import './__helpers__/dom_shims';
import './__helpers__/jquery';
......@@ -21,6 +21,10 @@ process.on('unhandledRejection', global.promiseRejectionHandler);
setupManualMocks();
// Fake the `Date` for the rest of the jest spec runtime environment.
// https://gitlab.com/gitlab-org/gitlab/-/merge_requests/39496#note_503084332
setGlobalDateToFakeDate();
afterEach(() =>
// give Promises a bit more time so they fail the right test
new Promise(setImmediate).then(() => {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment