widgetBuilder.spec.tsx 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990
  1. import selectEvent from 'react-select-event';
  2. import {urlEncode} from '@sentry/utils';
  3. import {initializeOrg} from 'sentry-test/initializeOrg';
  4. import {
  5. act,
  6. fireEvent,
  7. render,
  8. renderGlobalModal,
  9. screen,
  10. userEvent,
  11. waitFor,
  12. } from 'sentry-test/reactTestingLibrary';
  13. import * as indicators from 'sentry/actionCreators/indicator';
  14. import * as modals from 'sentry/actionCreators/modal';
  15. import TagStore from 'sentry/stores/tagStore';
  16. import {TOP_N} from 'sentry/utils/discover/types';
  17. import {
  18. DashboardDetails,
  19. DashboardWidgetSource,
  20. DisplayType,
  21. Widget,
  22. WidgetType,
  23. } from 'sentry/views/dashboards/types';
  24. import WidgetBuilder, {WidgetBuilderProps} from 'sentry/views/dashboards/widgetBuilder';
  25. const defaultOrgFeatures = [
  26. 'performance-view',
  27. 'dashboards-edit',
  28. 'global-views',
  29. 'dashboards-mep',
  30. ];
  31. // Mocking worldMapChart to avoid act warnings
  32. jest.mock('sentry/components/charts/worldMapChart');
  33. function mockDashboard(dashboard: Partial<DashboardDetails>): DashboardDetails {
  34. return {
  35. id: '1',
  36. title: 'Dashboard',
  37. createdBy: undefined,
  38. dateCreated: '2020-01-01T00:00:00.000Z',
  39. widgets: [],
  40. projects: [],
  41. filters: {},
  42. ...dashboard,
  43. };
  44. }
  45. function renderTestComponent({
  46. dashboard,
  47. query,
  48. orgFeatures,
  49. onSave,
  50. params,
  51. }: {
  52. dashboard?: WidgetBuilderProps['dashboard'];
  53. onSave?: WidgetBuilderProps['onSave'];
  54. orgFeatures?: string[];
  55. params?: Partial<WidgetBuilderProps['params']>;
  56. query?: Record<string, any>;
  57. } = {}) {
  58. const {organization, router, routerContext} = initializeOrg({
  59. ...initializeOrg(),
  60. organization: {
  61. features: orgFeatures ?? defaultOrgFeatures,
  62. },
  63. router: {
  64. location: {
  65. query: {
  66. source: DashboardWidgetSource.DASHBOARDS,
  67. ...query,
  68. },
  69. },
  70. },
  71. });
  72. render(
  73. <WidgetBuilder
  74. route={{}}
  75. router={router}
  76. routes={router.routes}
  77. routeParams={router.params}
  78. location={router.location}
  79. dashboard={{
  80. id: 'new',
  81. title: 'Dashboard',
  82. createdBy: undefined,
  83. dateCreated: '2020-01-01T00:00:00.000Z',
  84. widgets: [],
  85. projects: [],
  86. filters: {},
  87. ...dashboard,
  88. }}
  89. onSave={onSave ?? jest.fn()}
  90. params={{
  91. orgId: organization.slug,
  92. dashboardId: dashboard?.id ?? 'new',
  93. ...params,
  94. }}
  95. />,
  96. {
  97. context: routerContext,
  98. organization,
  99. }
  100. );
  101. return {router};
  102. }
  103. /**
  104. * This test suite contains tests that test the generic interactions
  105. * between most components in the WidgetBuilder. Tests for the
  106. * SortBy step can be found in (and should be added to)
  107. * ./widgetBuilderSortBy.spec.tsx and tests for specific dataset
  108. * behaviour can be found (and should be added to) ./widgetBuilderDataset.spec.tsx.
  109. * The test files are broken up to allow better parallelization
  110. * in CI (we currently parallelize files).
  111. */
  112. describe('WidgetBuilder', function () {
  113. const untitledDashboard: DashboardDetails = {
  114. id: '1',
  115. title: 'Untitled Dashboard',
  116. createdBy: undefined,
  117. dateCreated: '2020-01-01T00:00:00.000Z',
  118. widgets: [],
  119. projects: [],
  120. filters: {},
  121. };
  122. const testDashboard: DashboardDetails = {
  123. id: '2',
  124. title: 'Test Dashboard',
  125. createdBy: undefined,
  126. dateCreated: '2020-01-01T00:00:00.000Z',
  127. widgets: [],
  128. projects: [],
  129. filters: {},
  130. };
  131. let eventsStatsMock: jest.Mock | undefined;
  132. let eventsMock: jest.Mock | undefined;
  133. let tagsMock: jest.Mock | undefined;
  134. beforeEach(function () {
  135. MockApiClient.addMockResponse({
  136. url: '/organizations/org-slug/dashboards/',
  137. body: [
  138. {...untitledDashboard, widgetDisplay: [DisplayType.TABLE]},
  139. {...testDashboard, widgetDisplay: [DisplayType.AREA]},
  140. ],
  141. });
  142. MockApiClient.addMockResponse({
  143. url: '/organizations/org-slug/dashboards/widgets/',
  144. method: 'POST',
  145. statusCode: 200,
  146. body: [],
  147. });
  148. eventsMock = MockApiClient.addMockResponse({
  149. url: '/organizations/org-slug/events/',
  150. method: 'GET',
  151. statusCode: 200,
  152. body: {
  153. meta: {fields: {}},
  154. data: [],
  155. },
  156. });
  157. MockApiClient.addMockResponse({
  158. url: '/organizations/org-slug/projects/',
  159. method: 'GET',
  160. body: [],
  161. });
  162. MockApiClient.addMockResponse({
  163. url: '/organizations/org-slug/recent-searches/',
  164. method: 'GET',
  165. body: [],
  166. });
  167. MockApiClient.addMockResponse({
  168. url: '/organizations/org-slug/recent-searches/',
  169. method: 'POST',
  170. body: [],
  171. });
  172. MockApiClient.addMockResponse({
  173. url: '/organizations/org-slug/issues/',
  174. method: 'GET',
  175. body: [],
  176. });
  177. eventsStatsMock = MockApiClient.addMockResponse({
  178. url: '/organizations/org-slug/events-stats/',
  179. body: [],
  180. });
  181. MockApiClient.addMockResponse({
  182. url: '/organizations/org-slug/tags/event.type/values/',
  183. body: [{count: 2, name: 'Nvidia 1080ti'}],
  184. });
  185. MockApiClient.addMockResponse({
  186. url: '/organizations/org-slug/events-geo/',
  187. body: {data: [], meta: {}},
  188. });
  189. MockApiClient.addMockResponse({
  190. url: '/organizations/org-slug/users/',
  191. body: [],
  192. });
  193. MockApiClient.addMockResponse({
  194. method: 'GET',
  195. url: '/organizations/org-slug/sessions/',
  196. body: TestStubs.SessionsField({
  197. field: `sum(session)`,
  198. }),
  199. });
  200. MockApiClient.addMockResponse({
  201. method: 'GET',
  202. url: '/organizations/org-slug/metrics/data/',
  203. body: TestStubs.MetricsField({
  204. field: 'sum(sentry.sessions.session)',
  205. }),
  206. });
  207. tagsMock = MockApiClient.addMockResponse({
  208. url: '/organizations/org-slug/tags/',
  209. method: 'GET',
  210. body: TestStubs.Tags(),
  211. });
  212. MockApiClient.addMockResponse({
  213. url: '/organizations/org-slug/measurements-meta/',
  214. method: 'GET',
  215. body: {},
  216. });
  217. MockApiClient.addMockResponse({
  218. url: '/organizations/org-slug/tags/is/values/',
  219. method: 'GET',
  220. body: [],
  221. });
  222. MockApiClient.addMockResponse({
  223. url: '/organizations/org-slug/tags/transaction.duration/values/',
  224. method: 'GET',
  225. body: [],
  226. });
  227. MockApiClient.addMockResponse({
  228. url: '/organizations/org-slug/releases/',
  229. body: [],
  230. });
  231. TagStore.reset();
  232. });
  233. afterEach(function () {
  234. MockApiClient.clearMockResponses();
  235. jest.clearAllMocks();
  236. jest.useRealTimers();
  237. });
  238. it('no feature access', function () {
  239. renderTestComponent({orgFeatures: []});
  240. expect(screen.getByText("You don't have access to this feature")).toBeInTheDocument();
  241. });
  242. it('widget not found', function () {
  243. const widget: Widget = {
  244. displayType: DisplayType.AREA,
  245. interval: '1d',
  246. queries: [
  247. {
  248. name: 'Known Users',
  249. fields: [],
  250. columns: [],
  251. aggregates: [],
  252. conditions: '',
  253. orderby: '-time',
  254. },
  255. {
  256. name: 'Anonymous Users',
  257. fields: [],
  258. columns: [],
  259. aggregates: [],
  260. conditions: '',
  261. orderby: '-time',
  262. },
  263. ],
  264. title: 'Transactions',
  265. id: '1',
  266. };
  267. const dashboard = mockDashboard({widgets: [widget]});
  268. renderTestComponent({
  269. dashboard,
  270. orgFeatures: ['dashboards-edit'],
  271. params: {
  272. widgetIndex: '2', // Out of bounds, only one widget
  273. },
  274. });
  275. expect(
  276. screen.getByText('The widget you want to edit was not found.')
  277. ).toBeInTheDocument();
  278. });
  279. it('renders a widget not found message if the widget index url is not an integer', function () {
  280. const widget: Widget = {
  281. displayType: DisplayType.AREA,
  282. interval: '1d',
  283. queries: [
  284. {
  285. name: 'Known Users',
  286. fields: [],
  287. columns: [],
  288. aggregates: [],
  289. conditions: '',
  290. orderby: '-time',
  291. },
  292. ],
  293. title: 'Transactions',
  294. id: '1',
  295. };
  296. const dashboard = mockDashboard({widgets: [widget]});
  297. renderTestComponent({
  298. dashboard,
  299. orgFeatures: ['dashboards-edit'],
  300. params: {
  301. widgetIndex: '0.5', // Invalid index
  302. },
  303. });
  304. expect(
  305. screen.getByText('The widget you want to edit was not found.')
  306. ).toBeInTheDocument();
  307. });
  308. it('renders', async function () {
  309. renderTestComponent();
  310. // Header - Breadcrumbs
  311. expect(await screen.findByRole('link', {name: 'Dashboards'})).toHaveAttribute(
  312. 'href',
  313. '/organizations/org-slug/dashboards/'
  314. );
  315. expect(screen.getByRole('link', {name: 'Dashboard'})).toHaveAttribute(
  316. 'href',
  317. '/organizations/org-slug/dashboards/new/'
  318. );
  319. expect(screen.getByText('Widget Builder')).toBeInTheDocument();
  320. // Header - Widget Title
  321. expect(screen.getByRole('heading', {name: 'Custom Widget'})).toBeInTheDocument();
  322. // Footer - Actions
  323. expect(screen.getByLabelText('Cancel')).toBeInTheDocument();
  324. expect(screen.getByLabelText('Add Widget')).toBeInTheDocument();
  325. // Content - Step 1
  326. expect(
  327. screen.getByRole('heading', {name: 'Choose your dataset'})
  328. ).toBeInTheDocument();
  329. expect(screen.getByLabelText('Errors and Transactions')).toBeChecked();
  330. // Content - Step 2
  331. expect(
  332. screen.getByRole('heading', {name: 'Choose your visualization'})
  333. ).toBeInTheDocument();
  334. // Content - Step 3
  335. expect(
  336. screen.getByRole('heading', {name: 'Choose your columns'})
  337. ).toBeInTheDocument();
  338. // Content - Step 4
  339. expect(
  340. screen.getByRole('heading', {name: 'Filter your results'})
  341. ).toBeInTheDocument();
  342. // Content - Step 5
  343. expect(screen.getByRole('heading', {name: 'Sort by a column'})).toBeInTheDocument();
  344. });
  345. it('has links back to the new dashboard if creating', async function () {
  346. // Dashboard has undefined dashboardId when creating from a new dashboard
  347. // because of route setup
  348. renderTestComponent({params: {dashboardId: undefined}});
  349. expect(await screen.findByLabelText('Cancel')).toHaveAttribute(
  350. 'href',
  351. '/organizations/org-slug/dashboards/new/'
  352. );
  353. });
  354. it('renders new design', async function () {
  355. renderTestComponent({
  356. orgFeatures: [...defaultOrgFeatures],
  357. });
  358. // Switch to line chart for time series
  359. userEvent.click(screen.getByText('Table'));
  360. userEvent.click(screen.getByText('Line Chart'));
  361. // Header - Breadcrumbs
  362. expect(await screen.findByRole('link', {name: 'Dashboards'})).toHaveAttribute(
  363. 'href',
  364. '/organizations/org-slug/dashboards/'
  365. );
  366. expect(screen.getByRole('link', {name: 'Dashboard'})).toHaveAttribute(
  367. 'href',
  368. '/organizations/org-slug/dashboards/new/'
  369. );
  370. expect(screen.getByText('Widget Builder')).toBeInTheDocument();
  371. // Header - Widget Title
  372. expect(screen.getByRole('heading', {name: 'Custom Widget'})).toBeInTheDocument();
  373. // Footer - Actions
  374. expect(screen.getByLabelText('Cancel')).toBeInTheDocument();
  375. expect(screen.getByLabelText('Add Widget')).toBeInTheDocument();
  376. // Content - Step 1
  377. expect(
  378. screen.getByRole('heading', {name: 'Choose your dataset'})
  379. ).toBeInTheDocument();
  380. expect(screen.getByLabelText('Errors and Transactions')).toBeChecked();
  381. // Content - Step 2
  382. expect(
  383. screen.getByRole('heading', {name: 'Choose your visualization'})
  384. ).toBeInTheDocument();
  385. // Content - Step 3
  386. expect(
  387. screen.getByRole('heading', {name: 'Choose what to plot in the y-axis'})
  388. ).toBeInTheDocument();
  389. // Content - Step 4
  390. expect(
  391. screen.getByRole('heading', {name: 'Filter your results'})
  392. ).toBeInTheDocument();
  393. // Content - Step 5
  394. expect(screen.getByRole('heading', {name: 'Group your results'})).toBeInTheDocument();
  395. });
  396. it('can update the title', async function () {
  397. renderTestComponent({
  398. query: {source: DashboardWidgetSource.DISCOVERV2},
  399. });
  400. const customWidgetLabels = await screen.findAllByText('Custom Widget');
  401. // EditableText and chart title
  402. expect(customWidgetLabels).toHaveLength(2);
  403. userEvent.click(customWidgetLabels[0]);
  404. userEvent.clear(screen.getByRole('textbox', {name: 'Widget title'}));
  405. userEvent.paste(screen.getByRole('textbox', {name: 'Widget title'}), 'Unique Users');
  406. userEvent.keyboard('{enter}');
  407. expect(screen.queryByText('Custom Widget')).not.toBeInTheDocument();
  408. expect(screen.getAllByText('Unique Users')).toHaveLength(2);
  409. });
  410. it('can add query conditions', async function () {
  411. const {router} = renderTestComponent({
  412. query: {source: DashboardWidgetSource.DISCOVERV2},
  413. dashboard: testDashboard,
  414. });
  415. const search = await screen.findByTestId(/smart-search-input/);
  416. userEvent.click(search);
  417. // Use fireEvent for performance reasons as this test suite is slow
  418. fireEvent.paste(search, {
  419. target: {value: 'color:blue'},
  420. clipboardData: {getData: () => 'color:blue'},
  421. });
  422. userEvent.keyboard('{enter}');
  423. userEvent.click(screen.getByText('Add Widget'));
  424. await waitFor(() => {
  425. expect(router.push).toHaveBeenCalledWith(
  426. expect.objectContaining({
  427. pathname: '/organizations/org-slug/dashboard/2/',
  428. query: {
  429. displayType: 'table',
  430. interval: '5m',
  431. title: 'Custom Widget',
  432. queryNames: [''],
  433. queryConditions: ['color:blue'],
  434. queryFields: ['count()'],
  435. queryOrderby: '-count()',
  436. start: null,
  437. end: null,
  438. statsPeriod: '24h',
  439. utc: null,
  440. project: [],
  441. environment: [],
  442. },
  443. })
  444. );
  445. });
  446. });
  447. it('can choose a field', async function () {
  448. const {router} = renderTestComponent({
  449. query: {source: DashboardWidgetSource.DISCOVERV2},
  450. dashboard: testDashboard,
  451. });
  452. expect(await screen.findAllByText('Custom Widget')).toHaveLength(2);
  453. // No delete button as there is only one query.
  454. expect(screen.queryByLabelText('Remove query')).not.toBeInTheDocument();
  455. // 1 in the table header, 1 in the column selector, 1 in the sort field
  456. const countFields = screen.getAllByText('count()');
  457. expect(countFields).toHaveLength(3);
  458. await selectEvent.select(countFields[1], ['last_seen()']);
  459. userEvent.click(screen.getByText('Add Widget'));
  460. await waitFor(() => {
  461. expect(router.push).toHaveBeenCalledWith(
  462. expect.objectContaining({
  463. pathname: '/organizations/org-slug/dashboard/2/',
  464. query: {
  465. displayType: 'table',
  466. interval: '5m',
  467. title: 'Custom Widget',
  468. queryNames: [''],
  469. queryConditions: [''],
  470. queryFields: ['last_seen()'],
  471. queryOrderby: '-last_seen()',
  472. start: null,
  473. end: null,
  474. statsPeriod: '24h',
  475. utc: null,
  476. project: [],
  477. environment: [],
  478. },
  479. })
  480. );
  481. });
  482. });
  483. it('can add additional fields', async function () {
  484. const handleSave = jest.fn();
  485. renderTestComponent({onSave: handleSave});
  486. userEvent.click(await screen.findByText('Table'));
  487. // Select line chart display
  488. userEvent.click(screen.getByText('Line Chart'));
  489. // Click the add overlay button
  490. userEvent.click(screen.getByLabelText('Add Overlay'));
  491. await selectEvent.select(screen.getByText('(Required)'), ['count_unique(…)']);
  492. userEvent.click(screen.getByLabelText('Add Widget'));
  493. await waitFor(() => {
  494. expect(handleSave).toHaveBeenCalledWith([
  495. expect.objectContaining({
  496. title: 'Custom Widget',
  497. displayType: DisplayType.LINE,
  498. interval: '5m',
  499. widgetType: WidgetType.DISCOVER,
  500. queries: [
  501. {
  502. conditions: '',
  503. fields: ['count()', 'count_unique(user)'],
  504. aggregates: ['count()', 'count_unique(user)'],
  505. fieldAliases: [],
  506. columns: [],
  507. orderby: '',
  508. name: '',
  509. },
  510. ],
  511. }),
  512. ]);
  513. });
  514. expect(handleSave).toHaveBeenCalledTimes(1);
  515. });
  516. it('can add equation fields', async function () {
  517. const handleSave = jest.fn();
  518. renderTestComponent({onSave: handleSave});
  519. userEvent.click(await screen.findByText('Table'));
  520. // Select line chart display
  521. userEvent.click(screen.getByText('Line Chart'));
  522. // Click the add an equation button
  523. userEvent.click(screen.getByLabelText('Add an Equation'));
  524. expect(screen.getByPlaceholderText('Equation')).toBeInTheDocument();
  525. userEvent.paste(screen.getByPlaceholderText('Equation'), 'count() + 100');
  526. userEvent.click(screen.getByLabelText('Add Widget'));
  527. await waitFor(() => {
  528. expect(handleSave).toHaveBeenCalledWith([
  529. expect.objectContaining({
  530. title: 'Custom Widget',
  531. displayType: DisplayType.LINE,
  532. interval: '5m',
  533. widgetType: WidgetType.DISCOVER,
  534. queries: [
  535. {
  536. name: '',
  537. fields: ['count()', 'equation|count() + 100'],
  538. aggregates: ['count()', 'equation|count() + 100'],
  539. columns: [],
  540. fieldAliases: [],
  541. conditions: '',
  542. orderby: '',
  543. },
  544. ],
  545. }),
  546. ]);
  547. });
  548. expect(handleSave).toHaveBeenCalledTimes(1);
  549. });
  550. it('can respond to validation feedback', async function () {
  551. jest.spyOn(indicators, 'addErrorMessage');
  552. renderTestComponent();
  553. userEvent.click(await screen.findByText('Table'));
  554. const customWidgetLabels = await screen.findAllByText('Custom Widget');
  555. // EditableText and chart title
  556. expect(customWidgetLabels).toHaveLength(2);
  557. userEvent.click(customWidgetLabels[0]);
  558. userEvent.clear(screen.getByRole('textbox', {name: 'Widget title'}));
  559. userEvent.keyboard('{enter}');
  560. expect(indicators.addErrorMessage).toHaveBeenCalledWith('Widget title is required');
  561. });
  562. it('sets up widget data in edit correctly', async function () {
  563. const widget: Widget = {
  564. id: '1',
  565. title: 'Errors over time',
  566. interval: '5m',
  567. displayType: DisplayType.LINE,
  568. queries: [
  569. {
  570. name: 'errors',
  571. conditions: 'event.type:error',
  572. fields: ['count()', 'count_unique(id)'],
  573. aggregates: ['count()', 'count_unique(id)'],
  574. columns: [],
  575. orderby: '',
  576. },
  577. {
  578. name: 'csp',
  579. conditions: 'event.type:csp',
  580. fields: ['count()', 'count_unique(id)'],
  581. aggregates: ['count()', 'count_unique(id)'],
  582. columns: [],
  583. orderby: '',
  584. },
  585. ],
  586. };
  587. const dashboard = mockDashboard({widgets: [widget]});
  588. renderTestComponent({dashboard, params: {widgetIndex: '0'}});
  589. await screen.findByText('Line Chart');
  590. // Should be in edit 'mode'
  591. expect(await screen.findByText('Update Widget')).toBeInTheDocument();
  592. // Should set widget data up.
  593. expect(screen.getByText('Update Widget')).toBeInTheDocument();
  594. // Filters
  595. expect(
  596. screen.getAllByPlaceholderText('Search for events, users, tags, and more')
  597. ).toHaveLength(2);
  598. expect(screen.getByText('event.type:csp')).toBeInTheDocument();
  599. expect(screen.getByText('event.type:error')).toBeInTheDocument();
  600. // Y-axis
  601. expect(screen.getAllByRole('button', {name: 'Remove query'})).toHaveLength(2);
  602. expect(screen.getByText('count()')).toBeInTheDocument();
  603. expect(screen.getByText('count_unique(…)')).toBeInTheDocument();
  604. expect(screen.getByText('id')).toBeInTheDocument();
  605. // Expect events-stats endpoint to be called for each search conditions with
  606. // the same y-axis parameters
  607. expect(eventsStatsMock).toHaveBeenNthCalledWith(
  608. 1,
  609. '/organizations/org-slug/events-stats/',
  610. expect.objectContaining({
  611. query: expect.objectContaining({
  612. query: 'event.type:error',
  613. yAxis: ['count()', 'count_unique(id)'],
  614. }),
  615. })
  616. );
  617. expect(eventsStatsMock).toHaveBeenNthCalledWith(
  618. 2,
  619. '/organizations/org-slug/events-stats/',
  620. expect.objectContaining({
  621. query: expect.objectContaining({
  622. query: 'event.type:csp',
  623. yAxis: ['count()', 'count_unique(id)'],
  624. }),
  625. })
  626. );
  627. });
  628. it('can edit a widget', async function () {
  629. const widget: Widget = {
  630. id: '1',
  631. title: 'Errors over time',
  632. interval: '5m',
  633. displayType: DisplayType.LINE,
  634. queries: [
  635. {
  636. name: 'errors',
  637. conditions: 'event.type:error',
  638. fields: ['count()', 'count_unique(id)'],
  639. aggregates: ['count()', 'count_unique(id)'],
  640. columns: [],
  641. orderby: '',
  642. },
  643. {
  644. name: 'csp',
  645. conditions: 'event.type:csp',
  646. fields: ['count()', 'count_unique(id)'],
  647. aggregates: ['count()', 'count_unique(id)'],
  648. columns: [],
  649. orderby: '',
  650. },
  651. ],
  652. };
  653. const dashboard = mockDashboard({widgets: [widget]});
  654. const handleSave = jest.fn();
  655. renderTestComponent({onSave: handleSave, dashboard, params: {widgetIndex: '0'}});
  656. await screen.findByText('Line Chart');
  657. // Should be in edit 'mode'
  658. expect(screen.getByText('Update Widget')).toBeInTheDocument();
  659. const customWidgetLabels = screen.getAllByText(widget.title);
  660. // EditableText and chart title
  661. expect(customWidgetLabels).toHaveLength(2);
  662. userEvent.click(customWidgetLabels[0]);
  663. userEvent.clear(screen.getByRole('textbox', {name: 'Widget title'}));
  664. userEvent.paste(screen.getByRole('textbox', {name: 'Widget title'}), 'New Title');
  665. userEvent.click(screen.getByRole('button', {name: 'Update Widget'}));
  666. await waitFor(() => {
  667. expect(handleSave).toHaveBeenCalledWith([
  668. expect.objectContaining({
  669. ...widget,
  670. title: 'New Title',
  671. }),
  672. ]);
  673. });
  674. expect(handleSave).toHaveBeenCalledTimes(1);
  675. });
  676. it('renders column inputs for table widgets', async function () {
  677. const widget: Widget = {
  678. id: '0',
  679. title: 'sdk usage',
  680. interval: '5m',
  681. displayType: DisplayType.TABLE,
  682. queries: [
  683. {
  684. name: 'errors',
  685. conditions: 'event.type:error',
  686. fields: ['sdk.name', 'count()'],
  687. columns: ['sdk.name'],
  688. aggregates: ['count()'],
  689. orderby: '',
  690. },
  691. ],
  692. };
  693. const dashboard = mockDashboard({widgets: [widget]});
  694. renderTestComponent({dashboard, params: {widgetIndex: '0'}});
  695. // Should be in edit 'mode'
  696. expect(await screen.findByText('Update Widget')).toBeInTheDocument();
  697. // Should set widget data up.
  698. expect(screen.getByRole('heading', {name: widget.title})).toBeInTheDocument();
  699. expect(screen.getByText('Table')).toBeInTheDocument();
  700. expect(screen.getByLabelText('Search events')).toBeInTheDocument();
  701. // Should have an orderby select
  702. expect(screen.getByText('Sort by a column')).toBeInTheDocument();
  703. // Add a column, and choose a value,
  704. expect(screen.getByLabelText('Add a Column')).toBeInTheDocument();
  705. });
  706. it('can save table widgets', async function () {
  707. const widget: Widget = {
  708. id: '0',
  709. title: 'sdk usage',
  710. interval: '5m',
  711. displayType: DisplayType.TABLE,
  712. queries: [
  713. {
  714. name: 'errors',
  715. conditions: 'event.type:error',
  716. fields: ['sdk.name', 'count()'],
  717. columns: ['sdk.name'],
  718. aggregates: ['count()'],
  719. orderby: '-count()',
  720. },
  721. ],
  722. };
  723. const dashboard = mockDashboard({widgets: [widget]});
  724. const handleSave = jest.fn();
  725. renderTestComponent({dashboard, onSave: handleSave, params: {widgetIndex: '0'}});
  726. // Should be in edit 'mode'
  727. expect(await screen.findByText('Update Widget')).toBeInTheDocument();
  728. // Add a column, and choose a value,
  729. userEvent.click(screen.getByLabelText('Add a Column'));
  730. await selectEvent.select(screen.getByText('(Required)'), 'trace');
  731. // Save widget
  732. userEvent.click(screen.getByLabelText('Update Widget'));
  733. await waitFor(() => {
  734. expect(handleSave).toHaveBeenCalledWith([
  735. expect.objectContaining({
  736. id: '0',
  737. title: 'sdk usage',
  738. displayType: DisplayType.TABLE,
  739. interval: '5m',
  740. queries: [
  741. {
  742. name: 'errors',
  743. conditions: 'event.type:error',
  744. fields: ['sdk.name', 'count()', 'trace'],
  745. aggregates: ['count()'],
  746. columns: ['sdk.name', 'trace'],
  747. orderby: '-count()',
  748. fieldAliases: ['', '', ''],
  749. },
  750. ],
  751. widgetType: WidgetType.DISCOVER,
  752. }),
  753. ]);
  754. });
  755. expect(handleSave).toHaveBeenCalledTimes(1);
  756. });
  757. it('should properly query for table fields', async function () {
  758. const defaultWidgetQuery = {
  759. name: '',
  760. fields: ['title', 'count()'],
  761. columns: ['title'],
  762. aggregates: ['count()'],
  763. conditions: '',
  764. orderby: '',
  765. };
  766. const defaultTableColumns = ['title', 'count()', 'count_unique(user)', 'epm()'];
  767. renderTestComponent({
  768. query: {
  769. source: DashboardWidgetSource.DISCOVERV2,
  770. defaultWidgetQuery: urlEncode(defaultWidgetQuery),
  771. displayType: DisplayType.LINE,
  772. defaultTableColumns,
  773. },
  774. });
  775. expect(await screen.findByText('Line Chart')).toBeInTheDocument();
  776. userEvent.click(screen.getByText('Line Chart'));
  777. userEvent.click(screen.getByText('Table'));
  778. await waitFor(() => {
  779. expect(eventsMock).toHaveBeenLastCalledWith(
  780. '/organizations/org-slug/events/',
  781. expect.objectContaining({
  782. query: expect.objectContaining({
  783. field: defaultTableColumns,
  784. }),
  785. })
  786. );
  787. });
  788. });
  789. it('should use defaultWidgetQuery Y-Axis and Conditions if given a defaultWidgetQuery', async function () {
  790. const defaultWidgetQuery = {
  791. name: '',
  792. fields: ['count()', 'failure_count()', 'count_unique(user)'],
  793. columns: [],
  794. aggregates: ['count()', 'failure_count()', 'count_unique(user)'],
  795. conditions: 'tag:value',
  796. orderby: '',
  797. };
  798. renderTestComponent({
  799. query: {
  800. source: DashboardWidgetSource.DISCOVERV2,
  801. defaultWidgetQuery: urlEncode(defaultWidgetQuery),
  802. },
  803. });
  804. expect(await screen.findByText('tag:value')).toBeInTheDocument();
  805. // Table display, column, and sort field
  806. expect(screen.getAllByText('count()')).toHaveLength(3);
  807. // Table display and column
  808. expect(screen.getAllByText('failure_count()')).toHaveLength(2);
  809. // Table display
  810. expect(screen.getByText('count_unique(user)')).toBeInTheDocument();
  811. // Column
  812. expect(screen.getByText('count_unique(…)')).toBeInTheDocument();
  813. // Column
  814. expect(screen.getByText('user')).toBeInTheDocument();
  815. });
  816. it('uses displayType if given a displayType', async function () {
  817. renderTestComponent({
  818. query: {
  819. displayType: DisplayType.BAR,
  820. },
  821. });
  822. expect(await screen.findByText('Bar Chart')).toBeInTheDocument();
  823. });
  824. it('deletes the widget when the modal is confirmed', async () => {
  825. const handleSave = jest.fn();
  826. const widget: Widget = {
  827. id: '1',
  828. title: 'Errors over time',
  829. interval: '5m',
  830. displayType: DisplayType.LINE,
  831. queries: [
  832. {
  833. name: 'errors',
  834. conditions: 'event.type:error',
  835. fields: ['count()', 'count_unique(id)'],
  836. aggregates: ['count()', 'count_unique(id)'],
  837. columns: [],
  838. orderby: '',
  839. },
  840. {
  841. name: 'csp',
  842. conditions: 'event.type:csp',
  843. fields: ['count()', 'count_unique(id)'],
  844. aggregates: ['count()', 'count_unique(id)'],
  845. columns: [],
  846. orderby: '',
  847. },
  848. ],
  849. };
  850. const dashboard = mockDashboard({widgets: [widget]});
  851. renderTestComponent({onSave: handleSave, dashboard, params: {widgetIndex: '0'}});
  852. userEvent.click(await screen.findByText('Delete'));
  853. renderGlobalModal();
  854. userEvent.click(await screen.findByText('Confirm'));
  855. await waitFor(() => {
  856. // The only widget was deleted
  857. expect(handleSave).toHaveBeenCalledWith([]);
  858. });
  859. expect(handleSave).toHaveBeenCalledTimes(1);
  860. });
  861. it('persists the page filter period when updating a widget', async () => {
  862. const widget: Widget = {
  863. id: '1',
  864. title: 'Errors over time',
  865. interval: '5m',
  866. displayType: DisplayType.LINE,
  867. queries: [
  868. {
  869. name: 'errors',
  870. conditions: 'event.type:error',
  871. fields: ['count()', 'count_unique(id)'],
  872. aggregates: ['count()', 'count_unique(id)'],
  873. columns: [],
  874. orderby: '',
  875. },
  876. ],
  877. };
  878. const dashboard = mockDashboard({widgets: [widget]});
  879. const {router} = renderTestComponent({
  880. dashboard,
  881. params: {orgId: 'org-slug', widgetIndex: '0'},
  882. query: {statsPeriod: '90d'},
  883. });
  884. userEvent.click(screen.getByText('Update Widget'));
  885. await waitFor(() => {
  886. expect(router.push).toHaveBeenLastCalledWith(
  887. expect.objectContaining({
  888. pathname: '/organizations/org-slug/dashboard/1/',
  889. query: expect.objectContaining({
  890. statsPeriod: '90d',
  891. }),
  892. })
  893. );
  894. });
  895. });
  896. it('renders page filters in the filter step', async () => {
  897. const mockReleases = MockApiClient.addMockResponse({
  898. url: '/organizations/org-slug/releases/',
  899. body: [TestStubs.Release()],
  900. });
  901. renderTestComponent({
  902. params: {orgId: 'org-slug'},
  903. query: {statsPeriod: '90d'},
  904. orgFeatures: defaultOrgFeatures,
  905. });
  906. expect(await screen.findByTestId('page-filter-timerange-selector')).toBeDisabled();
  907. expect(screen.getByTestId('page-filter-environment-selector')).toBeDisabled();
  908. expect(screen.getByTestId('page-filter-project-selector-loading')).toBeDisabled();
  909. expect(mockReleases).toHaveBeenCalled();
  910. expect(screen.getByRole('button', {name: /all releases/i})).toBeDisabled();
  911. });
  912. it('appends dashboard filters to widget builder fetch data request', async () => {
  913. MockApiClient.addMockResponse({
  914. url: '/organizations/org-slug/releases/',
  915. body: [TestStubs.Release()],
  916. });
  917. const mock = MockApiClient.addMockResponse({
  918. url: '/organizations/org-slug/events/',
  919. body: [],
  920. });
  921. renderTestComponent({
  922. dashboard: {
  923. id: 'new',
  924. title: 'Dashboard',
  925. createdBy: undefined,
  926. dateCreated: '2020-01-01T00:00:00.000Z',
  927. widgets: [],
  928. projects: [],
  929. filters: {release: ['abc@1.2.0']},
  930. },
  931. params: {orgId: 'org-slug'},
  932. query: {statsPeriod: '90d'},
  933. orgFeatures: defaultOrgFeatures,
  934. });
  935. await waitFor(() => {
  936. expect(mock).toHaveBeenCalledWith(
  937. '/organizations/org-slug/events/',
  938. expect.objectContaining({
  939. query: expect.objectContaining({
  940. query: ' release:abc@1.2.0 ',
  941. }),
  942. })
  943. );
  944. });
  945. });
  946. it('does not error when query conditions field is blurred', async function () {
  947. jest.useFakeTimers();
  948. const widget: Widget = {
  949. id: '0',
  950. title: 'sdk usage',
  951. interval: '5m',
  952. displayType: DisplayType.BAR,
  953. queries: [
  954. {
  955. name: 'filled in',
  956. conditions: 'event.type:error',
  957. fields: ['count()', 'count_unique(id)'],
  958. aggregates: ['count()', 'count_unique(id)'],
  959. columns: [],
  960. orderby: '-count()',
  961. },
  962. ],
  963. };
  964. const dashboard = mockDashboard({widgets: [widget]});
  965. const handleSave = jest.fn();
  966. renderTestComponent({dashboard, onSave: handleSave, params: {widgetIndex: '0'}});
  967. userEvent.click(await screen.findByLabelText('Add Query'));
  968. // Triggering the onBlur of the new field should not error
  969. userEvent.click(
  970. screen.getAllByPlaceholderText('Search for events, users, tags, and more')[1]
  971. );
  972. userEvent.keyboard('{esc}');
  973. // Run all timers because the handleBlur contains a setTimeout
  974. jest.runAllTimers();
  975. });
  976. it('does not wipe column changes when filters are modified', async function () {
  977. jest.useFakeTimers();
  978. // widgetIndex: undefined means creating a new widget
  979. renderTestComponent({params: {widgetIndex: undefined}});
  980. userEvent.click(await screen.findByLabelText('Add a Column'));
  981. await selectEvent.select(screen.getByText('(Required)'), /project/);
  982. // Triggering the onBlur of the filter should not error
  983. userEvent.click(
  984. screen.getByPlaceholderText('Search for events, users, tags, and more')
  985. );
  986. userEvent.keyboard('{enter}');
  987. expect(await screen.findAllByText('project')).toHaveLength(2);
  988. });
  989. it('renders fields with commas properly', async () => {
  990. const defaultWidgetQuery = {
  991. conditions: '',
  992. fields: ['equation|count_if(transaction.duration,equals,300)*2'],
  993. aggregates: ['equation|count_if(transaction.duration,equals,300)*2'],
  994. columns: [],
  995. orderby: '',
  996. name: '',
  997. };
  998. const defaultTableColumns = [
  999. 'count_if(transaction.duration,equals,300)',
  1000. 'equation|count_if(transaction.duration,equals,300)*2',
  1001. ];
  1002. renderTestComponent({
  1003. query: {
  1004. source: DashboardWidgetSource.DISCOVERV2,
  1005. defaultWidgetQuery: urlEncode(defaultWidgetQuery),
  1006. defaultTableColumns,
  1007. yAxis: ['equation|count_if(transaction.duration,equals,300)*2'],
  1008. },
  1009. });
  1010. expect(
  1011. await screen.findByText('count_if(transaction.duration,equals,300)*2')
  1012. ).toBeInTheDocument();
  1013. });
  1014. it('sets the correct fields for a top n widget', async () => {
  1015. renderTestComponent({
  1016. orgFeatures: [...defaultOrgFeatures, 'performance-view'],
  1017. query: {
  1018. displayType: DisplayType.TOP_N,
  1019. },
  1020. });
  1021. // Top N now opens as Area Chart
  1022. expect(await screen.findByText('Area Chart')).toBeInTheDocument();
  1023. // Add a group by
  1024. userEvent.click(screen.getByText('Add Overlay'));
  1025. await selectEvent.select(screen.getByText('Select group'), /project/);
  1026. // Change the y-axis
  1027. await selectEvent.select(screen.getAllByText('count()')[0], 'eps()');
  1028. await waitFor(() => {
  1029. expect(eventsStatsMock).toHaveBeenLastCalledWith(
  1030. '/organizations/org-slug/events-stats/',
  1031. expect.objectContaining({
  1032. query: expect.objectContaining({
  1033. query: '',
  1034. yAxis: ['eps()'],
  1035. field: ['project', 'eps()'],
  1036. topEvents: TOP_N,
  1037. orderby: '-eps()',
  1038. }),
  1039. })
  1040. );
  1041. });
  1042. });
  1043. it('fetches tags when tag store is empty', async function () {
  1044. renderTestComponent();
  1045. await waitFor(() => {
  1046. expect(tagsMock).toHaveBeenCalled();
  1047. });
  1048. });
  1049. it('does not fetch tags when tag store is not empty', async function () {
  1050. await act(async () => {
  1051. TagStore.loadTagsSuccess(TestStubs.Tags());
  1052. renderTestComponent();
  1053. await tick();
  1054. });
  1055. expect(tagsMock).not.toHaveBeenCalled();
  1056. });
  1057. it('excludes the Other series when grouping and using multiple y-axes', async function () {
  1058. renderTestComponent({
  1059. orgFeatures: [...defaultOrgFeatures],
  1060. query: {
  1061. displayType: DisplayType.LINE,
  1062. },
  1063. });
  1064. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1065. userEvent.click(screen.getByText('Add Overlay'));
  1066. await selectEvent.select(screen.getByText('(Required)'), /count_unique/);
  1067. await waitFor(() => {
  1068. expect(eventsStatsMock).toHaveBeenCalledWith(
  1069. '/organizations/org-slug/events-stats/',
  1070. expect.objectContaining({
  1071. query: expect.objectContaining({excludeOther: '1'}),
  1072. })
  1073. );
  1074. });
  1075. });
  1076. it('excludes the Other series when grouping and using multiple queries', async function () {
  1077. renderTestComponent({
  1078. orgFeatures: [...defaultOrgFeatures],
  1079. query: {
  1080. displayType: DisplayType.LINE,
  1081. },
  1082. });
  1083. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1084. userEvent.click(screen.getByText('Add Query'));
  1085. await waitFor(() => {
  1086. expect(eventsStatsMock).toHaveBeenCalledWith(
  1087. '/organizations/org-slug/events-stats/',
  1088. expect.objectContaining({
  1089. query: expect.objectContaining({excludeOther: '1'}),
  1090. })
  1091. );
  1092. });
  1093. });
  1094. it('includes Other series when there is only one query and one y-axis', async function () {
  1095. renderTestComponent({
  1096. orgFeatures: [...defaultOrgFeatures],
  1097. query: {
  1098. displayType: DisplayType.LINE,
  1099. },
  1100. });
  1101. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1102. await waitFor(() => {
  1103. expect(eventsStatsMock).toHaveBeenCalledWith(
  1104. '/organizations/org-slug/events-stats/',
  1105. expect.objectContaining({
  1106. query: expect.not.objectContaining({excludeOther: '1'}),
  1107. })
  1108. );
  1109. });
  1110. });
  1111. it('decreases the limit when more y-axes and queries are added', async function () {
  1112. renderTestComponent({
  1113. orgFeatures: [...defaultOrgFeatures],
  1114. query: {
  1115. displayType: DisplayType.LINE,
  1116. },
  1117. });
  1118. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1119. screen.getByText('Limit to 5 results');
  1120. userEvent.click(screen.getByText('Add Query'));
  1121. userEvent.click(screen.getByText('Add Overlay'));
  1122. expect(screen.getByText('Limit to 2 results')).toBeInTheDocument();
  1123. });
  1124. it('alerts the user if there are unsaved changes', async function () {
  1125. const {router} = renderTestComponent();
  1126. const alertMock = jest.fn();
  1127. const setRouteLeaveHookMock = jest.spyOn(router, 'setRouteLeaveHook');
  1128. setRouteLeaveHookMock.mockImplementationOnce((_route, _callback) => {
  1129. alertMock();
  1130. });
  1131. const customWidgetLabels = await screen.findAllByText('Custom Widget');
  1132. // EditableText and chart title
  1133. expect(customWidgetLabels).toHaveLength(2);
  1134. // Change title text
  1135. userEvent.click(customWidgetLabels[0]);
  1136. userEvent.clear(screen.getByRole('textbox', {name: 'Widget title'}));
  1137. userEvent.paste(screen.getByRole('textbox', {name: 'Widget title'}), 'Unique Users');
  1138. userEvent.keyboard('{enter}');
  1139. // Click Cancel
  1140. userEvent.click(screen.getByText('Cancel'));
  1141. // Assert an alert was triggered
  1142. expect(alertMock).toHaveBeenCalled();
  1143. });
  1144. it('does not trigger alert dialog if no changes', async function () {
  1145. const {router} = renderTestComponent();
  1146. const alertMock = jest.fn();
  1147. const setRouteLeaveHookMock = jest.spyOn(router, 'setRouteLeaveHook');
  1148. setRouteLeaveHookMock.mockImplementationOnce((_route, _callback) => {
  1149. alertMock();
  1150. });
  1151. // Click Cancel
  1152. userEvent.click(await screen.findByText('Cancel'));
  1153. // Assert an alert was triggered
  1154. expect(alertMock).not.toHaveBeenCalled();
  1155. });
  1156. describe('Widget creation coming from other verticals', function () {
  1157. it('redirects correctly when creating a new dashboard', async function () {
  1158. const {router} = renderTestComponent({
  1159. query: {source: DashboardWidgetSource.DISCOVERV2},
  1160. });
  1161. userEvent.click(await screen.findByText('Add Widget'));
  1162. await waitFor(() => {
  1163. expect(router.push).toHaveBeenCalledWith(
  1164. expect.objectContaining({
  1165. pathname: '/organizations/org-slug/dashboards/new/',
  1166. query: {
  1167. displayType: 'table',
  1168. interval: '5m',
  1169. title: 'Custom Widget',
  1170. queryNames: [''],
  1171. queryConditions: [''],
  1172. queryFields: ['count()'],
  1173. queryOrderby: '-count()',
  1174. start: null,
  1175. end: null,
  1176. statsPeriod: '24h',
  1177. utc: null,
  1178. project: [],
  1179. environment: [],
  1180. },
  1181. })
  1182. );
  1183. });
  1184. });
  1185. it('redirects correctly when choosing an existing dashboard', async function () {
  1186. const {router} = renderTestComponent({
  1187. query: {source: DashboardWidgetSource.DISCOVERV2},
  1188. dashboard: testDashboard,
  1189. });
  1190. userEvent.click(await screen.findByText('Add Widget'));
  1191. await waitFor(() => {
  1192. expect(router.push).toHaveBeenCalledWith(
  1193. expect.objectContaining({
  1194. pathname: '/organizations/org-slug/dashboard/2/',
  1195. query: {
  1196. displayType: 'table',
  1197. interval: '5m',
  1198. title: 'Custom Widget',
  1199. queryNames: [''],
  1200. queryConditions: [''],
  1201. queryFields: ['count()'],
  1202. queryOrderby: '-count()',
  1203. start: null,
  1204. end: null,
  1205. statsPeriod: '24h',
  1206. utc: null,
  1207. project: [],
  1208. environment: [],
  1209. },
  1210. })
  1211. );
  1212. });
  1213. });
  1214. it('shows the correct orderby when switching from a line chart to table', async function () {
  1215. const defaultWidgetQuery = {
  1216. name: '',
  1217. fields: ['count_unique(user)'],
  1218. columns: [],
  1219. aggregates: ['count_unique(user)'],
  1220. conditions: '',
  1221. orderby: 'count_unique(user)',
  1222. };
  1223. const defaultTableColumns = ['title', 'count_unique(user)'];
  1224. renderTestComponent({
  1225. orgFeatures: [...defaultOrgFeatures],
  1226. query: {
  1227. source: DashboardWidgetSource.DISCOVERV2,
  1228. defaultWidgetQuery: urlEncode(defaultWidgetQuery),
  1229. displayType: DisplayType.LINE,
  1230. defaultTableColumns,
  1231. },
  1232. });
  1233. userEvent.click(await screen.findByText('Line Chart'));
  1234. userEvent.click(screen.getByText('Table'));
  1235. expect(screen.getByText('count_unique(user)')).toBeInTheDocument();
  1236. await waitFor(() => {
  1237. expect(eventsMock).toHaveBeenLastCalledWith(
  1238. '/organizations/org-slug/events/',
  1239. expect.objectContaining({
  1240. query: expect.objectContaining({
  1241. field: defaultTableColumns,
  1242. sort: ['count_unique(user)'],
  1243. }),
  1244. })
  1245. );
  1246. });
  1247. });
  1248. it('does not send request with orderby if a timeseries chart without grouping', async function () {
  1249. const defaultWidgetQuery = {
  1250. name: '',
  1251. fields: ['count_unique(user)'],
  1252. columns: [],
  1253. aggregates: ['count_unique(user)'],
  1254. conditions: '',
  1255. orderby: 'count_unique(user)',
  1256. };
  1257. const defaultTableColumns = ['title', 'count_unique(user)'];
  1258. renderTestComponent({
  1259. orgFeatures: [...defaultOrgFeatures],
  1260. query: {
  1261. source: DashboardWidgetSource.DISCOVERV2,
  1262. defaultWidgetQuery: urlEncode(defaultWidgetQuery),
  1263. displayType: DisplayType.LINE,
  1264. defaultTableColumns,
  1265. },
  1266. });
  1267. await waitFor(() => {
  1268. expect(eventsStatsMock).toHaveBeenLastCalledWith(
  1269. '/organizations/org-slug/events-stats/',
  1270. expect.objectContaining({
  1271. query: expect.objectContaining({
  1272. orderby: '',
  1273. }),
  1274. })
  1275. );
  1276. });
  1277. });
  1278. });
  1279. it('opens top-N widgets as area display', async function () {
  1280. const widget: Widget = {
  1281. id: '1',
  1282. title: 'Errors over time',
  1283. interval: '5m',
  1284. displayType: DisplayType.TOP_N,
  1285. queries: [
  1286. {
  1287. name: '',
  1288. conditions: '',
  1289. fields: ['count()', 'count_unique(id)'],
  1290. aggregates: ['count()', 'count_unique(id)'],
  1291. columns: [],
  1292. orderby: '-count()',
  1293. },
  1294. ],
  1295. };
  1296. const dashboard = mockDashboard({widgets: [widget]});
  1297. renderTestComponent({
  1298. orgFeatures: [...defaultOrgFeatures],
  1299. dashboard,
  1300. params: {
  1301. widgetIndex: '0',
  1302. },
  1303. });
  1304. expect(await screen.findByText('Area Chart')).toBeInTheDocument();
  1305. });
  1306. it('Update table header values (field alias)', async function () {
  1307. const handleSave = jest.fn();
  1308. renderTestComponent({
  1309. onSave: handleSave,
  1310. orgFeatures: [...defaultOrgFeatures],
  1311. });
  1312. userEvent.paste(screen.getByPlaceholderText('Alias'), 'First Alias');
  1313. userEvent.click(screen.getByLabelText('Add a Column'));
  1314. userEvent.paste(screen.getAllByPlaceholderText('Alias')[1], 'Second Alias');
  1315. userEvent.click(screen.getByText('Add Widget'));
  1316. await waitFor(() => {
  1317. expect(handleSave).toHaveBeenCalledWith([
  1318. expect.objectContaining({
  1319. queries: [
  1320. expect.objectContaining({fieldAliases: ['First Alias', 'Second Alias']}),
  1321. ],
  1322. }),
  1323. ]);
  1324. });
  1325. });
  1326. it('does not wipe equation aliases when a column alias is updated', async function () {
  1327. renderTestComponent({
  1328. orgFeatures: [...defaultOrgFeatures],
  1329. });
  1330. userEvent.click(screen.getByText('Add an Equation'));
  1331. userEvent.paste(screen.getAllByPlaceholderText('Alias')[1], 'This should persist');
  1332. userEvent.type(screen.getAllByPlaceholderText('Alias')[0], 'A');
  1333. expect(await screen.findByText('This should persist')).toBeInTheDocument();
  1334. });
  1335. it('does not wipe equation aliases when a column selection is made', async function () {
  1336. renderTestComponent({
  1337. orgFeatures: [...defaultOrgFeatures],
  1338. });
  1339. userEvent.click(screen.getByText('Add an Equation'));
  1340. userEvent.paste(screen.getAllByPlaceholderText('Alias')[1], 'This should persist');
  1341. // 1 for the table, 1 for the the column selector, 1 for the sort
  1342. await waitFor(() => expect(screen.getAllByText('count()')).toHaveLength(3));
  1343. await selectEvent.select(screen.getAllByText('count()')[1], /count_unique/);
  1344. expect(screen.getByText('This should persist')).toBeInTheDocument();
  1345. });
  1346. it('copies over the orderby from the previous query if adding another', async function () {
  1347. renderTestComponent({
  1348. orgFeatures: [...defaultOrgFeatures],
  1349. });
  1350. userEvent.click(await screen.findByText('Table'));
  1351. userEvent.click(screen.getByText('Line Chart'));
  1352. await selectEvent.select(screen.getByText('Select group'), 'project');
  1353. await selectEvent.select(screen.getAllByText('count()')[1], 'count_unique(…)');
  1354. MockApiClient.clearMockResponses();
  1355. eventsStatsMock = MockApiClient.addMockResponse({
  1356. url: '/organizations/org-slug/events-stats/',
  1357. body: [],
  1358. });
  1359. userEvent.click(screen.getByText('Add Query'));
  1360. // Assert on two calls, one for each query
  1361. const expectedArgs = expect.objectContaining({
  1362. query: expect.objectContaining({
  1363. orderby: '-count_unique(user)',
  1364. }),
  1365. });
  1366. expect(eventsStatsMock).toHaveBeenNthCalledWith(
  1367. 1,
  1368. '/organizations/org-slug/events-stats/',
  1369. expectedArgs
  1370. );
  1371. expect(eventsStatsMock).toHaveBeenNthCalledWith(
  1372. 2,
  1373. '/organizations/org-slug/events-stats/',
  1374. expectedArgs
  1375. );
  1376. });
  1377. it('disables add widget button and prevents widget previewing from firing widget query if widget query condition is invalid', async function () {
  1378. renderTestComponent({
  1379. orgFeatures: [...defaultOrgFeatures],
  1380. });
  1381. userEvent.click(await screen.findByText('Table'));
  1382. userEvent.click(screen.getByText('Line Chart'));
  1383. expect(eventsStatsMock).toHaveBeenCalledTimes(1);
  1384. userEvent.type(screen.getByTestId('smart-search-input'), 'transaction.duration:123a');
  1385. // Unfocus input
  1386. userEvent.click(screen.getByText('Filter your results'));
  1387. expect(screen.getByText('Add Widget').closest('button')).toBeDisabled();
  1388. expect(screen.getByText('Widget query condition is invalid.')).toBeInTheDocument();
  1389. expect(eventsStatsMock).toHaveBeenCalledTimes(1);
  1390. });
  1391. describe('Widget Library', function () {
  1392. it('only opens the modal when the query data is changed', async function () {
  1393. const mockModal = jest.spyOn(modals, 'openWidgetBuilderOverwriteModal');
  1394. renderTestComponent();
  1395. await screen.findByText('Widget Library');
  1396. userEvent.click(screen.getByText('Duration Distribution'));
  1397. // Widget Library, Builder title, and Chart title
  1398. expect(screen.getAllByText('Duration Distribution')).toHaveLength(3);
  1399. // Confirm modal doesn't open because no changes were made
  1400. expect(mockModal).not.toHaveBeenCalled();
  1401. userEvent.click(screen.getAllByLabelText('Remove this Y-Axis')[0]);
  1402. userEvent.click(screen.getByText('High Throughput Transactions'));
  1403. // Should not have overwritten widget data, and confirm modal should open
  1404. expect(screen.getAllByText('Duration Distribution')).toHaveLength(3);
  1405. expect(mockModal).toHaveBeenCalled();
  1406. });
  1407. });
  1408. describe('group by field', function () {
  1409. it('does not contain functions as options', async function () {
  1410. renderTestComponent({
  1411. query: {displayType: 'line'},
  1412. orgFeatures: [...defaultOrgFeatures],
  1413. });
  1414. expect(await screen.findByText('Select group')).toBeInTheDocument();
  1415. userEvent.click(screen.getByText('Select group'));
  1416. // Only one f(x) field set in the y-axis selector
  1417. expect(screen.getByText('f(x)')).toBeInTheDocument();
  1418. });
  1419. it('adds more fields when Add Group is clicked', async function () {
  1420. renderTestComponent({
  1421. query: {displayType: 'line'},
  1422. orgFeatures: [...defaultOrgFeatures],
  1423. });
  1424. userEvent.click(await screen.findByText('Add Group'));
  1425. expect(await screen.findAllByText('Select group')).toHaveLength(2);
  1426. });
  1427. it("doesn't reset group by when changing y-axis", async function () {
  1428. renderTestComponent({
  1429. query: {displayType: 'line'},
  1430. orgFeatures: [...defaultOrgFeatures],
  1431. });
  1432. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1433. userEvent.click(screen.getAllByText('count()')[0], undefined, {skipHover: true});
  1434. userEvent.click(screen.getByText(/count_unique/), undefined, {skipHover: true});
  1435. expect(await screen.findByText('project')).toBeInTheDocument();
  1436. });
  1437. it("doesn't erase the selection when switching to another time series", async function () {
  1438. renderTestComponent({
  1439. query: {displayType: 'line'},
  1440. orgFeatures: [...defaultOrgFeatures],
  1441. });
  1442. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1443. userEvent.click(screen.getByText('Line Chart'));
  1444. userEvent.click(screen.getByText('Area Chart'));
  1445. expect(await screen.findByText('project')).toBeInTheDocument();
  1446. });
  1447. it('sends a top N request when a grouping is selected', async function () {
  1448. renderTestComponent({
  1449. query: {displayType: 'line'},
  1450. orgFeatures: [...defaultOrgFeatures],
  1451. });
  1452. userEvent.click(await screen.findByText('Group your results'));
  1453. userEvent.type(screen.getByText('Select group'), 'project{enter}');
  1454. await waitFor(() =>
  1455. expect(eventsStatsMock).toHaveBeenNthCalledWith(
  1456. 2,
  1457. '/organizations/org-slug/events-stats/',
  1458. expect.objectContaining({
  1459. query: expect.objectContaining({
  1460. query: '',
  1461. yAxis: ['count()'],
  1462. field: ['project', 'count()'],
  1463. topEvents: TOP_N,
  1464. orderby: '-count()',
  1465. }),
  1466. })
  1467. )
  1468. );
  1469. });
  1470. it('allows deleting groups until there is one left', async function () {
  1471. renderTestComponent({
  1472. query: {displayType: 'line'},
  1473. orgFeatures: [...defaultOrgFeatures],
  1474. });
  1475. userEvent.click(await screen.findByText('Add Group'));
  1476. expect(screen.getAllByLabelText('Remove group')).toHaveLength(2);
  1477. userEvent.click(screen.getAllByLabelText('Remove group')[1]);
  1478. await waitFor(() =>
  1479. expect(screen.queryByLabelText('Remove group')).not.toBeInTheDocument()
  1480. );
  1481. });
  1482. it("display 'remove' and 'drag to reorder' buttons", async function () {
  1483. renderTestComponent({
  1484. query: {displayType: 'line'},
  1485. orgFeatures: [...defaultOrgFeatures],
  1486. });
  1487. expect(screen.queryByLabelText('Remove group')).not.toBeInTheDocument();
  1488. await selectEvent.select(screen.getByText('Select group'), 'project');
  1489. expect(screen.getByLabelText('Remove group')).toBeInTheDocument();
  1490. expect(screen.queryByLabelText('Drag to reorder')).not.toBeInTheDocument();
  1491. userEvent.click(screen.getByText('Add Group'));
  1492. expect(screen.getAllByLabelText('Remove group')).toHaveLength(2);
  1493. expect(screen.getAllByLabelText('Drag to reorder')).toHaveLength(2);
  1494. });
  1495. it.todo(
  1496. 'Since simulate drag and drop with RTL is not recommended because of browser layout, remember to create acceptance test for this'
  1497. );
  1498. });
  1499. describe('limit field', function () {
  1500. it('renders if groupBy value is present', async function () {
  1501. const handleSave = jest.fn();
  1502. renderTestComponent({
  1503. query: {displayType: 'line'},
  1504. orgFeatures: [...defaultOrgFeatures],
  1505. onSave: handleSave,
  1506. });
  1507. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1508. expect(screen.getByText('Limit to 5 results')).toBeInTheDocument();
  1509. userEvent.click(screen.getByText('Add Widget'));
  1510. await waitFor(() =>
  1511. expect(handleSave).toHaveBeenCalledWith([
  1512. expect.objectContaining({
  1513. limit: 5,
  1514. }),
  1515. ])
  1516. );
  1517. });
  1518. it('update value', async function () {
  1519. renderTestComponent({
  1520. query: {displayType: 'line'},
  1521. orgFeatures: [...defaultOrgFeatures],
  1522. });
  1523. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1524. userEvent.click(screen.getByText('Limit to 5 results'));
  1525. userEvent.click(screen.getByText('Limit to 2 results'));
  1526. await waitFor(() =>
  1527. expect(eventsStatsMock).toHaveBeenCalledWith(
  1528. '/organizations/org-slug/events-stats/',
  1529. expect.objectContaining({
  1530. query: expect.objectContaining({
  1531. query: '',
  1532. yAxis: ['count()'],
  1533. field: ['project', 'count()'],
  1534. topEvents: 2,
  1535. orderby: '-count()',
  1536. }),
  1537. })
  1538. )
  1539. );
  1540. });
  1541. it('gets removed if no groupBy value', async function () {
  1542. renderTestComponent({
  1543. query: {displayType: 'line'},
  1544. orgFeatures: [...defaultOrgFeatures],
  1545. });
  1546. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1547. expect(screen.getByText('Limit to 5 results')).toBeInTheDocument();
  1548. userEvent.click(screen.getByLabelText('Remove group'));
  1549. await waitFor(() =>
  1550. expect(screen.queryByText('Limit to 5 results')).not.toBeInTheDocument()
  1551. );
  1552. });
  1553. it('applies a limit when switching from a table to timeseries chart with grouping', async function () {
  1554. const widget: Widget = {
  1555. displayType: DisplayType.TABLE,
  1556. interval: '1d',
  1557. queries: [
  1558. {
  1559. name: 'Test Widget',
  1560. fields: ['count()', 'count_unique(user)', 'epm()', 'project'],
  1561. columns: ['project'],
  1562. aggregates: ['count()', 'count_unique(user)', 'epm()'],
  1563. conditions: '',
  1564. orderby: '',
  1565. },
  1566. ],
  1567. title: 'Transactions',
  1568. id: '1',
  1569. };
  1570. const dashboard = mockDashboard({widgets: [widget]});
  1571. renderTestComponent({
  1572. dashboard,
  1573. orgFeatures: [...defaultOrgFeatures],
  1574. params: {
  1575. widgetIndex: '0',
  1576. },
  1577. });
  1578. userEvent.click(await screen.findByText('Table'));
  1579. userEvent.click(screen.getByText('Line Chart'));
  1580. expect(screen.getByText('Limit to 3 results')).toBeInTheDocument();
  1581. expect(eventsStatsMock).toHaveBeenCalledWith(
  1582. '/organizations/org-slug/events-stats/',
  1583. expect.objectContaining({
  1584. query: expect.objectContaining({
  1585. topEvents: 3,
  1586. }),
  1587. })
  1588. );
  1589. });
  1590. it('persists the limit when switching between timeseries charts', async function () {
  1591. const widget: Widget = {
  1592. displayType: DisplayType.AREA,
  1593. interval: '1d',
  1594. queries: [
  1595. {
  1596. name: 'Test Widget',
  1597. fields: ['count()', 'count_unique(user)', 'epm()', 'project'],
  1598. columns: ['project'],
  1599. aggregates: ['count()', 'count_unique(user)', 'epm()'],
  1600. conditions: '',
  1601. orderby: '',
  1602. },
  1603. ],
  1604. title: 'Transactions',
  1605. id: '1',
  1606. limit: 1,
  1607. };
  1608. const dashboard = mockDashboard({widgets: [widget]});
  1609. renderTestComponent({
  1610. dashboard,
  1611. orgFeatures: [...defaultOrgFeatures],
  1612. params: {
  1613. widgetIndex: '0',
  1614. },
  1615. });
  1616. userEvent.click(await screen.findByText('Area Chart'));
  1617. userEvent.click(screen.getByText('Line Chart'));
  1618. expect(screen.getByText('Limit to 1 result')).toBeInTheDocument();
  1619. expect(eventsStatsMock).toHaveBeenCalledWith(
  1620. '/organizations/org-slug/events-stats/',
  1621. expect.objectContaining({
  1622. query: expect.objectContaining({
  1623. topEvents: 1,
  1624. }),
  1625. })
  1626. );
  1627. });
  1628. it('unsets the limit when going from timeseries to table', async function () {
  1629. const widget: Widget = {
  1630. displayType: DisplayType.AREA,
  1631. interval: '1d',
  1632. queries: [
  1633. {
  1634. name: 'Test Widget',
  1635. fields: ['count()', 'count_unique(user)', 'epm()', 'project'],
  1636. columns: ['project'],
  1637. aggregates: ['count()', 'count_unique(user)', 'epm()'],
  1638. conditions: '',
  1639. orderby: '',
  1640. },
  1641. ],
  1642. title: 'Transactions',
  1643. id: '1',
  1644. limit: 1,
  1645. };
  1646. const dashboard = mockDashboard({widgets: [widget]});
  1647. renderTestComponent({
  1648. dashboard,
  1649. orgFeatures: [...defaultOrgFeatures],
  1650. params: {
  1651. widgetIndex: '0',
  1652. },
  1653. });
  1654. userEvent.click(await screen.findByText('Area Chart'));
  1655. userEvent.click(screen.getByText('Table'));
  1656. expect(screen.queryByText('Limit to 1 result')).not.toBeInTheDocument();
  1657. expect(eventsMock).toHaveBeenCalledWith(
  1658. '/organizations/org-slug/events/',
  1659. expect.objectContaining({
  1660. query: expect.objectContaining({
  1661. topEvents: undefined,
  1662. }),
  1663. })
  1664. );
  1665. });
  1666. });
  1667. });