12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466 |
- import ReactEchartsCore from 'echarts-for-react/lib/core';
- import {initializeOrg} from 'sentry-test/initializeOrg';
- import {act, render, screen, userEvent, waitFor} from 'sentry-test/reactTestingLibrary';
- import {ModalRenderProps} from 'sentry/actionCreators/modal';
- import WidgetViewerModal from 'sentry/components/modals/widgetViewerModal';
- import MemberListStore from 'sentry/stores/memberListStore';
- import PageFiltersStore from 'sentry/stores/pageFiltersStore';
- import space from 'sentry/styles/space';
- import {Series} from 'sentry/types/echarts';
- import {TableDataWithTitle} from 'sentry/utils/discover/discoverQuery';
- import {
- DisplayType,
- Widget,
- WidgetQuery,
- WidgetType,
- } from 'sentry/views/dashboardsV2/types';
- jest.mock('echarts-for-react/lib/core', () => {
- return jest.fn(({style}) => {
- return <div style={{...style, background: 'green'}}>echarts mock</div>;
- });
- });
- jest.mock('sentry/components/tooltip', () => {
- return jest.fn(props => {
- return <div>{props.children}</div>;
- });
- });
- const stubEl = (props: {children?: React.ReactNode}) => <div>{props.children}</div>;
- let eventsMetaMock;
- const waitForMetaToHaveBeenCalled = async () => {
- await waitFor(() => {
- expect(eventsMetaMock).toHaveBeenCalled();
- });
- };
- async function renderModal({
- initialData: {organization, routerContext},
- widget,
- seriesData,
- tableData,
- pageLinks,
- }: {
- initialData: any;
- widget: any;
- pageLinks?: string;
- seriesData?: Series[];
- tableData?: TableDataWithTitle[];
- }) {
- const rendered = render(
- <div style={{padding: space(4)}}>
- <WidgetViewerModal
- Header={stubEl}
- Footer={stubEl as ModalRenderProps['Footer']}
- Body={stubEl as ModalRenderProps['Body']}
- CloseButton={stubEl}
- closeModal={() => undefined}
- organization={organization}
- widget={widget}
- onEdit={() => undefined}
- seriesData={seriesData}
- tableData={tableData}
- pageLinks={pageLinks}
- />
- </div>,
- {
- context: routerContext,
- organization,
- }
- );
- // Need to wait since WidgetViewerModal will make a request to events-meta
- // for total events count on mount
- if (widget.widgetType === WidgetType.DISCOVER) {
- await waitForMetaToHaveBeenCalled();
- }
- return rendered;
- }
- describe('Modals -> WidgetViewerModal', function () {
- let initialData, initialDataWithFlag;
- beforeEach(() => {
- initialData = initializeOrg({
- organization: {
- features: ['discover-query', 'widget-viewer-modal'],
- apdexThreshold: 400,
- },
- router: {
- location: {query: {}},
- },
- project: 1,
- projects: [],
- });
- initialDataWithFlag = {
- ...initialData,
- organization: {
- ...initialData.organization,
- features: [
- ...initialData.organization.features,
- 'discover-frontend-use-events-endpoint',
- ],
- },
- };
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/projects/',
- body: [],
- });
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/releases/',
- body: [],
- });
- eventsMetaMock = MockApiClient.addMockResponse({
- url: '/organizations/org-slug/events-meta/',
- body: {count: 33323612},
- });
- PageFiltersStore.init();
- PageFiltersStore.onInitializeUrlState(
- {
- projects: [1, 2],
- environments: ['prod', 'dev'],
- datetime: {start: null, end: null, period: '24h', utc: null},
- },
- new Set()
- );
- });
- afterEach(() => {
- MockApiClient.clearMockResponses();
- PageFiltersStore.teardown();
- });
- describe('Discover Widgets', function () {
- describe('Area Chart Widget', function () {
- let mockQuery: WidgetQuery;
- let additionalMockQuery: WidgetQuery;
- let mockWidget: Widget;
- function mockEventsv2() {
- return MockApiClient.addMockResponse({
- url: '/organizations/org-slug/eventsv2/',
- body: {
- data: [
- {
- title: '/organizations/:orgId/dashboards/',
- id: '1',
- count: 1,
- },
- ],
- meta: {
- title: 'string',
- id: 'string',
- count: 1,
- isMetricsData: false,
- },
- },
- });
- }
- function mockEvents() {
- return MockApiClient.addMockResponse({
- url: '/organizations/org-slug/events/',
- body: {
- data: [
- {
- title: '/organizations/:orgId/dashboards/',
- id: '1',
- count: 1,
- },
- ],
- meta: {
- fields: {
- title: 'string',
- id: 'string',
- count: 1,
- },
- isMetricsData: false,
- },
- },
- });
- }
- beforeEach(function () {
- mockQuery = {
- conditions: 'title:/organizations/:orgId/performance/summary/',
- fields: ['count()'],
- aggregates: ['count()'],
- columns: [],
- name: 'Query Name',
- orderby: '',
- };
- additionalMockQuery = {
- conditions: '',
- fields: ['count()'],
- aggregates: ['count()'],
- columns: [],
- name: 'Another Query Name',
- orderby: '',
- };
- mockWidget = {
- id: '1',
- title: 'Test Widget',
- displayType: DisplayType.AREA,
- interval: '5m',
- queries: [mockQuery, additionalMockQuery],
- widgetType: WidgetType.DISCOVER,
- };
- (ReactEchartsCore as jest.Mock).mockClear();
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/events-stats/',
- body: {
- data: [
- [[1646100000], [{count: 1}]],
- [[1646120000], [{count: 1}]],
- ],
- start: 1646100000,
- end: 1646120000,
- isMetricsData: false,
- },
- });
- });
- describe('with eventsv2', function () {
- it('renders Edit and Open buttons', async function () {
- mockEventsv2();
- await renderModal({initialData, widget: mockWidget});
- expect(screen.getByText('Edit Widget')).toBeInTheDocument();
- expect(screen.getByText('Open in Discover')).toBeInTheDocument();
- });
- it('renders updated table columns and orderby', async function () {
- const eventsv2Mock = mockEventsv2();
- await renderModal({initialData, widget: mockWidget});
- expect(screen.getByText('title')).toBeInTheDocument();
- expect(
- screen.getByText('/organizations/:orgId/dashboards/')
- ).toBeInTheDocument();
- expect(eventsv2Mock).toHaveBeenCalledWith(
- '/organizations/org-slug/eventsv2/',
- expect.objectContaining({
- query: expect.objectContaining({sort: ['-count()']}),
- })
- );
- });
- it('renders area chart', async function () {
- mockEventsv2();
- await renderModal({initialData, widget: mockWidget});
- expect(screen.getByText('echarts mock')).toBeInTheDocument();
- });
- it('renders Discover area chart widget viewer', async function () {
- mockEventsv2();
- const {container} = await renderModal({initialData, widget: mockWidget});
- expect(container).toSnapshot();
- });
- it('redirects user to Discover when clicking Open in Discover', async function () {
- mockEventsv2();
- await renderModal({initialData, widget: mockWidget});
- userEvent.click(screen.getByText('Open in Discover'));
- expect(initialData.router.push).toHaveBeenCalledWith(
- '/organizations/org-slug/discover/results/?environment=prod&environment=dev&field=count%28%29&name=Test%20Widget&project=1&project=2&query=title%3A%2Forganizations%2F%3AorgId%2Fperformance%2Fsummary%2F&statsPeriod=24h&yAxis=count%28%29'
- );
- });
- it('zooms into the selected time range', async function () {
- mockEventsv2();
- await renderModal({initialData, widget: mockWidget});
- act(() => {
- // Simulate dataZoom event on chart
- (ReactEchartsCore as jest.Mock).mock.calls[0][0].onEvents.datazoom(
- undefined,
- {
- getModel: () => {
- return {
- _payload: {
- batch: [{startValue: 1646100000000, endValue: 1646120000000}],
- },
- };
- },
- }
- );
- });
- expect(initialData.router.push).toHaveBeenCalledWith(
- expect.objectContaining({
- query: {
- viewerEnd: '2022-03-01T07:33:20',
- viewerStart: '2022-03-01T02:00:00',
- },
- })
- );
- });
- it('renders multiquery label and selector', async function () {
- mockEventsv2();
- await renderModal({initialData, widget: mockWidget});
- expect(
- screen.getByText(
- 'This widget was built with multiple queries. Table data can only be displayed for one query at a time. To edit any of the queries, edit the widget.'
- )
- ).toBeInTheDocument();
- expect(screen.getByText('Query Name')).toBeInTheDocument();
- });
- it('updates selected query when selected in the query dropdown', async function () {
- mockEventsv2();
- const {rerender} = await renderModal({initialData, widget: mockWidget});
- userEvent.click(screen.getByText('Query Name'));
- userEvent.click(screen.getByText('Another Query Name'));
- expect(initialData.router.replace).toHaveBeenCalledWith({
- query: {query: 1},
- });
- // Need to manually set the new router location and rerender to simulate the dropdown selection click
- initialData.router.location.query = {query: ['1']};
- rerender(
- <WidgetViewerModal
- Header={stubEl}
- Footer={stubEl as ModalRenderProps['Footer']}
- Body={stubEl as ModalRenderProps['Body']}
- CloseButton={stubEl}
- closeModal={() => undefined}
- organization={initialData.organization}
- widget={mockWidget}
- onEdit={() => undefined}
- />
- );
- await waitForMetaToHaveBeenCalled();
- expect(screen.getByText('Another Query Name')).toBeInTheDocument();
- });
- it('renders the correct discover query link when there are multiple queries in a widget', async function () {
- mockEventsv2();
- initialData.router.location.query = {query: ['1']};
- await renderModal({initialData, widget: mockWidget});
- expect(screen.getByRole('button', {name: 'Open in Discover'})).toHaveAttribute(
- 'href',
- '/organizations/org-slug/discover/results/?environment=prod&environment=dev&field=count%28%29&name=Test%20Widget&project=1&project=2&query=&statsPeriod=24h&yAxis=count%28%29'
- );
- });
- it('renders with first legend disabled by default', async function () {
- mockEventsv2();
- // Rerender with first legend disabled
- initialData.router.location.query = {legend: ['Query Name']};
- await renderModal({initialData, widget: mockWidget});
- expect(ReactEchartsCore).toHaveBeenLastCalledWith(
- expect.objectContaining({
- option: expect.objectContaining({
- legend: expect.objectContaining({
- selected: {'Query Name': false},
- }),
- }),
- }),
- {}
- );
- });
- it('renders total results in footer', async function () {
- mockEventsv2();
- await renderModal({initialData, widget: mockWidget});
- expect(screen.getByText('33,323,612')).toBeInTheDocument();
- });
- it('renders highlighted query text and multiple queries in select dropdown', async function () {
- mockEventsv2();
- const {container} = await renderModal({
- initialData,
- widget: {
- ...mockWidget,
- queries: [{...mockQuery, name: ''}, additionalMockQuery],
- },
- });
- userEvent.click(screen.getByText('/organizations/:orgId/performance/summary/'));
- expect(container).toSnapshot();
- });
- it('renders widget chart minimap', async function () {
- initialData.organization.features.push('widget-viewer-modal-minimap');
- mockEventsv2();
- await renderModal({
- initialData,
- widget: {
- ...mockWidget,
- queries: [{...mockQuery, name: ''}, additionalMockQuery],
- },
- });
- expect(ReactEchartsCore).toHaveBeenLastCalledWith(
- expect.objectContaining({
- option: expect.objectContaining({
- dataZoom: expect.arrayContaining([
- expect.objectContaining({
- realtime: false,
- showDetail: false,
- end: 100,
- start: 0,
- }),
- ]),
- }),
- }),
- {}
- );
- });
- it('zooming on minimap updates location query and updates echart start and end values', async function () {
- initialData.organization.features.push('widget-viewer-modal-minimap');
- mockEventsv2();
- await renderModal({
- initialData,
- widget: {
- ...mockWidget,
- queries: [{...mockQuery, name: ''}, additionalMockQuery],
- },
- });
- const calls = (ReactEchartsCore as jest.Mock).mock.calls;
- act(() => {
- // Simulate dataZoom event on chart
- calls[calls.length - 1][0].onEvents.datazoom(
- {seriesStart: 1646100000000, seriesEnd: 1646120000000},
- {
- getModel: () => {
- return {
- _payload: {start: 30, end: 70},
- };
- },
- }
- );
- });
- expect(initialData.router.push).toHaveBeenCalledWith(
- expect.objectContaining({
- query: {
- viewerEnd: '2022-03-01T05:53:20',
- viewerStart: '2022-03-01T03:40:00',
- },
- })
- );
- });
- it('includes group by in widget viewer table', async function () {
- mockEventsv2();
- mockWidget.queries = [
- {
- conditions: 'title:/organizations/:orgId/performance/summary/',
- fields: ['count()'],
- aggregates: ['count()'],
- columns: ['transaction'],
- name: 'Query Name',
- orderby: '-count()',
- },
- ];
- await renderModal({initialData, widget: mockWidget});
- screen.getByText('transaction');
- });
- it('includes order by in widget viewer table if not explicitly selected', async function () {
- mockEventsv2();
- mockWidget.queries = [
- {
- conditions: 'title:/organizations/:orgId/performance/summary/',
- fields: ['count()'],
- aggregates: ['count()'],
- columns: ['transaction'],
- name: 'Query Name',
- orderby: 'count_unique(user)',
- },
- ];
- await renderModal({initialData, widget: mockWidget});
- screen.getByText('count_unique(user)');
- });
- it('includes a custom equation order by in widget viewer table if not explicitly selected', async function () {
- mockEventsv2();
- mockWidget.queries = [
- {
- conditions: 'title:/organizations/:orgId/performance/summary/',
- fields: ['count()'],
- aggregates: ['count()'],
- columns: ['transaction'],
- name: 'Query Name',
- orderby: '-equation|count_unique(user) + 1',
- },
- ];
- await renderModal({initialData, widget: mockWidget});
- screen.getByText('count_unique(user) + 1');
- });
- });
- describe('with events', function () {
- it('renders updated table columns and orderby', async function () {
- const eventsMock = mockEvents();
- await renderModal({initialData: initialDataWithFlag, widget: mockWidget});
- expect(screen.getByText('title')).toBeInTheDocument();
- expect(
- screen.getByText('/organizations/:orgId/dashboards/')
- ).toBeInTheDocument();
- expect(eventsMock).toHaveBeenCalledWith(
- '/organizations/org-slug/events/',
- expect.objectContaining({
- query: expect.objectContaining({sort: ['-count()']}),
- })
- );
- });
- });
- });
- describe('TopN Chart Widget', function () {
- let mockQuery, mockWidget;
- function mockEventsStats() {
- return MockApiClient.addMockResponse({
- url: '/organizations/org-slug/events-stats/',
- body: {
- data: [
- [[1646100000], [{count: 1}]],
- [[1646120000], [{count: 1}]],
- ],
- start: 1646100000,
- end: 1646120000,
- isMetricsData: false,
- },
- });
- }
- const eventsMockData = [
- {
- 'error.type': ['Test Error 1a', 'Test Error 1b', 'Test Error 1c'],
- count: 10,
- },
- {
- 'error.type': ['Test Error 2'],
- count: 6,
- },
- {
- 'error.type': ['Test Error 3'],
- count: 5,
- },
- {
- 'error.type': ['Test Error 4'],
- count: 4,
- },
- {
- 'error.type': ['Test Error 5'],
- count: 3,
- },
- {
- 'error.type': ['Test Error 6'],
- count: 2,
- },
- ];
- function mockEventsv2() {
- return MockApiClient.addMockResponse({
- url: '/organizations/org-slug/eventsv2/',
- match: [MockApiClient.matchQuery({cursor: undefined})],
- headers: {
- Link:
- '<http://localhost/api/0/organizations/org-slug/eventsv2/?cursor=0:0:1>; rel="previous"; results="false"; cursor="0:0:1",' +
- '<http://localhost/api/0/organizations/org-slug/eventsv2/?cursor=0:10:0>; rel="next"; results="true"; cursor="0:10:0"',
- },
- body: {
- data: eventsMockData,
- meta: {
- 'error.type': 'array',
- count: 'integer',
- },
- },
- });
- }
- function mockEvents() {
- return MockApiClient.addMockResponse({
- url: '/organizations/org-slug/events/',
- match: [MockApiClient.matchQuery({cursor: undefined})],
- headers: {
- Link:
- '<http://localhost/api/0/organizations/org-slug/eventsv2/?cursor=0:0:1>; rel="previous"; results="false"; cursor="0:0:1",' +
- '<http://localhost/api/0/organizations/org-slug/eventsv2/?cursor=0:10:0>; rel="next"; results="true"; cursor="0:10:0"',
- },
- body: {
- data: eventsMockData,
- meta: {
- fields: {
- 'error.type': 'array',
- count: 'integer',
- },
- },
- },
- });
- }
- beforeEach(function () {
- mockQuery = {
- conditions: 'title:/organizations/:orgId/performance/summary/',
- fields: ['error.type', 'count()'],
- aggregates: ['count()'],
- columns: ['error.type'],
- id: '1',
- name: 'Query Name',
- orderby: '',
- };
- mockWidget = {
- title: 'Test Widget',
- displayType: DisplayType.TOP_N,
- interval: '5m',
- queries: [mockQuery],
- widgetType: WidgetType.DISCOVER,
- };
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/eventsv2/',
- match: [MockApiClient.matchQuery({cursor: '0:10:0'})],
- headers: {
- Link:
- '<http://localhost/api/0/organizations/org-slug/eventsv2/?cursor=0:0:1>; rel="previous"; results="false"; cursor="0:0:1",' +
- '<http://localhost/api/0/organizations/org-slug/eventsv2/?cursor=0:20:0>; rel="next"; results="true"; cursor="0:20:0"',
- },
- body: {
- data: [
- {
- 'error.type': ['Next Page Test Error'],
- count: 1,
- },
- ],
- meta: {
- 'error.type': 'array',
- count: 'integer',
- },
- },
- });
- });
- describe('with eventsv2', function () {
- it('renders Discover topn chart widget viewer', async function () {
- mockEventsStats();
- mockEventsv2();
- const {container} = await renderModal({initialData, widget: mockWidget});
- expect(container).toSnapshot();
- });
- it('sorts table when a sortable column header is clicked', async function () {
- const eventsStatsMock = mockEventsStats();
- const eventsv2Mock = mockEventsv2();
- const {rerender} = await renderModal({initialData, widget: mockWidget});
- userEvent.click(screen.getByText('count()'));
- expect(initialData.router.push).toHaveBeenCalledWith({
- query: {sort: ['-count()']},
- });
- // Need to manually set the new router location and rerender to simulate the sortable column click
- initialData.router.location.query = {sort: ['-count()']};
- rerender(
- <WidgetViewerModal
- Header={stubEl}
- Footer={stubEl as ModalRenderProps['Footer']}
- Body={stubEl as ModalRenderProps['Body']}
- CloseButton={stubEl}
- closeModal={() => undefined}
- organization={initialData.organization}
- widget={mockWidget}
- onEdit={() => undefined}
- />
- );
- await waitForMetaToHaveBeenCalled();
- expect(eventsv2Mock).toHaveBeenCalledWith(
- '/organizations/org-slug/eventsv2/',
- expect.objectContaining({
- query: expect.objectContaining({sort: ['-count()']}),
- })
- );
- expect(eventsStatsMock).toHaveBeenCalledWith(
- '/organizations/org-slug/events-stats/',
- expect.objectContaining({
- query: expect.objectContaining({orderby: '-count()'}),
- })
- );
- });
- it('renders pagination buttons', async function () {
- mockEventsStats();
- mockEventsv2();
- await renderModal({initialData, widget: mockWidget});
- expect(screen.getByRole('button', {name: 'Previous'})).toBeInTheDocument();
- expect(screen.getByRole('button', {name: 'Next'})).toBeInTheDocument();
- });
- it('does not render pagination buttons', async function () {
- mockEventsStats();
- mockEventsv2();
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/eventsv2/',
- headers: {
- Link:
- '<http://localhost/api/0/organizations/org-slug/eventsv2/?cursor=0:0:1>; rel="previous"; results="false"; cursor="0:0:1",' +
- '<http://localhost/api/0/organizations/org-slug/eventsv2/?cursor=0:20:0>; rel="next"; results="false"; cursor="0:20:0"',
- },
- body: {
- data: [
- {
- 'error.type': ['No Pagination'],
- count: 1,
- },
- ],
- meta: {
- 'error.type': 'array',
- count: 'integer',
- },
- },
- });
- await renderModal({initialData, widget: mockWidget});
- expect(
- screen.queryByRole('button', {name: 'Previous'})
- ).not.toBeInTheDocument();
- expect(screen.queryByRole('button', {name: 'Next'})).not.toBeInTheDocument();
- });
- it('paginates to the next page', async function () {
- mockEventsStats();
- mockEventsv2();
- const {rerender} = await renderModal({initialData, widget: mockWidget});
- expect(screen.getByText('Test Error 1c')).toBeInTheDocument();
- userEvent.click(screen.getByRole('button', {name: 'Next'}));
- expect(initialData.router.replace).toHaveBeenCalledWith(
- expect.objectContaining({
- query: {cursor: '0:10:0'},
- })
- );
- // Need to manually set the new router location and rerender to simulate the next page click
- initialData.router.location.query = {cursor: ['0:10:0']};
- rerender(
- <WidgetViewerModal
- Header={stubEl}
- Footer={stubEl as ModalRenderProps['Footer']}
- Body={stubEl as ModalRenderProps['Body']}
- CloseButton={stubEl}
- closeModal={() => undefined}
- organization={initialData.organization}
- widget={mockWidget}
- onEdit={() => undefined}
- />
- );
- await waitForMetaToHaveBeenCalled();
- expect(await screen.findByText('Next Page Test Error')).toBeInTheDocument();
- });
- it('uses provided seriesData and does not make an events-stats requests', async function () {
- const eventsStatsMock = mockEventsStats();
- mockEventsv2();
- await renderModal({initialData, widget: mockWidget, seriesData: []});
- expect(eventsStatsMock).not.toHaveBeenCalled();
- });
- it('makes events-stats requests when table is sorted', async function () {
- const eventsStatsMock = mockEventsStats();
- mockEventsv2();
- await renderModal({
- initialData,
- widget: mockWidget,
- seriesData: [],
- });
- expect(eventsStatsMock).not.toHaveBeenCalled();
- userEvent.click(screen.getByText('count()'));
- await waitForMetaToHaveBeenCalled();
- expect(eventsStatsMock).toHaveBeenCalledTimes(1);
- });
- it('renders widget chart minimap', async function () {
- mockEventsStats();
- mockEventsv2();
- initialData.organization.features.push('widget-viewer-modal-minimap');
- await renderModal({initialData, widget: mockWidget});
- expect(ReactEchartsCore).toHaveBeenLastCalledWith(
- expect.objectContaining({
- option: expect.objectContaining({
- dataZoom: expect.arrayContaining([
- expect.objectContaining({
- realtime: false,
- showDetail: false,
- end: 100,
- start: 0,
- }),
- ]),
- }),
- }),
- {}
- );
- });
- it('zooming on minimap updates location query and updates echart start and end values', async function () {
- mockEventsStats();
- mockEventsv2();
- initialData.organization.features.push('widget-viewer-modal-minimap');
- await renderModal({initialData, widget: mockWidget});
- const calls = (ReactEchartsCore as jest.Mock).mock.calls;
- act(() => {
- // Simulate dataZoom event on chart
- calls[calls.length - 1][0].onEvents.datazoom(
- {seriesStart: 1646100000000, seriesEnd: 1646120000000},
- {
- getModel: () => {
- return {
- _payload: {start: 30, end: 70},
- };
- },
- }
- );
- });
- expect(initialData.router.push).toHaveBeenCalledWith(
- expect.objectContaining({
- query: {
- viewerEnd: '2022-03-01T05:53:20',
- viewerStart: '2022-03-01T03:40:00',
- },
- })
- );
- await waitFor(() => {
- expect(ReactEchartsCore).toHaveBeenLastCalledWith(
- expect.objectContaining({
- option: expect.objectContaining({
- dataZoom: expect.arrayContaining([
- expect.objectContaining({
- realtime: false,
- showDetail: false,
- endValue: 1646114000000,
- startValue: 1646106000000,
- }),
- ]),
- }),
- }),
- {}
- );
- });
- });
- });
- describe('with events', function () {
- it('sorts table when a sortable column header is clicked', async function () {
- const eventsStatsMock = mockEventsStats();
- const eventsMock = mockEvents();
- const {rerender} = await renderModal({
- initialData: initialDataWithFlag,
- widget: mockWidget,
- });
- userEvent.click(screen.getByText('count()'));
- expect(initialDataWithFlag.router.push).toHaveBeenCalledWith({
- query: {sort: ['-count()']},
- });
- // Need to manually set the new router location and rerender to simulate the sortable column click
- initialDataWithFlag.router.location.query = {sort: ['-count()']};
- rerender(
- <WidgetViewerModal
- Header={stubEl}
- Footer={stubEl as ModalRenderProps['Footer']}
- Body={stubEl as ModalRenderProps['Body']}
- CloseButton={stubEl}
- closeModal={() => undefined}
- organization={initialDataWithFlag.organization}
- widget={mockWidget}
- onEdit={() => undefined}
- />
- );
- await waitForMetaToHaveBeenCalled();
- expect(eventsMock).toHaveBeenCalledWith(
- '/organizations/org-slug/events/',
- expect.objectContaining({
- query: expect.objectContaining({sort: ['-count()']}),
- })
- );
- expect(eventsStatsMock).toHaveBeenCalledWith(
- '/organizations/org-slug/events-stats/',
- expect.objectContaining({
- query: expect.objectContaining({orderby: '-count()'}),
- })
- );
- });
- });
- });
- describe('World Map Chart Widget', function () {
- let mockQuery, mockWidget;
- const eventsMockData = [
- {
- 'geo.country_code': 'ES',
- p75_measurements_lcp: 2000,
- },
- {
- 'geo.country_code': 'SK',
- p75_measurements_lcp: 3000,
- },
- {
- 'geo.country_code': 'CO',
- p75_measurements_lcp: 4000,
- },
- ];
- function mockEventsGeo() {
- return MockApiClient.addMockResponse({
- url: '/organizations/org-slug/events-geo/',
- body: {
- data: eventsMockData,
- meta: {
- 'geo.country_code': 'string',
- p75_measurements_lcp: 'duration',
- },
- },
- });
- }
- function mockEventsv2() {
- return MockApiClient.addMockResponse({
- url: '/organizations/org-slug/eventsv2/',
- body: {
- data: eventsMockData,
- meta: {
- 'geo.country_code': 'string',
- p75_measurements_lcp: 'duration',
- },
- },
- });
- }
- function mockEvents() {
- return MockApiClient.addMockResponse({
- url: '/organizations/org-slug/events/',
- body: {
- data: eventsMockData,
- meta: {
- fields: {
- 'geo.country_code': 'string',
- p75_measurements_lcp: 'duration',
- },
- },
- },
- });
- }
- beforeEach(function () {
- mockQuery = {
- conditions: 'title:/organizations/:orgId/performance/summary/',
- fields: ['p75(measurements.lcp)'],
- aggregates: ['p75(measurements.lcp)'],
- columns: [],
- id: '1',
- name: 'Query Name',
- orderby: '',
- };
- mockWidget = {
- title: 'Test Widget',
- displayType: DisplayType.WORLD_MAP,
- interval: '5m',
- queries: [mockQuery],
- widgetType: WidgetType.DISCOVER,
- };
- });
- describe('with eventsv2', function () {
- it('always queries geo.country_code in the table chart', async function () {
- const eventsv2Mock = mockEventsv2();
- mockEventsGeo();
- await renderModal({initialData, widget: mockWidget});
- expect(eventsv2Mock).toHaveBeenCalledWith(
- '/organizations/org-slug/eventsv2/',
- expect.objectContaining({
- query: expect.objectContaining({
- field: ['geo.country_code', 'p75(measurements.lcp)'],
- }),
- })
- );
- expect(await screen.findByText('geo.country_code')).toBeInTheDocument();
- });
- it('renders Discover topn chart widget viewer', async function () {
- mockEventsv2();
- mockEventsGeo();
- const {container} = await renderModal({initialData, widget: mockWidget});
- expect(container).toSnapshot();
- });
- it('uses provided tableData and does not make an eventsv2 requests', async function () {
- const eventsGeoMock = mockEventsGeo();
- mockEventsv2();
- await renderModal({initialData, widget: mockWidget, tableData: []});
- expect(eventsGeoMock).not.toHaveBeenCalled();
- });
- });
- describe('with events', function () {
- it('always queries geo.country_code in the table chart', async function () {
- const eventsMock = mockEvents();
- mockEventsGeo();
- await renderModal({initialData: initialDataWithFlag, widget: mockWidget});
- expect(eventsMock).toHaveBeenCalledWith(
- '/organizations/org-slug/events/',
- expect.objectContaining({
- query: expect.objectContaining({
- field: ['geo.country_code', 'p75(measurements.lcp)'],
- }),
- })
- );
- expect(await screen.findByText('geo.country_code')).toBeInTheDocument();
- });
- });
- });
- describe('Table Widget', function () {
- const mockQuery = {
- conditions: 'title:/organizations/:orgId/performance/summary/',
- fields: ['title', 'count()'],
- aggregates: ['count()'],
- columns: ['title'],
- id: '1',
- name: 'Query Name',
- orderby: '',
- };
- const mockWidget = {
- title: 'Test Widget',
- displayType: DisplayType.TABLE,
- interval: '5m',
- queries: [mockQuery],
- widgetType: WidgetType.DISCOVER,
- };
- function mockEventsv2() {
- return MockApiClient.addMockResponse({
- url: '/organizations/org-slug/eventsv2/',
- body: {
- data: [
- {
- title: '/organizations/:orgId/dashboards/',
- id: '1',
- count: 1,
- },
- ],
- meta: {
- title: 'string',
- id: 'string',
- count: 1,
- isMetricsData: false,
- },
- },
- });
- }
- function mockEvents() {
- return MockApiClient.addMockResponse({
- url: '/organizations/org-slug/events/',
- body: {
- data: [
- {
- title: '/organizations/:orgId/dashboards/',
- id: '1',
- count: 1,
- },
- ],
- meta: {
- fields: {
- title: 'string',
- id: 'string',
- count: 1,
- },
- isMetricsData: false,
- },
- },
- });
- }
- describe('with eventsv2', function () {
- it('makes eventsv2 requests when table is paginated', async function () {
- const eventsv2Mock = mockEventsv2();
- await renderModal({
- initialData,
- widget: mockWidget,
- tableData: [],
- pageLinks:
- '<https://sentry.io>; rel="previous"; results="false"; cursor="0:0:1", <https://sentry.io>; rel="next"; results="true"; cursor="0:20:0"',
- });
- expect(eventsv2Mock).not.toHaveBeenCalled();
- userEvent.click(screen.getByLabelText('Next'));
- await waitFor(() => {
- expect(eventsv2Mock).toHaveBeenCalled();
- });
- });
- });
- describe('with events', function () {
- it('makes events requests when table is paginated', async function () {
- const eventsMock = mockEvents();
- await renderModal({
- initialData: initialDataWithFlag,
- widget: mockWidget,
- tableData: [],
- pageLinks:
- '<https://sentry.io>; rel="previous"; results="false"; cursor="0:0:1", <https://sentry.io>; rel="next"; results="true"; cursor="0:20:0"',
- });
- expect(eventsMock).not.toHaveBeenCalled();
- userEvent.click(screen.getByLabelText('Next'));
- await waitFor(() => {
- expect(eventsMock).toHaveBeenCalled();
- });
- });
- it('disables the Open in Discover button for a custom measurement widget', async function () {
- const customMeasurementWidget = {
- ...mockWidget,
- queries: [
- {
- conditions: '',
- fields: [],
- aggregates: ['p99(measurements.custom.measurement)'],
- columns: ['title'],
- id: '1',
- name: 'Query Name',
- orderby: '',
- },
- ],
- };
- await renderModal({
- initialData: initialDataWithFlag,
- widget: customMeasurementWidget,
- tableData: [],
- pageLinks:
- '<https://sentry.io>; rel="previous"; results="false"; cursor="0:0:1", <https://sentry.io>; rel="next"; results="true"; cursor="0:20:0"',
- });
- userEvent.click(screen.getByText('Open in Discover'));
- expect(initialData.router.push).not.toHaveBeenCalled();
- });
- });
- });
- });
- describe('Issue Table Widget', function () {
- let issuesMock;
- const mockQuery = {
- conditions: 'is:unresolved',
- fields: ['events', 'status', 'title'],
- columns: ['events', 'status', 'title'],
- aggregates: [],
- id: '1',
- name: 'Query Name',
- orderby: '',
- };
- const mockWidget = {
- id: '1',
- title: 'Issue Widget',
- displayType: DisplayType.TABLE,
- interval: '5m',
- queries: [mockQuery],
- widgetType: WidgetType.ISSUE,
- };
- beforeEach(function () {
- MemberListStore.loadInitialData([]);
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/issues/',
- method: 'GET',
- match: [
- MockApiClient.matchData({
- cursor: '0:10:0',
- }),
- ],
- headers: {
- Link:
- '<http://localhost/api/0/organizations/org-slug/issues/?cursor=0:0:1>; rel="previous"; results="false"; cursor="0:0:1",' +
- '<http://localhost/api/0/organizations/org-slug/issues/?cursor=0:20:0>; rel="next"; results="true"; cursor="0:20:0"',
- },
- body: [
- {
- id: '2',
- title: 'Another Error: Failed',
- project: {
- id: '3',
- },
- status: 'unresolved',
- lifetime: {count: 5},
- count: 3,
- userCount: 1,
- },
- ],
- });
- issuesMock = MockApiClient.addMockResponse({
- url: '/organizations/org-slug/issues/',
- method: 'GET',
- match: [
- MockApiClient.matchData({
- cursor: undefined,
- }),
- ],
- headers: {
- Link:
- '<http://localhost/api/0/organizations/org-slug/issues/?cursor=0:0:1>; rel="previous"; results="false"; cursor="0:0:1",' +
- '<http://localhost/api/0/organizations/org-slug/issues/?cursor=0:10:0>; rel="next"; results="true"; cursor="0:10:0"',
- },
- body: [
- {
- id: '1',
- title: 'Error: Failed',
- project: {
- id: '3',
- },
- status: 'unresolved',
- lifetime: {count: 10},
- count: 6,
- userCount: 3,
- },
- ],
- });
- });
- it('renders widget title', async function () {
- await renderModal({initialData, widget: mockWidget});
- expect(screen.getByText('Issue Widget')).toBeInTheDocument();
- });
- it('renders Edit and Open buttons', async function () {
- await renderModal({initialData, widget: mockWidget});
- expect(screen.getByText('Edit Widget')).toBeInTheDocument();
- expect(screen.getByText('Open in Issues')).toBeInTheDocument();
- });
- it('renders events, status, and title table columns', async function () {
- await renderModal({initialData, widget: mockWidget});
- expect(screen.getByText('title')).toBeInTheDocument();
- expect(await screen.findByText('Error: Failed')).toBeInTheDocument();
- expect(screen.getByText('events')).toBeInTheDocument();
- expect(screen.getByText('6')).toBeInTheDocument();
- expect(screen.getByText('status')).toBeInTheDocument();
- expect(screen.getByText('unresolved')).toBeInTheDocument();
- });
- it('renders Issue table widget viewer', async function () {
- const {container} = await renderModal({initialData, widget: mockWidget});
- await screen.findByText('Error: Failed');
- expect(container).toSnapshot();
- });
- it('redirects user to Issues when clicking Open in Issues', async function () {
- await renderModal({initialData, widget: mockWidget});
- userEvent.click(screen.getByText('Open in Issues'));
- expect(initialData.router.push).toHaveBeenCalledWith(
- '/organizations/org-slug/issues/?environment=prod&environment=dev&project=1&project=2&query=is%3Aunresolved&sort=&statsPeriod=24h'
- );
- });
- it('sorts table when a sortable column header is clicked', async function () {
- const {rerender} = await renderModal({initialData, widget: mockWidget});
- userEvent.click(screen.getByText('events'));
- expect(initialData.router.push).toHaveBeenCalledWith({
- query: {sort: 'freq'},
- });
- // Need to manually set the new router location and rerender to simulate the sortable column click
- initialData.router.location.query = {sort: ['freq']};
- rerender(
- <WidgetViewerModal
- Header={stubEl}
- Footer={stubEl as ModalRenderProps['Footer']}
- Body={stubEl as ModalRenderProps['Body']}
- CloseButton={stubEl}
- closeModal={() => undefined}
- organization={initialData.organization}
- widget={mockWidget}
- onEdit={() => undefined}
- />
- );
- expect(issuesMock).toHaveBeenCalledWith(
- '/organizations/org-slug/issues/',
- expect.objectContaining({
- data: {
- cursor: undefined,
- environment: ['prod', 'dev'],
- expand: ['owners'],
- limit: 20,
- project: [1, 2],
- query: 'is:unresolved',
- sort: 'date',
- statsPeriod: '24h',
- },
- })
- );
- });
- it('renders pagination buttons', async function () {
- await renderModal({initialData, widget: mockWidget});
- expect(await screen.findByRole('button', {name: 'Previous'})).toBeInTheDocument();
- expect(screen.getByRole('button', {name: 'Next'})).toBeInTheDocument();
- });
- it('paginates to the next page', async function () {
- const {rerender} = await renderModal({initialData, widget: mockWidget});
- expect(await screen.findByText('Error: Failed')).toBeInTheDocument();
- userEvent.click(screen.getByRole('button', {name: 'Next'}));
- expect(issuesMock).toHaveBeenCalledTimes(1);
- expect(initialData.router.replace).toHaveBeenCalledWith(
- expect.objectContaining({
- query: {cursor: '0:10:0', page: 1},
- })
- );
- // Need to manually set the new router location and rerender to simulate the next page click
- initialData.router.location.query = {cursor: ['0:10:0']};
- rerender(
- <WidgetViewerModal
- Header={stubEl}
- Footer={stubEl as ModalRenderProps['Footer']}
- Body={stubEl as ModalRenderProps['Body']}
- CloseButton={stubEl}
- closeModal={() => undefined}
- organization={initialData.organization}
- widget={mockWidget}
- onEdit={() => undefined}
- />
- );
- expect(await screen.findByText('Another Error: Failed')).toBeInTheDocument();
- });
- it('displays with correct table column widths', async function () {
- initialData.router.location.query = {width: ['-1', '-1', '575']};
- await renderModal({initialData, widget: mockWidget});
- expect(screen.getByTestId('grid-editable')).toHaveStyle({
- 'grid-template-columns':
- ' minmax(90px, auto) minmax(90px, auto) minmax(575px, auto)',
- });
- });
- it('uses provided tableData and does not make an issues requests', async function () {
- await renderModal({initialData, widget: mockWidget, tableData: []});
- expect(issuesMock).not.toHaveBeenCalled();
- });
- it('makes issues requests when table is sorted', async function () {
- await renderModal({
- initialData,
- widget: mockWidget,
- tableData: [],
- });
- expect(issuesMock).not.toHaveBeenCalled();
- userEvent.click(screen.getByText('events'));
- await waitFor(() => {
- expect(issuesMock).toHaveBeenCalled();
- });
- });
- });
- describe('Release Health Widgets', function () {
- let metricsMock;
- const mockQuery = {
- conditions: '',
- fields: [`sum(session)`],
- columns: [],
- aggregates: [],
- id: '1',
- name: 'Query Name',
- orderby: '',
- };
- const mockWidget = {
- id: '1',
- title: 'Release Widget',
- displayType: DisplayType.LINE,
- interval: '5m',
- queries: [mockQuery],
- widgetType: WidgetType.RELEASE,
- };
- beforeEach(function () {
- metricsMock = MockApiClient.addMockResponse({
- url: '/organizations/org-slug/metrics/data/',
- body: TestStubs.MetricsTotalCountByReleaseIn24h(),
- headers: {
- link:
- '<http://localhost/api/0/organizations/org-slug/metrics/data/?cursor=0:0:1>; rel="previous"; results="false"; cursor="0:0:1",' +
- '<http://localhost/api/0/organizations/org-slug/metrics/data/?cursor=0:10:0>; rel="next"; results="true"; cursor="0:10:0"',
- },
- });
- });
- it('does a sessions query', async function () {
- await renderModal({initialData, widget: mockWidget});
- expect(metricsMock).toHaveBeenCalled();
- });
- it('renders widget title', async function () {
- await renderModal({initialData, widget: mockWidget});
- expect(screen.getByText('Release Widget')).toBeInTheDocument();
- });
- it('renders Edit and Open in Releases buttons', async function () {
- await renderModal({initialData, widget: mockWidget});
- expect(screen.getByText('Edit Widget')).toBeInTheDocument();
- expect(screen.getByText('Open in Releases')).toBeInTheDocument();
- });
- it('Open in Releases button redirects browser', async function () {
- await renderModal({initialData, widget: mockWidget});
- userEvent.click(screen.getByText('Open in Releases'));
- expect(initialData.router.push).toHaveBeenCalledWith(
- '/organizations/org-slug/releases/?environment=prod&environment=dev&project=1&project=2&statsPeriod=24h'
- );
- });
- it('renders table header and body', async function () {
- await renderModal({initialData, widget: mockWidget});
- expect(screen.getByText('release')).toBeInTheDocument();
- expect(await screen.findByText('e102abb2c46e')).toBeInTheDocument();
- expect(screen.getByText('sum(session)')).toBeInTheDocument();
- expect(screen.getByText('6.3k')).toBeInTheDocument();
- });
- it('renders Release widget viewer', async function () {
- const {container} = await renderModal({initialData, widget: mockWidget});
- expect(await screen.findByText('e102abb2c46e')).toBeInTheDocument();
- expect(container).toSnapshot();
- });
- it('renders pagination buttons', async function () {
- await renderModal({
- initialData,
- widget: mockWidget,
- });
- expect(await screen.findByRole('button', {name: 'Previous'})).toBeInTheDocument();
- expect(screen.getByRole('button', {name: 'Next'})).toBeInTheDocument();
- });
- it('does not render pagination buttons when sorting by release', async function () {
- await renderModal({
- initialData,
- widget: {...mockWidget, queries: [{...mockQuery, orderby: 'release'}]},
- });
- expect(screen.queryByRole('button', {name: 'Previous'})).not.toBeInTheDocument();
- expect(screen.queryByRole('button', {name: 'Next'})).not.toBeInTheDocument();
- });
- it('makes a new sessions request after sorting by a table column', async function () {
- const {rerender} = await renderModal({
- initialData,
- widget: mockWidget,
- tableData: [],
- seriesData: [],
- });
- expect(metricsMock).toHaveBeenCalledTimes(1);
- userEvent.click(screen.getByText(`sum(session)`));
- expect(initialData.router.push).toHaveBeenCalledWith({
- query: {sort: '-sum(session)'},
- });
- // Need to manually set the new router location and rerender to simulate the sortable column click
- initialData.router.location.query = {sort: '-sum(session)'};
- rerender(
- <WidgetViewerModal
- Header={stubEl}
- Footer={stubEl as ModalRenderProps['Footer']}
- Body={stubEl as ModalRenderProps['Body']}
- CloseButton={stubEl}
- closeModal={() => undefined}
- organization={initialData.organization}
- widget={mockWidget}
- onEdit={() => undefined}
- seriesData={[]}
- tableData={[]}
- />
- );
- await waitFor(() => {
- expect(metricsMock).toHaveBeenCalledTimes(2);
- });
- });
- });
- });
|