import { datadogRum } from '@datadog/browser-rum'; import { act, render } from '@testing-library/react'; import { FC } from 'react'; import { BrowserRouter, useHistory } from 'react-router-dom'; import { HashRouting } from '../hash-routing'; jest.mock('@datadog/browser-rum'); function mockLocation(newLocation: { origin?: string; pathname?: string } | string) { const { origin = window.location.origin, pathname = window.location.pathname } = typeof newLocation === 'string' ? { pathname: newLocation } : newLocation; (window.location as any) = Object.assign(new URL(`${origin}${pathname}`), { assign: jest.fn(), reload: jest.fn(), }); } describe(`[datadog-rum] ${HashRouting.name}`, () => { let history: ReturnType; const subject = () => { const History: FC = () => { history = useHistory(); return null; }; return render( ); }; beforeEach(() => { jest.clearAllMocks(); mockLocation({ origin: 'https://go.servicetitan.com' }); }); describe('when location changes', () => { const location = '/billing/1'; const setup = (locations: string[] = []) => { const subjectResult = subject(); jest.mocked(datadogRum.startView).mockClear(); locations.forEach(currentLocation => act(() => history.push(currentLocation))); return subjectResult; }; test('notifies DataDog', () => { setup([location]); expect(datadogRum.startView).toHaveBeenCalledTimes(1); expect(datadogRum.startView).toHaveBeenCalledWith('/billing/{id}'); }); test('sends single notification for duplicate locations', () => { setup([location, location]); expect(datadogRum.startView).toHaveBeenCalledTimes(1); }); test('sends single notification for similar locations', () => { setup([location, '/billing/2']); expect(datadogRum.startView).toHaveBeenCalledTimes(1); }); test('sends no notification after unmount', () => { const { unmount } = setup(); unmount(); history.push(location); expect(datadogRum.startView).not.toHaveBeenCalled(); }); }); });