widgetViewerModal.spec.tsx 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532
  1. import ReactEchartsCore from 'echarts-for-react/lib/core';
  2. import {initializeOrg} from 'sentry-test/initializeOrg';
  3. import {act, render, screen, userEvent, waitFor} from 'sentry-test/reactTestingLibrary';
  4. import {ModalRenderProps} from 'sentry/actionCreators/modal';
  5. import WidgetViewerModal from 'sentry/components/modals/widgetViewerModal';
  6. import MemberListStore from 'sentry/stores/memberListStore';
  7. import PageFiltersStore from 'sentry/stores/pageFiltersStore';
  8. import space from 'sentry/styles/space';
  9. import {Series} from 'sentry/types/echarts';
  10. import {TableDataWithTitle} from 'sentry/utils/discover/discoverQuery';
  11. import {
  12. DisplayType,
  13. Widget,
  14. WidgetQuery,
  15. WidgetType,
  16. } from 'sentry/views/dashboardsV2/types';
  17. jest.mock('echarts-for-react/lib/core', () => {
  18. return jest.fn(({style}) => {
  19. return <div style={{...style, background: 'green'}}>echarts mock</div>;
  20. });
  21. });
  22. jest.mock('sentry/components/tooltip', () => {
  23. return jest.fn(props => {
  24. return <div>{props.children}</div>;
  25. });
  26. });
  27. const stubEl = (props: {children?: React.ReactNode}) => <div>{props.children}</div>;
  28. let eventsMetaMock;
  29. const waitForMetaToHaveBeenCalled = async () => {
  30. await waitFor(() => {
  31. expect(eventsMetaMock).toHaveBeenCalled();
  32. });
  33. };
  34. async function renderModal({
  35. initialData: {organization, routerContext},
  36. widget,
  37. seriesData,
  38. tableData,
  39. pageLinks,
  40. }: {
  41. initialData: any;
  42. widget: any;
  43. pageLinks?: string;
  44. seriesData?: Series[];
  45. tableData?: TableDataWithTitle[];
  46. }) {
  47. const rendered = render(
  48. <div style={{padding: space(4)}}>
  49. <WidgetViewerModal
  50. Header={stubEl}
  51. Footer={stubEl as ModalRenderProps['Footer']}
  52. Body={stubEl as ModalRenderProps['Body']}
  53. CloseButton={stubEl}
  54. closeModal={() => undefined}
  55. organization={organization}
  56. widget={widget}
  57. onEdit={() => undefined}
  58. seriesData={seriesData}
  59. tableData={tableData}
  60. pageLinks={pageLinks}
  61. />
  62. </div>,
  63. {
  64. context: routerContext,
  65. organization,
  66. }
  67. );
  68. // Need to wait since WidgetViewerModal will make a request to events-meta
  69. // for total events count on mount
  70. if (widget.widgetType === WidgetType.DISCOVER) {
  71. await waitForMetaToHaveBeenCalled();
  72. }
  73. return rendered;
  74. }
  75. describe('Modals -> WidgetViewerModal', function () {
  76. let initialData, initialDataWithFlag;
  77. beforeEach(() => {
  78. initialData = initializeOrg({
  79. organization: {
  80. features: ['discover-query', 'widget-viewer-modal'],
  81. apdexThreshold: 400,
  82. },
  83. router: {
  84. location: {query: {}},
  85. },
  86. project: 1,
  87. projects: [],
  88. });
  89. initialDataWithFlag = {
  90. ...initialData,
  91. organization: {
  92. ...initialData.organization,
  93. features: [
  94. ...initialData.organization.features,
  95. 'discover-frontend-use-events-endpoint',
  96. ],
  97. },
  98. };
  99. MockApiClient.addMockResponse({
  100. url: '/organizations/org-slug/projects/',
  101. body: [],
  102. });
  103. MockApiClient.addMockResponse({
  104. url: '/organizations/org-slug/releases/',
  105. body: [],
  106. });
  107. eventsMetaMock = MockApiClient.addMockResponse({
  108. url: '/organizations/org-slug/events-meta/',
  109. body: {count: 33323612},
  110. });
  111. PageFiltersStore.init();
  112. PageFiltersStore.onInitializeUrlState(
  113. {
  114. projects: [1, 2],
  115. environments: ['prod', 'dev'],
  116. datetime: {start: null, end: null, period: '24h', utc: null},
  117. },
  118. new Set()
  119. );
  120. });
  121. afterEach(() => {
  122. MockApiClient.clearMockResponses();
  123. PageFiltersStore.teardown();
  124. });
  125. describe('Discover Widgets', function () {
  126. describe('Area Chart Widget', function () {
  127. let mockQuery: WidgetQuery;
  128. let additionalMockQuery: WidgetQuery;
  129. let mockWidget: Widget;
  130. function mockEventsv2() {
  131. return MockApiClient.addMockResponse({
  132. url: '/organizations/org-slug/eventsv2/',
  133. body: {
  134. data: [
  135. {
  136. title: '/organizations/:orgId/dashboards/',
  137. id: '1',
  138. count: 1,
  139. },
  140. ],
  141. meta: {
  142. title: 'string',
  143. id: 'string',
  144. count: 1,
  145. isMetricsData: false,
  146. },
  147. },
  148. });
  149. }
  150. function mockEvents() {
  151. return MockApiClient.addMockResponse({
  152. url: '/organizations/org-slug/events/',
  153. body: {
  154. data: [
  155. {
  156. title: '/organizations/:orgId/dashboards/',
  157. id: '1',
  158. count: 1,
  159. },
  160. ],
  161. meta: {
  162. fields: {
  163. title: 'string',
  164. id: 'string',
  165. count: 1,
  166. },
  167. isMetricsData: false,
  168. },
  169. },
  170. });
  171. }
  172. beforeEach(function () {
  173. mockQuery = {
  174. conditions: 'title:/organizations/:orgId/performance/summary/',
  175. fields: ['count()'],
  176. aggregates: ['count()'],
  177. columns: [],
  178. name: 'Query Name',
  179. orderby: '',
  180. };
  181. additionalMockQuery = {
  182. conditions: '',
  183. fields: ['count()'],
  184. aggregates: ['count()'],
  185. columns: [],
  186. name: 'Another Query Name',
  187. orderby: '',
  188. };
  189. mockWidget = {
  190. id: '1',
  191. title: 'Test Widget',
  192. displayType: DisplayType.AREA,
  193. interval: '5m',
  194. queries: [mockQuery, additionalMockQuery],
  195. widgetType: WidgetType.DISCOVER,
  196. };
  197. (ReactEchartsCore as jest.Mock).mockClear();
  198. MockApiClient.addMockResponse({
  199. url: '/organizations/org-slug/events-stats/',
  200. body: {
  201. data: [
  202. [[1646100000], [{count: 1}]],
  203. [[1646120000], [{count: 1}]],
  204. ],
  205. start: 1646100000,
  206. end: 1646120000,
  207. isMetricsData: false,
  208. },
  209. });
  210. });
  211. describe('with eventsv2', function () {
  212. it('renders Edit and Open buttons', async function () {
  213. mockEventsv2();
  214. await renderModal({initialData, widget: mockWidget});
  215. expect(screen.getByText('Edit Widget')).toBeInTheDocument();
  216. expect(screen.getByText('Open in Discover')).toBeInTheDocument();
  217. });
  218. it('renders updated table columns and orderby', async function () {
  219. const eventsv2Mock = mockEventsv2();
  220. await renderModal({initialData, widget: mockWidget});
  221. expect(screen.getByText('title')).toBeInTheDocument();
  222. expect(
  223. screen.getByText('/organizations/:orgId/dashboards/')
  224. ).toBeInTheDocument();
  225. expect(eventsv2Mock).toHaveBeenCalledWith(
  226. '/organizations/org-slug/eventsv2/',
  227. expect.objectContaining({
  228. query: expect.objectContaining({sort: ['-count()']}),
  229. })
  230. );
  231. });
  232. it('renders area chart', async function () {
  233. mockEventsv2();
  234. await renderModal({initialData, widget: mockWidget});
  235. expect(screen.getByText('echarts mock')).toBeInTheDocument();
  236. });
  237. it('renders Discover area chart widget viewer', async function () {
  238. mockEventsv2();
  239. const {container} = await renderModal({initialData, widget: mockWidget});
  240. expect(container).toSnapshot();
  241. });
  242. it('redirects user to Discover when clicking Open in Discover', async function () {
  243. mockEventsv2();
  244. await renderModal({initialData, widget: mockWidget});
  245. userEvent.click(screen.getByText('Open in Discover'));
  246. expect(initialData.router.push).toHaveBeenCalledWith(
  247. '/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'
  248. );
  249. });
  250. it('zooms into the selected time range', async function () {
  251. mockEventsv2();
  252. await renderModal({initialData, widget: mockWidget});
  253. act(() => {
  254. // Simulate dataZoom event on chart
  255. (ReactEchartsCore as jest.Mock).mock.calls[0][0].onEvents.datazoom(
  256. undefined,
  257. {
  258. getModel: () => {
  259. return {
  260. _payload: {
  261. batch: [{startValue: 1646100000000, endValue: 1646120000000}],
  262. },
  263. };
  264. },
  265. }
  266. );
  267. });
  268. expect(initialData.router.push).toHaveBeenCalledWith(
  269. expect.objectContaining({
  270. query: {
  271. viewerEnd: '2022-03-01T07:33:20',
  272. viewerStart: '2022-03-01T02:00:00',
  273. },
  274. })
  275. );
  276. });
  277. it('renders multiquery label and selector', async function () {
  278. mockEventsv2();
  279. await renderModal({initialData, widget: mockWidget});
  280. expect(
  281. screen.getByText(
  282. '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.'
  283. )
  284. ).toBeInTheDocument();
  285. expect(screen.getByText('Query Name')).toBeInTheDocument();
  286. });
  287. it('updates selected query when selected in the query dropdown', async function () {
  288. mockEventsv2();
  289. const {rerender} = await renderModal({initialData, widget: mockWidget});
  290. userEvent.click(screen.getByText('Query Name'));
  291. userEvent.click(screen.getByText('Another Query Name'));
  292. expect(initialData.router.replace).toHaveBeenCalledWith({
  293. query: {query: 1},
  294. });
  295. // Need to manually set the new router location and rerender to simulate the dropdown selection click
  296. initialData.router.location.query = {query: ['1']};
  297. rerender(
  298. <WidgetViewerModal
  299. Header={stubEl}
  300. Footer={stubEl as ModalRenderProps['Footer']}
  301. Body={stubEl as ModalRenderProps['Body']}
  302. CloseButton={stubEl}
  303. closeModal={() => undefined}
  304. organization={initialData.organization}
  305. widget={mockWidget}
  306. onEdit={() => undefined}
  307. />
  308. );
  309. await waitForMetaToHaveBeenCalled();
  310. expect(screen.getByText('Another Query Name')).toBeInTheDocument();
  311. });
  312. it('renders the correct discover query link when there are multiple queries in a widget', async function () {
  313. mockEventsv2();
  314. initialData.router.location.query = {query: ['1']};
  315. await renderModal({initialData, widget: mockWidget});
  316. expect(screen.getByRole('button', {name: 'Open in Discover'})).toHaveAttribute(
  317. 'href',
  318. '/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'
  319. );
  320. });
  321. it('renders with first legend disabled by default', async function () {
  322. mockEventsv2();
  323. // Rerender with first legend disabled
  324. initialData.router.location.query = {legend: ['Query Name']};
  325. await renderModal({initialData, widget: mockWidget});
  326. expect(ReactEchartsCore).toHaveBeenLastCalledWith(
  327. expect.objectContaining({
  328. option: expect.objectContaining({
  329. legend: expect.objectContaining({
  330. selected: {'Query Name': false},
  331. }),
  332. }),
  333. }),
  334. {}
  335. );
  336. });
  337. it('renders total results in footer', async function () {
  338. mockEventsv2();
  339. await renderModal({initialData, widget: mockWidget});
  340. expect(screen.getByText('33,323,612')).toBeInTheDocument();
  341. });
  342. it('renders highlighted query text and multiple queries in select dropdown', async function () {
  343. mockEventsv2();
  344. const {container} = await renderModal({
  345. initialData,
  346. widget: {
  347. ...mockWidget,
  348. queries: [{...mockQuery, name: ''}, additionalMockQuery],
  349. },
  350. });
  351. userEvent.click(screen.getByText('/organizations/:orgId/performance/summary/'));
  352. expect(container).toSnapshot();
  353. });
  354. it('renders widget chart minimap', async function () {
  355. initialData.organization.features.push('widget-viewer-modal-minimap');
  356. mockEventsv2();
  357. await renderModal({
  358. initialData,
  359. widget: {
  360. ...mockWidget,
  361. queries: [{...mockQuery, name: ''}, additionalMockQuery],
  362. },
  363. });
  364. expect(ReactEchartsCore).toHaveBeenLastCalledWith(
  365. expect.objectContaining({
  366. option: expect.objectContaining({
  367. dataZoom: expect.arrayContaining([
  368. expect.objectContaining({
  369. realtime: false,
  370. showDetail: false,
  371. end: 100,
  372. start: 0,
  373. }),
  374. ]),
  375. }),
  376. }),
  377. {}
  378. );
  379. });
  380. it('zooming on minimap updates location query and updates echart start and end values', async function () {
  381. initialData.organization.features.push('widget-viewer-modal-minimap');
  382. mockEventsv2();
  383. await renderModal({
  384. initialData,
  385. widget: {
  386. ...mockWidget,
  387. queries: [{...mockQuery, name: ''}, additionalMockQuery],
  388. },
  389. });
  390. const calls = (ReactEchartsCore as jest.Mock).mock.calls;
  391. act(() => {
  392. // Simulate dataZoom event on chart
  393. calls[calls.length - 1][0].onEvents.datazoom(
  394. {seriesStart: 1646100000000, seriesEnd: 1646120000000},
  395. {
  396. getModel: () => {
  397. return {
  398. _payload: {start: 30, end: 70},
  399. };
  400. },
  401. }
  402. );
  403. });
  404. expect(initialData.router.push).toHaveBeenCalledWith(
  405. expect.objectContaining({
  406. query: {
  407. viewerEnd: '2022-03-01T05:53:20',
  408. viewerStart: '2022-03-01T03:40:00',
  409. },
  410. })
  411. );
  412. });
  413. it('includes group by in widget viewer table', async function () {
  414. mockEventsv2();
  415. mockWidget.queries = [
  416. {
  417. conditions: 'title:/organizations/:orgId/performance/summary/',
  418. fields: ['count()'],
  419. aggregates: ['count()'],
  420. columns: ['transaction'],
  421. name: 'Query Name',
  422. orderby: '-count()',
  423. },
  424. ];
  425. await renderModal({initialData, widget: mockWidget});
  426. screen.getByText('transaction');
  427. });
  428. it('includes order by in widget viewer table if not explicitly selected', async function () {
  429. mockEventsv2();
  430. mockWidget.queries = [
  431. {
  432. conditions: 'title:/organizations/:orgId/performance/summary/',
  433. fields: ['count()'],
  434. aggregates: ['count()'],
  435. columns: ['transaction'],
  436. name: 'Query Name',
  437. orderby: 'count_unique(user)',
  438. },
  439. ];
  440. await renderModal({initialData, widget: mockWidget});
  441. screen.getByText('count_unique(user)');
  442. });
  443. it('includes a custom equation order by in widget viewer table if not explicitly selected', async function () {
  444. mockEventsv2();
  445. mockWidget.queries = [
  446. {
  447. conditions: 'title:/organizations/:orgId/performance/summary/',
  448. fields: ['count()'],
  449. aggregates: ['count()'],
  450. columns: ['transaction'],
  451. name: 'Query Name',
  452. orderby: '-equation|count_unique(user) + 1',
  453. },
  454. ];
  455. await renderModal({initialData, widget: mockWidget});
  456. screen.getByText('count_unique(user) + 1');
  457. });
  458. });
  459. describe('with events', function () {
  460. it('renders updated table columns and orderby', async function () {
  461. const eventsMock = mockEvents();
  462. await renderModal({initialData: initialDataWithFlag, widget: mockWidget});
  463. expect(screen.getByText('title')).toBeInTheDocument();
  464. expect(
  465. screen.getByText('/organizations/:orgId/dashboards/')
  466. ).toBeInTheDocument();
  467. expect(eventsMock).toHaveBeenCalledWith(
  468. '/organizations/org-slug/events/',
  469. expect.objectContaining({
  470. query: expect.objectContaining({sort: ['-count()']}),
  471. })
  472. );
  473. });
  474. });
  475. });
  476. describe('TopN Chart Widget', function () {
  477. let mockQuery, mockWidget;
  478. function mockEventsStats() {
  479. return MockApiClient.addMockResponse({
  480. url: '/organizations/org-slug/events-stats/',
  481. body: {
  482. data: [
  483. [[1646100000], [{count: 1}]],
  484. [[1646120000], [{count: 1}]],
  485. ],
  486. start: 1646100000,
  487. end: 1646120000,
  488. isMetricsData: false,
  489. },
  490. });
  491. }
  492. const eventsMockData = [
  493. {
  494. 'error.type': ['Test Error 1a', 'Test Error 1b', 'Test Error 1c'],
  495. count: 10,
  496. },
  497. {
  498. 'error.type': ['Test Error 2'],
  499. count: 6,
  500. },
  501. {
  502. 'error.type': ['Test Error 3'],
  503. count: 5,
  504. },
  505. {
  506. 'error.type': ['Test Error 4'],
  507. count: 4,
  508. },
  509. {
  510. 'error.type': ['Test Error 5'],
  511. count: 3,
  512. },
  513. {
  514. 'error.type': ['Test Error 6'],
  515. count: 2,
  516. },
  517. ];
  518. function mockEventsv2() {
  519. return MockApiClient.addMockResponse({
  520. url: '/organizations/org-slug/eventsv2/',
  521. match: [MockApiClient.matchQuery({cursor: undefined})],
  522. headers: {
  523. Link:
  524. '<http://localhost/api/0/organizations/org-slug/eventsv2/?cursor=0:0:1>; rel="previous"; results="false"; cursor="0:0:1",' +
  525. '<http://localhost/api/0/organizations/org-slug/eventsv2/?cursor=0:10:0>; rel="next"; results="true"; cursor="0:10:0"',
  526. },
  527. body: {
  528. data: eventsMockData,
  529. meta: {
  530. 'error.type': 'array',
  531. count: 'integer',
  532. },
  533. },
  534. });
  535. }
  536. function mockEvents() {
  537. return MockApiClient.addMockResponse({
  538. url: '/organizations/org-slug/events/',
  539. match: [MockApiClient.matchQuery({cursor: undefined})],
  540. headers: {
  541. Link:
  542. '<http://localhost/api/0/organizations/org-slug/eventsv2/?cursor=0:0:1>; rel="previous"; results="false"; cursor="0:0:1",' +
  543. '<http://localhost/api/0/organizations/org-slug/eventsv2/?cursor=0:10:0>; rel="next"; results="true"; cursor="0:10:0"',
  544. },
  545. body: {
  546. data: eventsMockData,
  547. meta: {
  548. fields: {
  549. 'error.type': 'array',
  550. count: 'integer',
  551. },
  552. },
  553. },
  554. });
  555. }
  556. beforeEach(function () {
  557. mockQuery = {
  558. conditions: 'title:/organizations/:orgId/performance/summary/',
  559. fields: ['error.type', 'count()'],
  560. aggregates: ['count()'],
  561. columns: ['error.type'],
  562. id: '1',
  563. name: 'Query Name',
  564. orderby: '',
  565. };
  566. mockWidget = {
  567. title: 'Test Widget',
  568. displayType: DisplayType.TOP_N,
  569. interval: '5m',
  570. queries: [mockQuery],
  571. widgetType: WidgetType.DISCOVER,
  572. };
  573. MockApiClient.addMockResponse({
  574. url: '/organizations/org-slug/eventsv2/',
  575. match: [MockApiClient.matchQuery({cursor: '0:10:0'})],
  576. headers: {
  577. Link:
  578. '<http://localhost/api/0/organizations/org-slug/eventsv2/?cursor=0:0:1>; rel="previous"; results="false"; cursor="0:0:1",' +
  579. '<http://localhost/api/0/organizations/org-slug/eventsv2/?cursor=0:20:0>; rel="next"; results="true"; cursor="0:20:0"',
  580. },
  581. body: {
  582. data: [
  583. {
  584. 'error.type': ['Next Page Test Error'],
  585. count: 1,
  586. },
  587. ],
  588. meta: {
  589. 'error.type': 'array',
  590. count: 'integer',
  591. },
  592. },
  593. });
  594. });
  595. describe('with eventsv2', function () {
  596. it('renders Discover topn chart widget viewer', async function () {
  597. mockEventsStats();
  598. mockEventsv2();
  599. const {container} = await renderModal({initialData, widget: mockWidget});
  600. expect(container).toSnapshot();
  601. });
  602. it('sorts table when a sortable column header is clicked', async function () {
  603. const eventsStatsMock = mockEventsStats();
  604. const eventsv2Mock = mockEventsv2();
  605. const {rerender} = await renderModal({initialData, widget: mockWidget});
  606. userEvent.click(screen.getByText('count()'));
  607. expect(initialData.router.push).toHaveBeenCalledWith({
  608. query: {sort: ['-count()']},
  609. });
  610. // Need to manually set the new router location and rerender to simulate the sortable column click
  611. initialData.router.location.query = {sort: ['-count()']};
  612. rerender(
  613. <WidgetViewerModal
  614. Header={stubEl}
  615. Footer={stubEl as ModalRenderProps['Footer']}
  616. Body={stubEl as ModalRenderProps['Body']}
  617. CloseButton={stubEl}
  618. closeModal={() => undefined}
  619. organization={initialData.organization}
  620. widget={mockWidget}
  621. onEdit={() => undefined}
  622. />
  623. );
  624. await waitForMetaToHaveBeenCalled();
  625. expect(eventsv2Mock).toHaveBeenCalledWith(
  626. '/organizations/org-slug/eventsv2/',
  627. expect.objectContaining({
  628. query: expect.objectContaining({sort: ['-count()']}),
  629. })
  630. );
  631. expect(eventsStatsMock).toHaveBeenCalledWith(
  632. '/organizations/org-slug/events-stats/',
  633. expect.objectContaining({
  634. query: expect.objectContaining({orderby: '-count()'}),
  635. })
  636. );
  637. });
  638. it('renders pagination buttons', async function () {
  639. mockEventsStats();
  640. mockEventsv2();
  641. await renderModal({initialData, widget: mockWidget});
  642. expect(screen.getByRole('button', {name: 'Previous'})).toBeInTheDocument();
  643. expect(screen.getByRole('button', {name: 'Next'})).toBeInTheDocument();
  644. });
  645. it('does not render pagination buttons', async function () {
  646. mockEventsStats();
  647. mockEventsv2();
  648. MockApiClient.addMockResponse({
  649. url: '/organizations/org-slug/eventsv2/',
  650. headers: {
  651. Link:
  652. '<http://localhost/api/0/organizations/org-slug/eventsv2/?cursor=0:0:1>; rel="previous"; results="false"; cursor="0:0:1",' +
  653. '<http://localhost/api/0/organizations/org-slug/eventsv2/?cursor=0:20:0>; rel="next"; results="false"; cursor="0:20:0"',
  654. },
  655. body: {
  656. data: [
  657. {
  658. 'error.type': ['No Pagination'],
  659. count: 1,
  660. },
  661. ],
  662. meta: {
  663. 'error.type': 'array',
  664. count: 'integer',
  665. },
  666. },
  667. });
  668. await renderModal({initialData, widget: mockWidget});
  669. expect(
  670. screen.queryByRole('button', {name: 'Previous'})
  671. ).not.toBeInTheDocument();
  672. expect(screen.queryByRole('button', {name: 'Next'})).not.toBeInTheDocument();
  673. });
  674. it('paginates to the next page', async function () {
  675. mockEventsStats();
  676. mockEventsv2();
  677. const {rerender} = await renderModal({initialData, widget: mockWidget});
  678. expect(screen.getByText('Test Error 1c')).toBeInTheDocument();
  679. userEvent.click(screen.getByRole('button', {name: 'Next'}));
  680. expect(initialData.router.replace).toHaveBeenCalledWith(
  681. expect.objectContaining({
  682. query: {cursor: '0:10:0'},
  683. })
  684. );
  685. // Need to manually set the new router location and rerender to simulate the next page click
  686. initialData.router.location.query = {cursor: ['0:10:0']};
  687. rerender(
  688. <WidgetViewerModal
  689. Header={stubEl}
  690. Footer={stubEl as ModalRenderProps['Footer']}
  691. Body={stubEl as ModalRenderProps['Body']}
  692. CloseButton={stubEl}
  693. closeModal={() => undefined}
  694. organization={initialData.organization}
  695. widget={mockWidget}
  696. onEdit={() => undefined}
  697. />
  698. );
  699. await waitForMetaToHaveBeenCalled();
  700. expect(await screen.findByText('Next Page Test Error')).toBeInTheDocument();
  701. });
  702. it('uses provided seriesData and does not make an events-stats requests', async function () {
  703. const eventsStatsMock = mockEventsStats();
  704. mockEventsv2();
  705. await renderModal({initialData, widget: mockWidget, seriesData: []});
  706. expect(eventsStatsMock).not.toHaveBeenCalled();
  707. });
  708. it('makes events-stats requests when table is sorted', async function () {
  709. const eventsStatsMock = mockEventsStats();
  710. mockEventsv2();
  711. await renderModal({
  712. initialData,
  713. widget: mockWidget,
  714. seriesData: [],
  715. });
  716. expect(eventsStatsMock).not.toHaveBeenCalled();
  717. userEvent.click(screen.getByText('count()'));
  718. await waitForMetaToHaveBeenCalled();
  719. expect(eventsStatsMock).toHaveBeenCalledTimes(1);
  720. });
  721. it('renders widget chart minimap', async function () {
  722. mockEventsStats();
  723. mockEventsv2();
  724. initialData.organization.features.push('widget-viewer-modal-minimap');
  725. await renderModal({initialData, widget: mockWidget});
  726. expect(ReactEchartsCore).toHaveBeenLastCalledWith(
  727. expect.objectContaining({
  728. option: expect.objectContaining({
  729. dataZoom: expect.arrayContaining([
  730. expect.objectContaining({
  731. realtime: false,
  732. showDetail: false,
  733. end: 100,
  734. start: 0,
  735. }),
  736. ]),
  737. }),
  738. }),
  739. {}
  740. );
  741. });
  742. it('zooming on minimap updates location query and updates echart start and end values', async function () {
  743. mockEventsStats();
  744. mockEventsv2();
  745. initialData.organization.features.push('widget-viewer-modal-minimap');
  746. await renderModal({initialData, widget: mockWidget});
  747. const calls = (ReactEchartsCore as jest.Mock).mock.calls;
  748. act(() => {
  749. // Simulate dataZoom event on chart
  750. calls[calls.length - 1][0].onEvents.datazoom(
  751. {seriesStart: 1646100000000, seriesEnd: 1646120000000},
  752. {
  753. getModel: () => {
  754. return {
  755. _payload: {start: 30, end: 70},
  756. };
  757. },
  758. }
  759. );
  760. });
  761. expect(initialData.router.push).toHaveBeenCalledWith(
  762. expect.objectContaining({
  763. query: {
  764. viewerEnd: '2022-03-01T05:53:20',
  765. viewerStart: '2022-03-01T03:40:00',
  766. },
  767. })
  768. );
  769. await waitFor(() => {
  770. expect(ReactEchartsCore).toHaveBeenLastCalledWith(
  771. expect.objectContaining({
  772. option: expect.objectContaining({
  773. dataZoom: expect.arrayContaining([
  774. expect.objectContaining({
  775. realtime: false,
  776. showDetail: false,
  777. endValue: 1646114000000,
  778. startValue: 1646106000000,
  779. }),
  780. ]),
  781. }),
  782. }),
  783. {}
  784. );
  785. });
  786. });
  787. });
  788. describe('with events', function () {
  789. it('sorts table when a sortable column header is clicked', async function () {
  790. const eventsStatsMock = mockEventsStats();
  791. const eventsMock = mockEvents();
  792. const {rerender} = await renderModal({
  793. initialData: initialDataWithFlag,
  794. widget: mockWidget,
  795. });
  796. userEvent.click(screen.getByText('count()'));
  797. expect(initialDataWithFlag.router.push).toHaveBeenCalledWith({
  798. query: {sort: ['-count()']},
  799. });
  800. // Need to manually set the new router location and rerender to simulate the sortable column click
  801. initialDataWithFlag.router.location.query = {sort: ['-count()']};
  802. rerender(
  803. <WidgetViewerModal
  804. Header={stubEl}
  805. Footer={stubEl as ModalRenderProps['Footer']}
  806. Body={stubEl as ModalRenderProps['Body']}
  807. CloseButton={stubEl}
  808. closeModal={() => undefined}
  809. organization={initialDataWithFlag.organization}
  810. widget={mockWidget}
  811. onEdit={() => undefined}
  812. />
  813. );
  814. await waitForMetaToHaveBeenCalled();
  815. expect(eventsMock).toHaveBeenCalledWith(
  816. '/organizations/org-slug/events/',
  817. expect.objectContaining({
  818. query: expect.objectContaining({sort: ['-count()']}),
  819. })
  820. );
  821. expect(eventsStatsMock).toHaveBeenCalledWith(
  822. '/organizations/org-slug/events-stats/',
  823. expect.objectContaining({
  824. query: expect.objectContaining({orderby: '-count()'}),
  825. })
  826. );
  827. });
  828. });
  829. });
  830. describe('World Map Chart Widget', function () {
  831. let mockQuery, mockWidget;
  832. const eventsMockData = [
  833. {
  834. 'geo.country_code': 'ES',
  835. p75_measurements_lcp: 2000,
  836. },
  837. {
  838. 'geo.country_code': 'SK',
  839. p75_measurements_lcp: 3000,
  840. },
  841. {
  842. 'geo.country_code': 'CO',
  843. p75_measurements_lcp: 4000,
  844. },
  845. ];
  846. function mockEventsGeo() {
  847. return MockApiClient.addMockResponse({
  848. url: '/organizations/org-slug/events-geo/',
  849. body: {
  850. data: eventsMockData,
  851. meta: {
  852. 'geo.country_code': 'string',
  853. p75_measurements_lcp: 'duration',
  854. },
  855. },
  856. });
  857. }
  858. function mockEventsv2() {
  859. return MockApiClient.addMockResponse({
  860. url: '/organizations/org-slug/eventsv2/',
  861. body: {
  862. data: eventsMockData,
  863. meta: {
  864. 'geo.country_code': 'string',
  865. p75_measurements_lcp: 'duration',
  866. },
  867. },
  868. });
  869. }
  870. function mockEvents() {
  871. return MockApiClient.addMockResponse({
  872. url: '/organizations/org-slug/events/',
  873. body: {
  874. data: eventsMockData,
  875. meta: {
  876. fields: {
  877. 'geo.country_code': 'string',
  878. p75_measurements_lcp: 'duration',
  879. },
  880. },
  881. },
  882. });
  883. }
  884. beforeEach(function () {
  885. mockQuery = {
  886. conditions: 'title:/organizations/:orgId/performance/summary/',
  887. fields: ['p75(measurements.lcp)'],
  888. aggregates: ['p75(measurements.lcp)'],
  889. columns: [],
  890. id: '1',
  891. name: 'Query Name',
  892. orderby: '',
  893. };
  894. mockWidget = {
  895. title: 'Test Widget',
  896. displayType: DisplayType.WORLD_MAP,
  897. interval: '5m',
  898. queries: [mockQuery],
  899. widgetType: WidgetType.DISCOVER,
  900. };
  901. });
  902. describe('with eventsv2', function () {
  903. it('always queries geo.country_code in the table chart', async function () {
  904. const eventsv2Mock = mockEventsv2();
  905. mockEventsGeo();
  906. await renderModal({initialData, widget: mockWidget});
  907. expect(eventsv2Mock).toHaveBeenCalledWith(
  908. '/organizations/org-slug/eventsv2/',
  909. expect.objectContaining({
  910. query: expect.objectContaining({
  911. field: ['geo.country_code', 'p75(measurements.lcp)'],
  912. }),
  913. })
  914. );
  915. expect(await screen.findByText('geo.country_code')).toBeInTheDocument();
  916. });
  917. it('renders Discover topn chart widget viewer', async function () {
  918. mockEventsv2();
  919. mockEventsGeo();
  920. const {container} = await renderModal({initialData, widget: mockWidget});
  921. expect(container).toSnapshot();
  922. });
  923. it('uses provided tableData and does not make an eventsv2 requests', async function () {
  924. const eventsGeoMock = mockEventsGeo();
  925. mockEventsv2();
  926. await renderModal({initialData, widget: mockWidget, tableData: []});
  927. expect(eventsGeoMock).not.toHaveBeenCalled();
  928. });
  929. });
  930. describe('with events', function () {
  931. it('always queries geo.country_code in the table chart', async function () {
  932. const eventsMock = mockEvents();
  933. mockEventsGeo();
  934. await renderModal({initialData: initialDataWithFlag, widget: mockWidget});
  935. expect(eventsMock).toHaveBeenCalledWith(
  936. '/organizations/org-slug/events/',
  937. expect.objectContaining({
  938. query: expect.objectContaining({
  939. field: ['geo.country_code', 'p75(measurements.lcp)'],
  940. }),
  941. })
  942. );
  943. expect(await screen.findByText('geo.country_code')).toBeInTheDocument();
  944. });
  945. });
  946. });
  947. describe('Table Widget', function () {
  948. const mockQuery = {
  949. conditions: 'title:/organizations/:orgId/performance/summary/',
  950. fields: ['title', 'count()'],
  951. aggregates: ['count()'],
  952. columns: ['title'],
  953. id: '1',
  954. name: 'Query Name',
  955. orderby: '',
  956. };
  957. const mockWidget = {
  958. title: 'Test Widget',
  959. displayType: DisplayType.TABLE,
  960. interval: '5m',
  961. queries: [mockQuery],
  962. widgetType: WidgetType.DISCOVER,
  963. };
  964. function mockEventsv2() {
  965. return MockApiClient.addMockResponse({
  966. url: '/organizations/org-slug/eventsv2/',
  967. body: {
  968. data: [
  969. {
  970. title: '/organizations/:orgId/dashboards/',
  971. id: '1',
  972. count: 1,
  973. },
  974. ],
  975. meta: {
  976. title: 'string',
  977. id: 'string',
  978. count: 1,
  979. isMetricsData: false,
  980. },
  981. },
  982. });
  983. }
  984. function mockEvents() {
  985. return MockApiClient.addMockResponse({
  986. url: '/organizations/org-slug/events/',
  987. body: {
  988. data: [
  989. {
  990. title: '/organizations/:orgId/dashboards/',
  991. id: '1',
  992. count: 1,
  993. },
  994. ],
  995. meta: {
  996. fields: {
  997. title: 'string',
  998. id: 'string',
  999. count: 1,
  1000. },
  1001. isMetricsData: false,
  1002. },
  1003. },
  1004. });
  1005. }
  1006. describe('with eventsv2', function () {
  1007. it('makes eventsv2 requests when table is paginated', async function () {
  1008. const eventsv2Mock = mockEventsv2();
  1009. await renderModal({
  1010. initialData,
  1011. widget: mockWidget,
  1012. tableData: [],
  1013. pageLinks:
  1014. '<https://sentry.io>; rel="previous"; results="false"; cursor="0:0:1", <https://sentry.io>; rel="next"; results="true"; cursor="0:20:0"',
  1015. });
  1016. expect(eventsv2Mock).not.toHaveBeenCalled();
  1017. userEvent.click(screen.getByLabelText('Next'));
  1018. await waitFor(() => {
  1019. expect(eventsv2Mock).toHaveBeenCalled();
  1020. });
  1021. });
  1022. });
  1023. describe('with events', function () {
  1024. it('makes events requests when table is paginated', async function () {
  1025. const eventsMock = mockEvents();
  1026. await renderModal({
  1027. initialData: initialDataWithFlag,
  1028. widget: mockWidget,
  1029. tableData: [],
  1030. pageLinks:
  1031. '<https://sentry.io>; rel="previous"; results="false"; cursor="0:0:1", <https://sentry.io>; rel="next"; results="true"; cursor="0:20:0"',
  1032. });
  1033. expect(eventsMock).not.toHaveBeenCalled();
  1034. userEvent.click(screen.getByLabelText('Next'));
  1035. await waitFor(() => {
  1036. expect(eventsMock).toHaveBeenCalled();
  1037. });
  1038. });
  1039. it('disables the Open in Discover button for a custom measurement widget', async function () {
  1040. const customMeasurementWidget = {
  1041. ...mockWidget,
  1042. queries: [
  1043. {
  1044. conditions: '',
  1045. fields: [],
  1046. aggregates: ['p99(measurements.custom.measurement)'],
  1047. columns: ['title'],
  1048. id: '1',
  1049. name: 'Query Name',
  1050. orderby: '',
  1051. },
  1052. ],
  1053. };
  1054. await renderModal({
  1055. initialData: initialDataWithFlag,
  1056. widget: customMeasurementWidget,
  1057. tableData: [],
  1058. pageLinks:
  1059. '<https://sentry.io>; rel="previous"; results="false"; cursor="0:0:1", <https://sentry.io>; rel="next"; results="true"; cursor="0:20:0"',
  1060. });
  1061. userEvent.click(screen.getByText('Open in Discover'));
  1062. expect(initialData.router.push).not.toHaveBeenCalled();
  1063. });
  1064. it('displays table data with units correctly', async function () {
  1065. const eventsMock = MockApiClient.addMockResponse({
  1066. url: '/organizations/org-slug/events/',
  1067. match: [MockApiClient.matchQuery({cursor: undefined})],
  1068. headers: {
  1069. Link:
  1070. '<http://localhost/api/0/organizations/org-slug/events/?cursor=0:0:1>; rel="previous"; results="false"; cursor="0:0:1",' +
  1071. '<http://localhost/api/0/organizations/org-slug/events/?cursor=0:10:0>; rel="next"; results="true"; cursor="0:10:0"',
  1072. },
  1073. body: {
  1074. data: [
  1075. {
  1076. 'p75(measurements.custom.minute)': 94.87035966318831,
  1077. 'p95(measurements.custom.ratio)': 0.9881980140455187,
  1078. 'p75(measurements.custom.kibibyte)': 217.87035966318834,
  1079. },
  1080. ],
  1081. meta: {
  1082. fields: {
  1083. 'p75(measurements.custom.minute)': 'duration',
  1084. 'p95(measurements.custom.ratio)': 'percentage',
  1085. 'p75(measurements.custom.kibibyte)': 'size',
  1086. },
  1087. units: {
  1088. 'p75(measurements.custom.minute)': 'minute',
  1089. 'p95(measurements.custom.ratio)': null,
  1090. 'p75(measurements.custom.kibibyte)': 'kibibyte',
  1091. },
  1092. isMetricsData: true,
  1093. tips: {},
  1094. },
  1095. },
  1096. });
  1097. await renderModal({
  1098. initialData: initialDataWithFlag,
  1099. widget: {
  1100. title: 'Custom Widget',
  1101. displayType: 'table',
  1102. queries: [
  1103. {
  1104. fields: [
  1105. 'p75(measurements.custom.kibibyte)',
  1106. 'p75(measurements.custom.minute)',
  1107. 'p95(measurements.custom.ratio)',
  1108. ],
  1109. aggregates: [
  1110. 'p75(measurements.custom.kibibyte)',
  1111. 'p75(measurements.custom.minute)',
  1112. 'p95(measurements.custom.ratio)',
  1113. ],
  1114. columns: [],
  1115. orderby: '-p75(measurements.custom.kibibyte)',
  1116. },
  1117. ],
  1118. widgetType: 'discover',
  1119. },
  1120. });
  1121. await waitFor(() => {
  1122. expect(eventsMock).toHaveBeenCalled();
  1123. });
  1124. expect(screen.getByText('217.9 KiB')).toBeInTheDocument();
  1125. expect(screen.getByText('1.58hr')).toBeInTheDocument();
  1126. expect(screen.getByText('98.82%')).toBeInTheDocument();
  1127. });
  1128. });
  1129. });
  1130. });
  1131. describe('Issue Table Widget', function () {
  1132. let issuesMock;
  1133. const mockQuery = {
  1134. conditions: 'is:unresolved',
  1135. fields: ['events', 'status', 'title'],
  1136. columns: ['events', 'status', 'title'],
  1137. aggregates: [],
  1138. id: '1',
  1139. name: 'Query Name',
  1140. orderby: '',
  1141. };
  1142. const mockWidget = {
  1143. id: '1',
  1144. title: 'Issue Widget',
  1145. displayType: DisplayType.TABLE,
  1146. interval: '5m',
  1147. queries: [mockQuery],
  1148. widgetType: WidgetType.ISSUE,
  1149. };
  1150. beforeEach(function () {
  1151. MemberListStore.loadInitialData([]);
  1152. MockApiClient.addMockResponse({
  1153. url: '/organizations/org-slug/issues/',
  1154. method: 'GET',
  1155. match: [
  1156. MockApiClient.matchData({
  1157. cursor: '0:10:0',
  1158. }),
  1159. ],
  1160. headers: {
  1161. Link:
  1162. '<http://localhost/api/0/organizations/org-slug/issues/?cursor=0:0:1>; rel="previous"; results="false"; cursor="0:0:1",' +
  1163. '<http://localhost/api/0/organizations/org-slug/issues/?cursor=0:20:0>; rel="next"; results="true"; cursor="0:20:0"',
  1164. },
  1165. body: [
  1166. {
  1167. id: '2',
  1168. title: 'Another Error: Failed',
  1169. project: {
  1170. id: '3',
  1171. },
  1172. status: 'unresolved',
  1173. lifetime: {count: 5},
  1174. count: 3,
  1175. userCount: 1,
  1176. },
  1177. ],
  1178. });
  1179. issuesMock = MockApiClient.addMockResponse({
  1180. url: '/organizations/org-slug/issues/',
  1181. method: 'GET',
  1182. match: [
  1183. MockApiClient.matchData({
  1184. cursor: undefined,
  1185. }),
  1186. ],
  1187. headers: {
  1188. Link:
  1189. '<http://localhost/api/0/organizations/org-slug/issues/?cursor=0:0:1>; rel="previous"; results="false"; cursor="0:0:1",' +
  1190. '<http://localhost/api/0/organizations/org-slug/issues/?cursor=0:10:0>; rel="next"; results="true"; cursor="0:10:0"',
  1191. },
  1192. body: [
  1193. {
  1194. id: '1',
  1195. title: 'Error: Failed',
  1196. project: {
  1197. id: '3',
  1198. },
  1199. status: 'unresolved',
  1200. lifetime: {count: 10},
  1201. count: 6,
  1202. userCount: 3,
  1203. },
  1204. ],
  1205. });
  1206. });
  1207. it('renders widget title', async function () {
  1208. await renderModal({initialData, widget: mockWidget});
  1209. expect(screen.getByText('Issue Widget')).toBeInTheDocument();
  1210. });
  1211. it('renders Edit and Open buttons', async function () {
  1212. await renderModal({initialData, widget: mockWidget});
  1213. expect(screen.getByText('Edit Widget')).toBeInTheDocument();
  1214. expect(screen.getByText('Open in Issues')).toBeInTheDocument();
  1215. });
  1216. it('renders events, status, and title table columns', async function () {
  1217. await renderModal({initialData, widget: mockWidget});
  1218. expect(screen.getByText('title')).toBeInTheDocument();
  1219. expect(await screen.findByText('Error: Failed')).toBeInTheDocument();
  1220. expect(screen.getByText('events')).toBeInTheDocument();
  1221. expect(screen.getByText('6')).toBeInTheDocument();
  1222. expect(screen.getByText('status')).toBeInTheDocument();
  1223. expect(screen.getByText('unresolved')).toBeInTheDocument();
  1224. });
  1225. it('renders Issue table widget viewer', async function () {
  1226. const {container} = await renderModal({initialData, widget: mockWidget});
  1227. await screen.findByText('Error: Failed');
  1228. expect(container).toSnapshot();
  1229. });
  1230. it('redirects user to Issues when clicking Open in Issues', async function () {
  1231. await renderModal({initialData, widget: mockWidget});
  1232. userEvent.click(screen.getByText('Open in Issues'));
  1233. expect(initialData.router.push).toHaveBeenCalledWith(
  1234. '/organizations/org-slug/issues/?environment=prod&environment=dev&project=1&project=2&query=is%3Aunresolved&sort=&statsPeriod=24h'
  1235. );
  1236. });
  1237. it('sorts table when a sortable column header is clicked', async function () {
  1238. const {rerender} = await renderModal({initialData, widget: mockWidget});
  1239. userEvent.click(screen.getByText('events'));
  1240. expect(initialData.router.push).toHaveBeenCalledWith({
  1241. query: {sort: 'freq'},
  1242. });
  1243. // Need to manually set the new router location and rerender to simulate the sortable column click
  1244. initialData.router.location.query = {sort: ['freq']};
  1245. rerender(
  1246. <WidgetViewerModal
  1247. Header={stubEl}
  1248. Footer={stubEl as ModalRenderProps['Footer']}
  1249. Body={stubEl as ModalRenderProps['Body']}
  1250. CloseButton={stubEl}
  1251. closeModal={() => undefined}
  1252. organization={initialData.organization}
  1253. widget={mockWidget}
  1254. onEdit={() => undefined}
  1255. />
  1256. );
  1257. expect(issuesMock).toHaveBeenCalledWith(
  1258. '/organizations/org-slug/issues/',
  1259. expect.objectContaining({
  1260. data: {
  1261. cursor: undefined,
  1262. environment: ['prod', 'dev'],
  1263. expand: ['owners'],
  1264. limit: 20,
  1265. project: [1, 2],
  1266. query: 'is:unresolved',
  1267. sort: 'date',
  1268. statsPeriod: '24h',
  1269. },
  1270. })
  1271. );
  1272. });
  1273. it('renders pagination buttons', async function () {
  1274. await renderModal({initialData, widget: mockWidget});
  1275. expect(await screen.findByRole('button', {name: 'Previous'})).toBeInTheDocument();
  1276. expect(screen.getByRole('button', {name: 'Next'})).toBeInTheDocument();
  1277. });
  1278. it('paginates to the next page', async function () {
  1279. const {rerender} = await renderModal({initialData, widget: mockWidget});
  1280. expect(await screen.findByText('Error: Failed')).toBeInTheDocument();
  1281. userEvent.click(screen.getByRole('button', {name: 'Next'}));
  1282. expect(issuesMock).toHaveBeenCalledTimes(1);
  1283. expect(initialData.router.replace).toHaveBeenCalledWith(
  1284. expect.objectContaining({
  1285. query: {cursor: '0:10:0', page: 1},
  1286. })
  1287. );
  1288. // Need to manually set the new router location and rerender to simulate the next page click
  1289. initialData.router.location.query = {cursor: ['0:10:0']};
  1290. rerender(
  1291. <WidgetViewerModal
  1292. Header={stubEl}
  1293. Footer={stubEl as ModalRenderProps['Footer']}
  1294. Body={stubEl as ModalRenderProps['Body']}
  1295. CloseButton={stubEl}
  1296. closeModal={() => undefined}
  1297. organization={initialData.organization}
  1298. widget={mockWidget}
  1299. onEdit={() => undefined}
  1300. />
  1301. );
  1302. expect(await screen.findByText('Another Error: Failed')).toBeInTheDocument();
  1303. });
  1304. it('displays with correct table column widths', async function () {
  1305. initialData.router.location.query = {width: ['-1', '-1', '575']};
  1306. await renderModal({initialData, widget: mockWidget});
  1307. expect(screen.getByTestId('grid-editable')).toHaveStyle({
  1308. 'grid-template-columns':
  1309. ' minmax(90px, auto) minmax(90px, auto) minmax(575px, auto)',
  1310. });
  1311. });
  1312. it('uses provided tableData and does not make an issues requests', async function () {
  1313. await renderModal({initialData, widget: mockWidget, tableData: []});
  1314. expect(issuesMock).not.toHaveBeenCalled();
  1315. });
  1316. it('makes issues requests when table is sorted', async function () {
  1317. await renderModal({
  1318. initialData,
  1319. widget: mockWidget,
  1320. tableData: [],
  1321. });
  1322. expect(issuesMock).not.toHaveBeenCalled();
  1323. userEvent.click(screen.getByText('events'));
  1324. await waitFor(() => {
  1325. expect(issuesMock).toHaveBeenCalled();
  1326. });
  1327. });
  1328. });
  1329. describe('Release Health Widgets', function () {
  1330. let metricsMock;
  1331. const mockQuery = {
  1332. conditions: '',
  1333. fields: [`sum(session)`],
  1334. columns: [],
  1335. aggregates: [],
  1336. id: '1',
  1337. name: 'Query Name',
  1338. orderby: '',
  1339. };
  1340. const mockWidget = {
  1341. id: '1',
  1342. title: 'Release Widget',
  1343. displayType: DisplayType.LINE,
  1344. interval: '5m',
  1345. queries: [mockQuery],
  1346. widgetType: WidgetType.RELEASE,
  1347. };
  1348. beforeEach(function () {
  1349. metricsMock = MockApiClient.addMockResponse({
  1350. url: '/organizations/org-slug/metrics/data/',
  1351. body: TestStubs.MetricsTotalCountByReleaseIn24h(),
  1352. headers: {
  1353. link:
  1354. '<http://localhost/api/0/organizations/org-slug/metrics/data/?cursor=0:0:1>; rel="previous"; results="false"; cursor="0:0:1",' +
  1355. '<http://localhost/api/0/organizations/org-slug/metrics/data/?cursor=0:10:0>; rel="next"; results="true"; cursor="0:10:0"',
  1356. },
  1357. });
  1358. });
  1359. it('does a sessions query', async function () {
  1360. jest.useFakeTimers().setSystemTime(new Date('2022-08-02'));
  1361. await renderModal({initialData, widget: mockWidget});
  1362. expect(metricsMock).toHaveBeenCalled();
  1363. });
  1364. it('renders widget title', async function () {
  1365. await renderModal({initialData, widget: mockWidget});
  1366. expect(screen.getByText('Release Widget')).toBeInTheDocument();
  1367. });
  1368. it('renders Edit and Open in Releases buttons', async function () {
  1369. await renderModal({initialData, widget: mockWidget});
  1370. expect(screen.getByText('Edit Widget')).toBeInTheDocument();
  1371. expect(screen.getByText('Open in Releases')).toBeInTheDocument();
  1372. });
  1373. it('Open in Releases button redirects browser', async function () {
  1374. await renderModal({initialData, widget: mockWidget});
  1375. userEvent.click(screen.getByText('Open in Releases'));
  1376. expect(initialData.router.push).toHaveBeenCalledWith(
  1377. '/organizations/org-slug/releases/?environment=prod&environment=dev&project=1&project=2&statsPeriod=24h'
  1378. );
  1379. });
  1380. it('renders table header and body', async function () {
  1381. await renderModal({initialData, widget: mockWidget});
  1382. expect(screen.getByText('release')).toBeInTheDocument();
  1383. expect(await screen.findByText('e102abb2c46e')).toBeInTheDocument();
  1384. expect(screen.getByText('sum(session)')).toBeInTheDocument();
  1385. expect(screen.getByText('6.3k')).toBeInTheDocument();
  1386. });
  1387. it('renders Release widget viewer', async function () {
  1388. const {container} = await renderModal({initialData, widget: mockWidget});
  1389. expect(await screen.findByText('e102abb2c46e')).toBeInTheDocument();
  1390. expect(container).toSnapshot();
  1391. });
  1392. it('renders pagination buttons', async function () {
  1393. await renderModal({
  1394. initialData,
  1395. widget: mockWidget,
  1396. });
  1397. expect(await screen.findByRole('button', {name: 'Previous'})).toBeInTheDocument();
  1398. expect(screen.getByRole('button', {name: 'Next'})).toBeInTheDocument();
  1399. });
  1400. it('does not render pagination buttons when sorting by release', async function () {
  1401. await renderModal({
  1402. initialData,
  1403. widget: {...mockWidget, queries: [{...mockQuery, orderby: 'release'}]},
  1404. });
  1405. expect(screen.queryByRole('button', {name: 'Previous'})).not.toBeInTheDocument();
  1406. expect(screen.queryByRole('button', {name: 'Next'})).not.toBeInTheDocument();
  1407. });
  1408. it('makes a new sessions request after sorting by a table column', async function () {
  1409. const {rerender} = await renderModal({
  1410. initialData,
  1411. widget: mockWidget,
  1412. tableData: [],
  1413. seriesData: [],
  1414. });
  1415. expect(metricsMock).toHaveBeenCalledTimes(1);
  1416. userEvent.click(screen.getByText(`sum(session)`));
  1417. expect(initialData.router.push).toHaveBeenCalledWith({
  1418. query: {sort: '-sum(session)'},
  1419. });
  1420. // Need to manually set the new router location and rerender to simulate the sortable column click
  1421. initialData.router.location.query = {sort: '-sum(session)'};
  1422. rerender(
  1423. <WidgetViewerModal
  1424. Header={stubEl}
  1425. Footer={stubEl as ModalRenderProps['Footer']}
  1426. Body={stubEl as ModalRenderProps['Body']}
  1427. CloseButton={stubEl}
  1428. closeModal={() => undefined}
  1429. organization={initialData.organization}
  1430. widget={mockWidget}
  1431. onEdit={() => undefined}
  1432. seriesData={[]}
  1433. tableData={[]}
  1434. />
  1435. );
  1436. await waitFor(() => {
  1437. expect(metricsMock).toHaveBeenCalledTimes(2);
  1438. });
  1439. });
  1440. });
  1441. });