Browse Source

test(ui): Add mock date test helpers, remove fake timers (#66342)

Scott Cooper 1 year ago
parent
commit
0bcfd64bbd

+ 3 - 2
static/app/components/modals/widgetViewerModal.spec.tsx

@@ -4,6 +4,7 @@ import {ProjectFixture} from 'sentry-fixture/project';
 
 import {initializeOrg} from 'sentry-test/initializeOrg';
 import {act, render, screen, userEvent, waitFor} from 'sentry-test/reactTestingLibrary';
+import {resetMockDate, setMockDate} from 'sentry-test/utils';
 
 import type {ModalRenderProps} from 'sentry/actionCreators/modal';
 import WidgetViewerModal from 'sentry/components/modals/widgetViewerModal';
@@ -1269,7 +1270,7 @@ describe('Modals -> WidgetViewerModal', function () {
       widgetType: WidgetType.RELEASE,
     };
     beforeEach(function () {
-      jest.useFakeTimers().setSystemTime(new Date('2022-08-02'));
+      setMockDate(new Date('2022-08-02'));
       metricsMock = MockApiClient.addMockResponse({
         url: '/organizations/org-slug/metrics/data/',
         body: MetricsTotalCountByReleaseIn24h(),
@@ -1281,7 +1282,7 @@ describe('Modals -> WidgetViewerModal', function () {
       });
     });
     afterEach(() => {
-      jest.useRealTimers();
+      resetMockDate();
     });
 
     it('does a sessions query', async function () {

+ 12 - 8
static/app/components/replays/playerDOMAlert.spec.tsx

@@ -1,20 +1,23 @@
-import {render, screen} from 'sentry-test/reactTestingLibrary';
+import {render, screen, waitFor} from 'sentry-test/reactTestingLibrary';
+import {resetMockDate, setMockDate} from 'sentry-test/utils';
 
 import localStorage from 'sentry/utils/localStorage';
 
 import PlayerDOMAlert from './playerDOMAlert';
 
 jest.mock('sentry/utils/localStorage');
-jest.useFakeTimers();
 
 const mockGetItem = jest.mocked(localStorage.getItem);
 
 const now = new Date('2020-01-01');
-jest.setSystemTime(now);
 
 describe('PlayerDOMAlert', () => {
   beforeEach(() => {
     mockGetItem.mockReset();
+    setMockDate(now);
+  });
+  afterEach(() => {
+    resetMockDate();
   });
 
   it('should render the alert when local storage key is not set', () => {
@@ -30,18 +33,19 @@ describe('PlayerDOMAlert', () => {
     expect(screen.queryByTestId('player-dom-alert')).not.toBeInTheDocument();
   });
 
-  it('should be dismissable', () => {
+  it('should be dismissable', async () => {
     render(<PlayerDOMAlert />);
 
     expect(screen.getByTestId('player-dom-alert')).toBeVisible();
 
     screen.getByLabelText('Close Alert').click();
-    jest.runAllTicks();
 
     expect(screen.queryByTestId('player-dom-alert')).not.toBeInTheDocument();
-    expect(localStorage.setItem).toHaveBeenCalledWith(
-      'replay-player-dom-alert-dismissed',
-      '"1577836800000"'
+    await waitFor(() =>
+      expect(localStorage.setItem).toHaveBeenCalledWith(
+        'replay-player-dom-alert-dismissed',
+        '"1577836800000"'
+      )
     );
   });
 });

+ 7 - 7
static/app/utils/metrics/index.spec.tsx

@@ -1,3 +1,5 @@
+import {resetMockDate, setMockDate} from 'sentry-test/utils';
+
 import type {MetricsOperation} from 'sentry/types';
 import {
   getAbsoluteDateTimeRange,
@@ -121,9 +123,11 @@ describe('isFormattedMQL', () => {
 });
 
 describe('getAbsoluteDateTimeRange', () => {
-  beforeAll(() => {
-    jest.useFakeTimers();
-    jest.setSystemTime(new Date('2024-01-01T00:00:00Z'));
+  beforeEach(() => {
+    setMockDate(new Date('2024-01-01T00:00:00Z'));
+  });
+  afterEach(() => {
+    resetMockDate();
   });
 
   it('should return the correct object with "start" and "end" when period is not provided', () => {
@@ -150,8 +154,4 @@ describe('getAbsoluteDateTimeRange', () => {
       end: '2024-01-01T00:00:00.000Z',
     });
   });
-
-  afterAll(() => {
-    jest.useRealTimers();
-  });
 });

+ 10 - 9
static/app/utils/useDismissAlert.spec.tsx

@@ -1,10 +1,10 @@
 import {reactHooks} from 'sentry-test/reactTestingLibrary';
+import {setMockDate} from 'sentry-test/utils';
 
 import localStorage from 'sentry/utils/localStorage';
 import useDismissAlert from 'sentry/utils/useDismissAlert';
 
 jest.mock('sentry/utils/localStorage');
-jest.useFakeTimers();
 
 const mockSetItem = jest.mocked(localStorage.setItem);
 const mockGetItem = jest.mocked(localStorage.getItem);
@@ -14,7 +14,7 @@ const now = new Date('2020-01-01');
 
 describe('useDismissAlert', () => {
   beforeEach(() => {
-    jest.setSystemTime(now);
+    setMockDate(now);
 
     mockSetItem.mockReset();
     mockGetItem.mockReset();
@@ -53,25 +53,26 @@ describe('useDismissAlert', () => {
     expect(result.current.isDismissed).toBeTruthy();
   });
 
-  it('should set the current timestamp into localstorage when an alert is dismissed', () => {
-    const {result} = reactHooks.renderHook(useDismissAlert, {
+  it('should set the current timestamp into localstorage when an alert is dismissed', async () => {
+    const {result, waitFor} = reactHooks.renderHook(useDismissAlert, {
       initialProps: {key},
     });
 
     reactHooks.act(() => {
       result.current.dismiss();
-      jest.runAllTicks();
     });
 
-    expect(mockSetItem).toHaveBeenCalledWith(
-      key,
-      JSON.stringify(now.getTime().toString())
+    await waitFor(() =>
+      expect(mockSetItem).toHaveBeenCalledWith(
+        key,
+        JSON.stringify(now.getTime().toString())
+      )
     );
   });
 
   it('should be dismissed if the timestamp in localStorage is older than the expiration', () => {
     const today = new Date('2020-01-01');
-    jest.setSystemTime(today);
+    setMockDate(today);
 
     // Dismissed on christmas
     const christmas = new Date('2019-12-25').getTime();

+ 6 - 6
static/app/views/alerts/rules/metric/details/utils.spec.tsx

@@ -1,18 +1,18 @@
-import MockDate from 'mockdate';
 import moment from 'moment';
 import {IncidentFixture} from 'sentry-fixture/incident';
 import {MetricRuleFixture} from 'sentry-fixture/metricRule';
 
+import {resetMockDate, setMockDate} from 'sentry-test/utils';
+
 import {buildMetricGraphDateRange} from 'sentry/views/alerts/rules/metric/details/utils';
 
 describe('buildMetricGraphDateRange', () => {
   const now = '2022-05-16T20:00:00';
-  beforeAll(() => {
-    MockDate.set(`${now}Z`);
+  beforeEach(() => {
+    setMockDate(new Date(`${now}Z`));
   });
-  afterAll(() => {
-    // reset mock date
-    MockDate.set(new Date(1508208080000));
+  afterEach(() => {
+    resetMockDate();
   });
 
   it('should use current date for an active alert', () => {

+ 8 - 7
static/app/views/dashboards/widgetBuilder/widgetBuilderDataset.spec.tsx

@@ -12,6 +12,7 @@ import {
   waitFor,
   within,
 } from 'sentry-test/reactTestingLibrary';
+import {resetMockDate, setMockDate} from 'sentry-test/utils';
 
 import ProjectsStore from 'sentry/stores/projectsStore';
 import TagStore from 'sentry/stores/tagStore';
@@ -270,7 +271,7 @@ describe('WidgetBuilder', function () {
   afterEach(function () {
     MockApiClient.clearMockResponses();
     jest.clearAllMocks();
-    jest.useRealTimers();
+    resetMockDate();
   });
 
   describe('Release Widgets', function () {
@@ -362,7 +363,7 @@ describe('WidgetBuilder', function () {
     });
 
     it('does not allow sort on tags except release', async function () {
-      jest.useFakeTimers().setSystemTime(new Date('2022-08-02'));
+      setMockDate(new Date('2022-08-02'));
       renderTestComponent();
 
       expect(
@@ -403,7 +404,7 @@ describe('WidgetBuilder', function () {
     });
 
     it('makes the appropriate sessions call', async function () {
-      jest.useFakeTimers().setSystemTime(new Date('2022-08-02'));
+      setMockDate(new Date('2022-08-02'));
       renderTestComponent();
 
       expect(
@@ -435,7 +436,7 @@ describe('WidgetBuilder', function () {
     });
 
     it('calls the session endpoint with the right limit', async function () {
-      jest.useFakeTimers().setSystemTime(new Date('2022-08-02'));
+      setMockDate(new Date('2022-08-02'));
       renderTestComponent();
 
       expect(
@@ -473,7 +474,7 @@ describe('WidgetBuilder', function () {
     });
 
     it('calls sessions api when session.status is selected as a groupby', async function () {
-      jest.useFakeTimers().setSystemTime(new Date('2022-08-02'));
+      setMockDate(new Date('2022-08-02'));
       renderTestComponent();
 
       expect(
@@ -532,7 +533,7 @@ describe('WidgetBuilder', function () {
     });
 
     it('sets widgetType to release', async function () {
-      jest.useFakeTimers().setSystemTime(new Date('2022-08-02'));
+      setMockDate(new Date('2022-08-02'));
       renderTestComponent();
 
       await userEvent.click(await screen.findByText('Releases (Sessions, Crash rates)'), {
@@ -604,7 +605,7 @@ describe('WidgetBuilder', function () {
     });
 
     it('adds a function when the only column chosen in a table is a tag', async function () {
-      jest.useFakeTimers().setSystemTime(new Date('2022-08-02'));
+      setMockDate(new Date('2022-08-02'));
       renderTestComponent();
 
       await userEvent.click(await screen.findByText('Releases (Sessions, Crash rates)'), {

+ 5 - 5
static/app/views/dashboards/widgetCard/releaseWidgetQueries.spec.tsx

@@ -6,6 +6,7 @@ import {SessionsFieldFixture} from 'sentry-fixture/sessions';
 
 import {initializeOrg} from 'sentry-test/initializeOrg';
 import {render, screen, waitFor} from 'sentry-test/reactTestingLibrary';
+import {resetMockDate, setMockDate} from 'sentry-test/utils';
 
 import {
   DashboardFilterKeys,
@@ -72,12 +73,15 @@ describe('Dashboards > ReleaseWidgetQueries', function () {
 
   const api = new MockApiClient();
 
+  beforeEach(function () {
+    setMockDate(new Date('2022-08-02'));
+  });
   afterEach(function () {
     MockApiClient.clearMockResponses();
+    resetMockDate();
   });
 
   it('can send chart requests', async function () {
-    jest.useFakeTimers().setSystemTime(new Date('2022-08-02'));
     const mock = MockApiClient.addMockResponse({
       url: '/organizations/org-slug/metrics/data/',
       body: MetricsFieldFixture(`session.all`),
@@ -459,7 +463,6 @@ describe('Dashboards > ReleaseWidgetQueries', function () {
   });
 
   it('can send table requests', async function () {
-    jest.useFakeTimers().setSystemTime(new Date('2022-08-02'));
     const mock = MockApiClient.addMockResponse({
       url: '/organizations/org-slug/metrics/data/',
       body: MetricsSessionUserCountByStatusByReleaseFixture(),
@@ -559,7 +562,6 @@ describe('Dashboards > ReleaseWidgetQueries', function () {
   });
 
   it('can send big number requests', async function () {
-    jest.useFakeTimers().setSystemTime(new Date('2022-08-02'));
     const mock = MockApiClient.addMockResponse({
       url: '/organizations/org-slug/metrics/data/',
       body: MetricsFieldFixture(`count_unique(sentry.sessions.user)`),
@@ -605,7 +607,6 @@ describe('Dashboards > ReleaseWidgetQueries', function () {
   });
 
   it('can send multiple API requests', function () {
-    jest.useFakeTimers().setSystemTime(new Date('2022-08-02'));
     const metricsMock = MockApiClient.addMockResponse({
       url: '/organizations/org-slug/metrics/data/',
       body: SessionsFieldFixture(`session.all`),
@@ -700,7 +701,6 @@ describe('Dashboards > ReleaseWidgetQueries', function () {
   });
 
   it('adjusts interval based on date window', function () {
-    jest.useFakeTimers().setSystemTime(new Date('2022-08-02'));
     const mock = MockApiClient.addMockResponse({
       url: '/organizations/org-slug/metrics/data/',
       body: SessionsFieldFixture(`session.all`),

+ 6 - 1
static/app/views/issueDetails/groupReplays/groupReplays.spec.tsx

@@ -22,6 +22,8 @@ type InitializeOrgProps = {
 };
 import {ReplayListFixture} from 'sentry-fixture/replayList';
 
+import {resetMockDate, setMockDate} from 'sentry-test/utils';
+
 const REPLAY_ID_1 = '346789a703f6454384f1de473b8b9fcc';
 const REPLAY_ID_2 = 'b05dae9b6be54d21a4d5ad9f8f02b780';
 
@@ -61,6 +63,9 @@ describe('GroupReplays', () => {
       body: [],
     });
   });
+  afterEach(() => {
+    resetMockDate();
+  });
 
   describe('Replay Feature Disabled', () => {
     const mockGroup = GroupFixture();
@@ -330,7 +335,7 @@ describe('GroupReplays', () => {
       });
 
       // Mock the system date to be 2022-09-28
-      jest.useFakeTimers().setSystemTime(new Date('Sep 28, 2022 11:29:13 PM UTC'));
+      setMockDate(new Date('Sep 28, 2022 11:29:13 PM UTC'));
 
       render(<GroupReplays group={mockGroup} />, {
         context: routerContext,

+ 3 - 1
static/app/views/performance/transactionSummary/transactionReplays/index.spec.tsx

@@ -3,6 +3,7 @@ import {ReplayListFixture} from 'sentry-fixture/replayList';
 
 import {initializeOrg} from 'sentry-test/initializeOrg';
 import {render, screen, waitFor} from 'sentry-test/reactTestingLibrary';
+import {resetMockDate, setMockDate} from 'sentry-test/utils';
 
 import ProjectsStore from 'sentry/stores/projectsStore';
 import {
@@ -126,6 +127,7 @@ describe('TransactionReplays', () => {
 
   afterEach(() => {
     MockApiClient.clearMockResponses();
+    resetMockDate();
   });
 
   it('should query the events endpoint for replayIds of a transaction', async () => {
@@ -239,7 +241,7 @@ describe('TransactionReplays', () => {
     });
 
     // Mock the system date to be 2022-09-28
-    jest.useFakeTimers().setSystemTime(new Date('Sep 28, 2022 11:29:13 PM UTC'));
+    setMockDate(new Date('Sep 28, 2022 11:29:13 PM UTC'));
 
     renderComponent();
 

+ 15 - 0
tests/js/sentry-test/utils.tsx

@@ -1,3 +1,5 @@
+import MockDate from 'mockdate';
+
 // Taken from https://stackoverflow.com/a/56859650/1015027
 function findTextWithMarkup(contentNode: null | Element, textMatch: string | RegExp) {
   const hasText = (node: Element): boolean => {
@@ -27,3 +29,16 @@ export function textWithMarkupMatcher(textMatch: string | RegExp) {
     return findTextWithMarkup(element, textMatch);
   };
 }
+
+export function setMockDate(date: Date | number) {
+  MockDate.set(date);
+}
+
+/**
+ * Mock (current) date to always be National Pasta Day
+ * 2017-10-17T02:41:20.000Z
+ */
+export function resetMockDate() {
+  const constantDate = new Date(1508208080000);
+  MockDate.set(constantDate);
+}

Some files were not shown because too many files changed in this diff