Commit fbaa3c90 authored by Paul Slaughter's avatar Paul Slaughter

Fix specs for global useFakeDate

- There are some rare instances where it
  is still acceptable to useRealDate incl.
  Cookie.set and timezone mock library.

Update jest fake_date for rspec consistency
parent 8ae398b8
...@@ -2,12 +2,10 @@ import { GlAlert, GlDropdown, GlDropdownItem, GlModal } from '@gitlab/ui'; ...@@ -2,12 +2,10 @@ import { GlAlert, GlDropdown, GlDropdownItem, GlModal } from '@gitlab/ui';
import { shallowMount, createLocalVue } from '@vue/test-utils'; import { shallowMount, createLocalVue } from '@vue/test-utils';
import DownloadTestCoverage from 'ee/analytics/repository_analytics/components/download_test_coverage.vue'; import DownloadTestCoverage from 'ee/analytics/repository_analytics/components/download_test_coverage.vue';
import SelectProjectsDropdown from 'ee/analytics/repository_analytics/components/select_projects_dropdown.vue'; import SelectProjectsDropdown from 'ee/analytics/repository_analytics/components/select_projects_dropdown.vue';
import { useFakeDate } from 'helpers/fake_date';
const localVue = createLocalVue(); const localVue = createLocalVue();
describe('Download test coverage component', () => { describe('Download test coverage component', () => {
useFakeDate();
let wrapper; let wrapper;
const findCodeCoverageModalButton = () => const findCodeCoverageModalButton = () =>
...@@ -73,8 +71,6 @@ describe('Download test coverage component', () => { ...@@ -73,8 +71,6 @@ describe('Download test coverage component', () => {
}); });
describe('when selecting a project', () => { describe('when selecting a project', () => {
// Due to the fake_date helper, we can always expect today's date to be 2020-07-06
// and the default date 30 days ago to be 2020-06-06
const groupAnalyticsCoverageReportsPathWithDates = `${injectedProperties.groupAnalyticsCoverageReportsPath}?start_date=2020-06-06&end_date=2020-07-06`; const groupAnalyticsCoverageReportsPathWithDates = `${injectedProperties.groupAnalyticsCoverageReportsPath}?start_date=2020-06-06&end_date=2020-07-06`;
describe('with all projects selected', () => { describe('with all projects selected', () => {
......
...@@ -3,14 +3,12 @@ import { mount, createLocalVue } from '@vue/test-utils'; ...@@ -3,14 +3,12 @@ import { mount, createLocalVue } from '@vue/test-utils';
import VueApollo from 'vue-apollo'; import VueApollo from 'vue-apollo';
import TestCoverageSummary from 'ee/analytics/repository_analytics/components/test_coverage_summary.vue'; import TestCoverageSummary from 'ee/analytics/repository_analytics/components/test_coverage_summary.vue';
import getGroupTestCoverage from 'ee/analytics/repository_analytics/graphql/queries/get_group_test_coverage.query.graphql'; import getGroupTestCoverage from 'ee/analytics/repository_analytics/graphql/queries/get_group_test_coverage.query.graphql';
import { useFakeDate } from 'helpers/fake_date';
import createMockApollo from 'helpers/mock_apollo_helper'; import createMockApollo from 'helpers/mock_apollo_helper';
import waitForPromises from 'helpers/wait_for_promises'; import waitForPromises from 'helpers/wait_for_promises';
const localVue = createLocalVue(); const localVue = createLocalVue();
describe('Test coverage table component', () => { describe('Test coverage table component', () => {
useFakeDate();
let wrapper; let wrapper;
let fakeApollo; let fakeApollo;
......
import { GlDaterangePicker } from '@gitlab/ui'; import { GlDaterangePicker } from '@gitlab/ui';
import { mount } from '@vue/test-utils'; import { mount } from '@vue/test-utils';
import { useFakeDate } from 'helpers/fake_date';
import Daterange from 'ee/analytics/shared/components/daterange.vue'; import Daterange from 'ee/analytics/shared/components/daterange.vue';
const defaultProps = { const defaultProps = {
...@@ -8,6 +9,8 @@ const defaultProps = { ...@@ -8,6 +9,8 @@ const defaultProps = {
}; };
describe('Daterange component', () => { describe('Daterange component', () => {
useFakeDate(2019, 8, 25);
let wrapper; let wrapper;
const factory = (props = defaultProps) => { const factory = (props = defaultProps) => {
...@@ -19,10 +22,6 @@ describe('Daterange component', () => { ...@@ -19,10 +22,6 @@ describe('Daterange component', () => {
}); });
}; };
beforeEach(() => {
jest.spyOn(global.Date, 'now').mockImplementation(() => new Date('2019-09-25T00:00:00Z'));
});
afterEach(() => { afterEach(() => {
wrapper.destroy(); wrapper.destroy();
}); });
......
import dateFormat from 'dateformat'; import dateFormat from 'dateformat';
import timezoneMock from 'timezone-mock'; import timezoneMock from 'timezone-mock';
import BurndownChartData from 'ee/burndown_chart/burn_chart_data'; import BurndownChartData from 'ee/burndown_chart/burn_chart_data';
import { useFakeDate } from 'helpers/fake_date';
describe('BurndownChartData', () => { describe('BurndownChartData', () => {
const startDate = '2017-03-01'; const startDate = '2017-03-01';
...@@ -68,16 +69,7 @@ describe('BurndownChartData', () => { ...@@ -68,16 +69,7 @@ describe('BurndownChartData', () => {
}); });
describe('when viewing before due date', () => { describe('when viewing before due date', () => {
const realDateNow = Date.now; useFakeDate(2017, 2, 2);
beforeAll(() => {
const today = jest.fn(() => new Date(2017, 2, 2));
global.Date.now = today;
});
afterAll(() => {
global.Date.now = realDateNow;
});
it('counts until today if milestone due date > date today', () => { it('counts until today if milestone due date > date today', () => {
const chartData = burndownChartData.generateBurndownTimeseries(); const chartData = burndownChartData.generateBurndownTimeseries();
......
...@@ -236,10 +236,11 @@ describe('burndown_chart', () => { ...@@ -236,10 +236,11 @@ describe('burndown_chart', () => {
}); });
}); });
describe('with day3', () => { describe('when dueDate is in the future', () => {
// day3 is before the day4 we set to dueDate in the beforeEach
useFakeDateFromDay(day3); useFakeDateFromDay(day3);
it('if dueDate is in the future, pad data up to current date using last existing value', () => { it('pad data up to current date using last existing value', () => {
const result = wrapper.vm.padSparseBurnupData([day1, day2]); const result = wrapper.vm.padSparseBurnupData([day1, day2]);
expect(result.length).toBe(3); expect(result.length).toBe(3);
......
import { mount } from '@vue/test-utils'; import { mount } from '@vue/test-utils';
import EnvironmentAlert from 'ee/environments/components/environment_alert.vue'; import EnvironmentAlert from 'ee/environments/components/environment_alert.vue';
import SeverityBadge from 'ee/vue_shared/security_reports/components/severity_badge.vue'; import SeverityBadge from 'ee/vue_shared/security_reports/components/severity_badge.vue';
import { useFakeDate } from 'helpers/fake_date';
describe('Environment Alert', () => { describe('Environment Alert', () => {
let wrapper; let wrapper;
const DEFAULT_PROVIDE = { projectPath: 'test-org/test' }; const DEFAULT_PROVIDE = { projectPath: 'test-org/test' };
const DEFAULT_PROPS = { environment: { name: 'staging' } }; const DEFAULT_PROPS = { environment: { name: 'staging' } };
useFakeDate();
const factory = (props = {}, provide = {}) => { const factory = (props = {}, provide = {}) => {
wrapper = mount(EnvironmentAlert, { wrapper = mount(EnvironmentAlert, {
propsData: { propsData: {
......
...@@ -11,7 +11,8 @@ import { differenceInMilliseconds } from '~/lib/utils/datetime_utility'; ...@@ -11,7 +11,8 @@ import { differenceInMilliseconds } from '~/lib/utils/datetime_utility';
describe('GeoNodeLastUpdated', () => { describe('GeoNodeLastUpdated', () => {
let wrapper; let wrapper;
const staleStatusTime = differenceInMilliseconds(STATUS_DELAY_THRESHOLD_MS); // The threshold is exclusive so -1
const staleStatusTime = differenceInMilliseconds(STATUS_DELAY_THRESHOLD_MS) - 1;
const nonStaleStatusTime = new Date().getTime(); const nonStaleStatusTime = new Date().getTime();
const defaultProps = { const defaultProps = {
......
...@@ -4,7 +4,6 @@ import MockAdapter from 'axios-mock-adapter'; ...@@ -4,7 +4,6 @@ import MockAdapter from 'axios-mock-adapter';
import CsvExportButton, { import CsvExportButton, {
STORAGE_KEY, STORAGE_KEY,
} from 'ee/security_dashboard/components/csv_export_button.vue'; } from 'ee/security_dashboard/components/csv_export_button.vue';
import { useFakeDate } from 'helpers/fake_date';
import { TEST_HOST } from 'helpers/test_constants'; import { TEST_HOST } from 'helpers/test_constants';
import { deprecatedCreateFlash as createFlash } from '~/flash'; import { deprecatedCreateFlash as createFlash } from '~/flash';
import axios from '~/lib/utils/axios_utils'; import axios from '~/lib/utils/axios_utils';
...@@ -14,7 +13,6 @@ import statusCodes from '~/lib/utils/http_status'; ...@@ -14,7 +13,6 @@ import statusCodes from '~/lib/utils/http_status';
jest.mock('~/flash'); jest.mock('~/flash');
jest.mock('~/lib/utils/downloader'); jest.mock('~/lib/utils/downloader');
useFakeDate();
const mockReportDate = formatDate(new Date(), 'isoDateTime'); const mockReportDate = formatDate(new Date(), 'isoDateTime');
const vulnerabilitiesExportEndpoint = `${TEST_HOST}/vulnerability_findings.csv`; const vulnerabilitiesExportEndpoint = `${TEST_HOST}/vulnerability_findings.csv`;
......
import { shallowMount } from '@vue/test-utils'; import { shallowMount } from '@vue/test-utils';
import { useFakeDate } from 'helpers/fake_date';
import ExpiresAtField from '~/access_tokens/components/expires_at_field.vue'; import ExpiresAtField from '~/access_tokens/components/expires_at_field.vue';
describe('~/access_tokens/components/expires_at_field', () => { describe('~/access_tokens/components/expires_at_field', () => {
useFakeDate();
let wrapper; let wrapper;
const createComponent = () => { const createComponent = () => {
......
...@@ -69,7 +69,7 @@ describe('CompareDropdownLayout', () => { ...@@ -69,7 +69,7 @@ describe('CompareDropdownLayout', () => {
expect(findListItemsData()).toEqual([ expect(findListItemsData()).toEqual([
{ {
href: 'version/1', href: 'version/1',
text: 'version 1 (base) abcdef1 1 commit 2 years ago', text: 'version 1 (base) abcdef1 1 commit 1 year ago',
createdAt: TEST_CREATED_AT, createdAt: TEST_CREATED_AT,
isActive: true, isActive: true,
}, },
......
import { shallowMount } from '@vue/test-utils'; import { shallowMount } from '@vue/test-utils';
import { GlLink, GlLabel, GlIcon, GlFormCheckbox } from '@gitlab/ui'; import { GlLink, GlLabel, GlIcon, GlFormCheckbox } from '@gitlab/ui';
import { useFakeDate } from 'helpers/fake_date';
import IssuableItem from '~/issuable_list/components/issuable_item.vue'; import IssuableItem from '~/issuable_list/components/issuable_item.vue';
import IssuableAssignees from '~/vue_shared/components/issue/issue_assignees.vue'; import IssuableAssignees from '~/vue_shared/components/issue/issue_assignees.vue';
...@@ -19,6 +19,9 @@ const createComponent = ({ issuableSymbol = '#', issuable = mockIssuable, slots ...@@ -19,6 +19,9 @@ const createComponent = ({ issuableSymbol = '#', issuable = mockIssuable, slots
}); });
describe('IssuableItem', () => { describe('IssuableItem', () => {
// The mock data is dependent that this is after our default date
useFakeDate(2020, 11, 11);
const mockLabels = mockIssuable.labels.nodes; const mockLabels = mockIssuable.labels.nodes;
const mockAuthor = mockIssuable.author; const mockAuthor = mockIssuable.author;
const originalUrl = gon.gitlab_url; const originalUrl = gon.gitlab_url;
......
import { shallowMount } from '@vue/test-utils'; import { shallowMount } from '@vue/test-utils';
import { useFakeDate } from 'helpers/fake_date';
import IssuableBody from '~/issuable_show/components/issuable_body.vue'; import IssuableBody from '~/issuable_show/components/issuable_body.vue';
...@@ -35,6 +36,9 @@ const createComponent = (propsData = issuableBodyProps) => ...@@ -35,6 +36,9 @@ const createComponent = (propsData = issuableBodyProps) =>
}); });
describe('IssuableBody', () => { describe('IssuableBody', () => {
// Some assertions expect a date later than our default
useFakeDate(2020, 11, 11);
let wrapper; let wrapper;
beforeEach(() => { beforeEach(() => {
...@@ -98,11 +102,8 @@ describe('IssuableBody', () => { ...@@ -98,11 +102,8 @@ describe('IssuableBody', () => {
it('renders issuable edit info', () => { it('renders issuable edit info', () => {
const editedEl = wrapper.find('small'); const editedEl = wrapper.find('small');
const sanitizedText = editedEl.text().replace(/\n/g, ' ').replace(/\s+/g, ' ');
expect(sanitizedText).toContain('Edited'); expect(editedEl.text()).toMatchInterpolatedText('Edited 3 months ago by Administrator');
expect(sanitizedText).toContain('ago');
expect(sanitizedText).toContain(`by ${mockIssuable.updatedBy.name}`);
}); });
it('renders issuable-edit-form when `editFormVisible` prop is true', async () => { it('renders issuable-edit-form when `editFormVisible` prop is true', async () => {
......
...@@ -12,9 +12,15 @@ import { simpleIssue, testAssignees, testLabels } from '../issuable_list_test_da ...@@ -12,9 +12,15 @@ import { simpleIssue, testAssignees, testLabels } from '../issuable_list_test_da
jest.mock('~/user_popovers'); jest.mock('~/user_popovers');
const TEST_NOW = '2019-08-28T20:03:04.713Z'; const TODAY = new Date();
const TEST_MONTH_AGO = '2019-07-28';
const TEST_MONTH_LATER = '2019-09-30'; const createTestDateFromDelta = (timeDelta) =>
formatDate(new Date(TODAY.getTime() + timeDelta), 'yyyy-mm-dd');
// TODO: Encapsulate date helpers https://gitlab.com/gitlab-org/gitlab/-/issues/320883
const MONTHS_IN_MS = 1000 * 60 * 60 * 24 * 31;
const TEST_MONTH_AGO = createTestDateFromDelta(-MONTHS_IN_MS);
const TEST_MONTH_LATER = createTestDateFromDelta(MONTHS_IN_MS);
const DATE_FORMAT = 'mmm d, yyyy'; const DATE_FORMAT = 'mmm d, yyyy';
const TEST_USER_NAME = 'Tyler Durden'; const TEST_USER_NAME = 'Tyler Durden';
const TEST_BASE_URL = `${TEST_HOST}/issues`; const TEST_BASE_URL = `${TEST_HOST}/issues`;
...@@ -26,16 +32,8 @@ const TEST_MILESTONE = { ...@@ -26,16 +32,8 @@ const TEST_MILESTONE = {
const TEXT_CLOSED = 'CLOSED'; const TEXT_CLOSED = 'CLOSED';
const TEST_META_COUNT = 100; const TEST_META_COUNT = 100;
// Use FixedDate so that time sensitive info in snapshots don't fail
class FixedDate extends Date {
constructor(date = TEST_NOW) {
super(date);
}
}
describe('Issuable component', () => { describe('Issuable component', () => {
let issuable; let issuable;
let DateOrig;
let wrapper; let wrapper;
const factory = (props = {}, scopedLabelsAvailable = false) => { const factory = (props = {}, scopedLabelsAvailable = false) => {
...@@ -63,15 +61,6 @@ describe('Issuable component', () => { ...@@ -63,15 +61,6 @@ describe('Issuable component', () => {
wrapper = null; wrapper = null;
}); });
beforeAll(() => {
DateOrig = window.Date;
window.Date = FixedDate;
});
afterAll(() => {
window.Date = DateOrig;
});
const checkExists = (findFn) => () => findFn().exists(); const checkExists = (findFn) => () => findFn().exists();
const hasIcon = (iconName, iconWrapper = wrapper) => const hasIcon = (iconName, iconWrapper = wrapper) =>
iconWrapper.findAll(GlIcon).wrappers.some((icon) => icon.props('name') === iconName); iconWrapper.findAll(GlIcon).wrappers.some((icon) => icon.props('name') === iconName);
......
...@@ -8,19 +8,9 @@ import { convertObjectPropsToCamelCase } from '~/lib/utils/common_utils'; ...@@ -8,19 +8,9 @@ import { convertObjectPropsToCamelCase } from '~/lib/utils/common_utils';
const originalRelease = getJSONFixture('api/releases/release.json'); const originalRelease = getJSONFixture('api/releases/release.json');
const mockFutureDate = new Date(9999, 0, 0).toISOString(); // TODO: Encapsulate date helpers https://gitlab.com/gitlab-org/gitlab/-/issues/320883
let mockIsFutureRelease = false; const MONTHS_IN_MS = 1000 * 60 * 60 * 24 * 31;
const mockFutureDate = new Date(new Date().getTime() + MONTHS_IN_MS).toISOString();
jest.mock('~/vue_shared/mixins/timeago', () => ({
methods: {
timeFormatted() {
return mockIsFutureRelease ? 'in 1 month' : '7 fortnights ago';
},
tooltipTitle() {
return 'February 30, 2401';
},
},
}));
describe('Release block footer', () => { describe('Release block footer', () => {
let wrapper; let wrapper;
...@@ -44,7 +34,6 @@ describe('Release block footer', () => { ...@@ -44,7 +34,6 @@ describe('Release block footer', () => {
afterEach(() => { afterEach(() => {
wrapper.destroy(); wrapper.destroy();
wrapper = null; wrapper = null;
mockIsFutureRelease = false;
}); });
const commitInfoSection = () => wrapper.find('.js-commit-info'); const commitInfoSection = () => wrapper.find('.js-commit-info');
...@@ -88,7 +77,7 @@ describe('Release block footer', () => { ...@@ -88,7 +77,7 @@ describe('Release block footer', () => {
it('renders the author and creation time info', () => { it('renders the author and creation time info', () => {
expect(trimText(authorDateInfoSection().text())).toBe( expect(trimText(authorDateInfoSection().text())).toBe(
`Created 7 fortnights ago by ${release.author.username}`, `Created 1 year ago by ${release.author.username}`,
); );
}); });
...@@ -100,7 +89,6 @@ describe('Release block footer', () => { ...@@ -100,7 +89,6 @@ describe('Release block footer', () => {
describe('renders the author and creation time info with future release date', () => { describe('renders the author and creation time info with future release date', () => {
beforeEach(() => { beforeEach(() => {
mockIsFutureRelease = true;
factory({ releasedAt: mockFutureDate }); factory({ releasedAt: mockFutureDate });
}); });
...@@ -113,7 +101,6 @@ describe('Release block footer', () => { ...@@ -113,7 +101,6 @@ describe('Release block footer', () => {
describe('when the release date is in the future', () => { describe('when the release date is in the future', () => {
beforeEach(() => { beforeEach(() => {
mockIsFutureRelease = true;
factory({ releasedAt: mockFutureDate }); factory({ releasedAt: mockFutureDate });
}); });
...@@ -177,13 +164,12 @@ describe('Release block footer', () => { ...@@ -177,13 +164,12 @@ describe('Release block footer', () => {
beforeEach(() => factory({ author: undefined })); beforeEach(() => factory({ author: undefined }));
it('renders the release date without the author name', () => { it('renders the release date without the author name', () => {
expect(trimText(authorDateInfoSection().text())).toBe(`Created 7 fortnights ago`); expect(trimText(authorDateInfoSection().text())).toBe(`Created 1 year ago`);
}); });
}); });
describe('future release without any author info', () => { describe('future release without any author info', () => {
beforeEach(() => { beforeEach(() => {
mockIsFutureRelease = true;
factory({ author: undefined, releasedAt: mockFutureDate }); factory({ author: undefined, releasedAt: mockFutureDate });
}); });
......
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