widgetBuilder.spec.tsx 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008
  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. await userEvent.click(screen.getByText('Table'));
  360. await 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. await userEvent.click(customWidgetLabels[0]);
  404. await userEvent.clear(screen.getByRole('textbox', {name: 'Widget title'}));
  405. await userEvent.click(screen.getByRole('textbox', {name: 'Widget title'}));
  406. await userEvent.paste('Unique Users');
  407. await userEvent.keyboard('{enter}');
  408. expect(screen.queryByText('Custom Widget')).not.toBeInTheDocument();
  409. expect(screen.getAllByText('Unique Users')).toHaveLength(2);
  410. });
  411. it('can add query conditions', async function () {
  412. const {router} = renderTestComponent({
  413. query: {source: DashboardWidgetSource.DISCOVERV2},
  414. dashboard: testDashboard,
  415. });
  416. const search = await screen.findByTestId(/smart-search-input/);
  417. await userEvent.click(search);
  418. // Use fireEvent for performance reasons as this test suite is slow
  419. fireEvent.paste(search, {
  420. target: {value: 'color:blue'},
  421. clipboardData: {getData: () => 'color:blue'},
  422. });
  423. await userEvent.keyboard('{enter}');
  424. await userEvent.click(screen.getByText('Add Widget'));
  425. await waitFor(() => {
  426. expect(router.push).toHaveBeenCalledWith(
  427. expect.objectContaining({
  428. pathname: '/organizations/org-slug/dashboard/2/',
  429. query: {
  430. displayType: 'table',
  431. interval: '5m',
  432. title: 'Custom Widget',
  433. queryNames: [''],
  434. queryConditions: ['color:blue'],
  435. queryFields: ['count()'],
  436. queryOrderby: '-count()',
  437. start: null,
  438. end: null,
  439. statsPeriod: '24h',
  440. utc: null,
  441. project: [],
  442. environment: [],
  443. },
  444. })
  445. );
  446. });
  447. });
  448. it('can choose a field', async function () {
  449. const {router} = renderTestComponent({
  450. query: {source: DashboardWidgetSource.DISCOVERV2},
  451. dashboard: testDashboard,
  452. });
  453. expect(await screen.findAllByText('Custom Widget')).toHaveLength(2);
  454. // No delete button as there is only one query.
  455. expect(screen.queryByLabelText('Remove query')).not.toBeInTheDocument();
  456. // 1 in the table header, 1 in the column selector, 1 in the sort field
  457. const countFields = screen.getAllByText('count()');
  458. expect(countFields).toHaveLength(3);
  459. await selectEvent.select(countFields[1], ['last_seen()']);
  460. await userEvent.click(screen.getByText('Add Widget'));
  461. await waitFor(() => {
  462. expect(router.push).toHaveBeenCalledWith(
  463. expect.objectContaining({
  464. pathname: '/organizations/org-slug/dashboard/2/',
  465. query: {
  466. displayType: 'table',
  467. interval: '5m',
  468. title: 'Custom Widget',
  469. queryNames: [''],
  470. queryConditions: [''],
  471. queryFields: ['last_seen()'],
  472. queryOrderby: '-last_seen()',
  473. start: null,
  474. end: null,
  475. statsPeriod: '24h',
  476. utc: null,
  477. project: [],
  478. environment: [],
  479. },
  480. })
  481. );
  482. });
  483. });
  484. it('can add additional fields', async function () {
  485. const handleSave = jest.fn();
  486. renderTestComponent({onSave: handleSave});
  487. await userEvent.click(await screen.findByText('Table'));
  488. // Select line chart display
  489. await userEvent.click(screen.getByText('Line Chart'));
  490. // Click the add overlay button
  491. await userEvent.click(screen.getByLabelText('Add Overlay'));
  492. await selectEvent.select(screen.getByText('(Required)'), ['count_unique(…)']);
  493. await userEvent.click(screen.getByLabelText('Add Widget'));
  494. await waitFor(() => {
  495. expect(handleSave).toHaveBeenCalledWith([
  496. expect.objectContaining({
  497. title: 'Custom Widget',
  498. displayType: DisplayType.LINE,
  499. interval: '5m',
  500. widgetType: WidgetType.DISCOVER,
  501. queries: [
  502. {
  503. conditions: '',
  504. fields: ['count()', 'count_unique(user)'],
  505. aggregates: ['count()', 'count_unique(user)'],
  506. fieldAliases: [],
  507. columns: [],
  508. orderby: '',
  509. name: '',
  510. },
  511. ],
  512. }),
  513. ]);
  514. });
  515. expect(handleSave).toHaveBeenCalledTimes(1);
  516. });
  517. it('can add equation fields', async function () {
  518. const handleSave = jest.fn();
  519. renderTestComponent({onSave: handleSave});
  520. await userEvent.click(await screen.findByText('Table'));
  521. // Select line chart display
  522. await userEvent.click(screen.getByText('Line Chart'));
  523. // Click the add an equation button
  524. await userEvent.click(screen.getByLabelText('Add an Equation'));
  525. expect(screen.getByPlaceholderText('Equation')).toBeInTheDocument();
  526. await userEvent.click(screen.getByPlaceholderText('Equation'));
  527. await userEvent.paste('count() + 100');
  528. await userEvent.click(screen.getByLabelText('Add Widget'));
  529. await waitFor(() => {
  530. expect(handleSave).toHaveBeenCalledWith([
  531. expect.objectContaining({
  532. title: 'Custom Widget',
  533. displayType: DisplayType.LINE,
  534. interval: '5m',
  535. widgetType: WidgetType.DISCOVER,
  536. queries: [
  537. {
  538. name: '',
  539. fields: ['count()', 'equation|count() + 100'],
  540. aggregates: ['count()', 'equation|count() + 100'],
  541. columns: [],
  542. fieldAliases: [],
  543. conditions: '',
  544. orderby: '',
  545. },
  546. ],
  547. }),
  548. ]);
  549. });
  550. expect(handleSave).toHaveBeenCalledTimes(1);
  551. });
  552. it('can respond to validation feedback', async function () {
  553. jest.spyOn(indicators, 'addErrorMessage');
  554. renderTestComponent();
  555. await userEvent.click(await screen.findByText('Table'));
  556. const customWidgetLabels = await screen.findAllByText('Custom Widget');
  557. // EditableText and chart title
  558. expect(customWidgetLabels).toHaveLength(2);
  559. await userEvent.click(customWidgetLabels[0]);
  560. await userEvent.clear(screen.getByRole('textbox', {name: 'Widget title'}));
  561. await userEvent.keyboard('{enter}');
  562. expect(indicators.addErrorMessage).toHaveBeenCalledWith('Widget title is required');
  563. });
  564. it('sets up widget data in edit correctly', async function () {
  565. const widget: Widget = {
  566. id: '1',
  567. title: 'Errors over time',
  568. interval: '5m',
  569. displayType: DisplayType.LINE,
  570. queries: [
  571. {
  572. name: 'errors',
  573. conditions: 'event.type:error',
  574. fields: ['count()', 'count_unique(id)'],
  575. aggregates: ['count()', 'count_unique(id)'],
  576. columns: [],
  577. orderby: '',
  578. },
  579. {
  580. name: 'csp',
  581. conditions: 'event.type:csp',
  582. fields: ['count()', 'count_unique(id)'],
  583. aggregates: ['count()', 'count_unique(id)'],
  584. columns: [],
  585. orderby: '',
  586. },
  587. ],
  588. };
  589. const dashboard = mockDashboard({widgets: [widget]});
  590. renderTestComponent({dashboard, params: {widgetIndex: '0'}});
  591. await screen.findByText('Line Chart');
  592. // Should be in edit 'mode'
  593. expect(await screen.findByText('Update Widget')).toBeInTheDocument();
  594. // Should set widget data up.
  595. expect(screen.getByText('Update Widget')).toBeInTheDocument();
  596. // Filters
  597. expect(
  598. screen.getAllByPlaceholderText('Search for events, users, tags, and more')
  599. ).toHaveLength(2);
  600. expect(screen.getByText('event.type:csp')).toBeInTheDocument();
  601. expect(screen.getByText('event.type:error')).toBeInTheDocument();
  602. // Y-axis
  603. expect(screen.getAllByRole('button', {name: 'Remove query'})).toHaveLength(2);
  604. expect(screen.getByText('count()')).toBeInTheDocument();
  605. expect(screen.getByText('count_unique(…)')).toBeInTheDocument();
  606. expect(screen.getByText('id')).toBeInTheDocument();
  607. // Expect events-stats endpoint to be called for each search conditions with
  608. // the same y-axis parameters
  609. expect(eventsStatsMock).toHaveBeenNthCalledWith(
  610. 1,
  611. '/organizations/org-slug/events-stats/',
  612. expect.objectContaining({
  613. query: expect.objectContaining({
  614. query: 'event.type:error',
  615. yAxis: ['count()', 'count_unique(id)'],
  616. }),
  617. })
  618. );
  619. expect(eventsStatsMock).toHaveBeenNthCalledWith(
  620. 2,
  621. '/organizations/org-slug/events-stats/',
  622. expect.objectContaining({
  623. query: expect.objectContaining({
  624. query: 'event.type:csp',
  625. yAxis: ['count()', 'count_unique(id)'],
  626. }),
  627. })
  628. );
  629. });
  630. it('can edit a widget', async function () {
  631. const widget: Widget = {
  632. id: '1',
  633. title: 'Errors over time',
  634. interval: '5m',
  635. displayType: DisplayType.LINE,
  636. queries: [
  637. {
  638. name: 'errors',
  639. conditions: 'event.type:error',
  640. fields: ['count()', 'count_unique(id)'],
  641. aggregates: ['count()', 'count_unique(id)'],
  642. columns: [],
  643. orderby: '',
  644. },
  645. {
  646. name: 'csp',
  647. conditions: 'event.type:csp',
  648. fields: ['count()', 'count_unique(id)'],
  649. aggregates: ['count()', 'count_unique(id)'],
  650. columns: [],
  651. orderby: '',
  652. },
  653. ],
  654. };
  655. const dashboard = mockDashboard({widgets: [widget]});
  656. const handleSave = jest.fn();
  657. renderTestComponent({onSave: handleSave, dashboard, params: {widgetIndex: '0'}});
  658. await screen.findByText('Line Chart');
  659. // Should be in edit 'mode'
  660. expect(screen.getByText('Update Widget')).toBeInTheDocument();
  661. const customWidgetLabels = screen.getAllByText(widget.title);
  662. // EditableText and chart title
  663. expect(customWidgetLabels).toHaveLength(2);
  664. await userEvent.click(customWidgetLabels[0]);
  665. await userEvent.clear(screen.getByRole('textbox', {name: 'Widget title'}));
  666. await userEvent.click(screen.getByRole('textbox', {name: 'Widget title'}));
  667. await userEvent.paste('New Title');
  668. await userEvent.click(screen.getByRole('button', {name: 'Update Widget'}));
  669. await waitFor(() => {
  670. expect(handleSave).toHaveBeenCalledWith([
  671. expect.objectContaining({
  672. ...widget,
  673. title: 'New Title',
  674. }),
  675. ]);
  676. });
  677. expect(handleSave).toHaveBeenCalledTimes(1);
  678. });
  679. it('renders column inputs for table widgets', async function () {
  680. const widget: Widget = {
  681. id: '0',
  682. title: 'sdk usage',
  683. interval: '5m',
  684. displayType: DisplayType.TABLE,
  685. queries: [
  686. {
  687. name: 'errors',
  688. conditions: 'event.type:error',
  689. fields: ['sdk.name', 'count()'],
  690. columns: ['sdk.name'],
  691. aggregates: ['count()'],
  692. orderby: '',
  693. },
  694. ],
  695. };
  696. const dashboard = mockDashboard({widgets: [widget]});
  697. renderTestComponent({dashboard, params: {widgetIndex: '0'}});
  698. // Should be in edit 'mode'
  699. expect(await screen.findByText('Update Widget')).toBeInTheDocument();
  700. // Should set widget data up.
  701. expect(screen.getByRole('heading', {name: widget.title})).toBeInTheDocument();
  702. expect(screen.getByText('Table')).toBeInTheDocument();
  703. expect(screen.getByLabelText('Search events')).toBeInTheDocument();
  704. // Should have an orderby select
  705. expect(screen.getByText('Sort by a column')).toBeInTheDocument();
  706. // Add a column, and choose a value,
  707. expect(screen.getByLabelText('Add a Column')).toBeInTheDocument();
  708. });
  709. it('can save table widgets', async function () {
  710. const widget: Widget = {
  711. id: '0',
  712. title: 'sdk usage',
  713. interval: '5m',
  714. displayType: DisplayType.TABLE,
  715. queries: [
  716. {
  717. name: 'errors',
  718. conditions: 'event.type:error',
  719. fields: ['sdk.name', 'count()'],
  720. columns: ['sdk.name'],
  721. aggregates: ['count()'],
  722. orderby: '-count()',
  723. },
  724. ],
  725. };
  726. const dashboard = mockDashboard({widgets: [widget]});
  727. const handleSave = jest.fn();
  728. renderTestComponent({dashboard, onSave: handleSave, params: {widgetIndex: '0'}});
  729. // Should be in edit 'mode'
  730. expect(await screen.findByText('Update Widget')).toBeInTheDocument();
  731. // Add a column, and choose a value,
  732. await userEvent.click(screen.getByLabelText('Add a Column'));
  733. await selectEvent.select(screen.getByText('(Required)'), 'trace');
  734. // Save widget
  735. await userEvent.click(screen.getByLabelText('Update Widget'));
  736. await waitFor(() => {
  737. expect(handleSave).toHaveBeenCalledWith([
  738. expect.objectContaining({
  739. id: '0',
  740. title: 'sdk usage',
  741. displayType: DisplayType.TABLE,
  742. interval: '5m',
  743. queries: [
  744. {
  745. name: 'errors',
  746. conditions: 'event.type:error',
  747. fields: ['sdk.name', 'count()', 'trace'],
  748. aggregates: ['count()'],
  749. columns: ['sdk.name', 'trace'],
  750. orderby: '-count()',
  751. fieldAliases: ['', '', ''],
  752. },
  753. ],
  754. widgetType: WidgetType.DISCOVER,
  755. }),
  756. ]);
  757. });
  758. expect(handleSave).toHaveBeenCalledTimes(1);
  759. });
  760. it('should properly query for table fields', async function () {
  761. const defaultWidgetQuery = {
  762. name: '',
  763. fields: ['title', 'count()'],
  764. columns: ['title'],
  765. aggregates: ['count()'],
  766. conditions: '',
  767. orderby: '',
  768. };
  769. const defaultTableColumns = ['title', 'count()', 'count_unique(user)', 'epm()'];
  770. renderTestComponent({
  771. query: {
  772. source: DashboardWidgetSource.DISCOVERV2,
  773. defaultWidgetQuery: urlEncode(defaultWidgetQuery),
  774. displayType: DisplayType.LINE,
  775. defaultTableColumns,
  776. },
  777. });
  778. expect(await screen.findByText('Line Chart')).toBeInTheDocument();
  779. await userEvent.click(screen.getByText('Line Chart'));
  780. await userEvent.click(screen.getByText('Table'));
  781. await waitFor(() => {
  782. expect(eventsMock).toHaveBeenLastCalledWith(
  783. '/organizations/org-slug/events/',
  784. expect.objectContaining({
  785. query: expect.objectContaining({
  786. field: defaultTableColumns,
  787. }),
  788. })
  789. );
  790. });
  791. });
  792. it('should use defaultWidgetQuery Y-Axis and Conditions if given a defaultWidgetQuery', async function () {
  793. const defaultWidgetQuery = {
  794. name: '',
  795. fields: ['count()', 'failure_count()', 'count_unique(user)'],
  796. columns: [],
  797. aggregates: ['count()', 'failure_count()', 'count_unique(user)'],
  798. conditions: 'tag:value',
  799. orderby: '',
  800. };
  801. renderTestComponent({
  802. query: {
  803. source: DashboardWidgetSource.DISCOVERV2,
  804. defaultWidgetQuery: urlEncode(defaultWidgetQuery),
  805. },
  806. });
  807. expect(await screen.findByText('tag:value')).toBeInTheDocument();
  808. // Table display, column, and sort field
  809. expect(screen.getAllByText('count()')).toHaveLength(3);
  810. // Table display and column
  811. expect(screen.getAllByText('failure_count()')).toHaveLength(2);
  812. // Table display
  813. expect(screen.getByText('count_unique(user)')).toBeInTheDocument();
  814. // Column
  815. expect(screen.getByText('count_unique(…)')).toBeInTheDocument();
  816. // Column
  817. expect(screen.getByText('user')).toBeInTheDocument();
  818. });
  819. it('uses displayType if given a displayType', async function () {
  820. renderTestComponent({
  821. query: {
  822. displayType: DisplayType.BAR,
  823. },
  824. });
  825. expect(await screen.findByText('Bar Chart')).toBeInTheDocument();
  826. });
  827. it('deletes the widget when the modal is confirmed', async () => {
  828. const handleSave = jest.fn();
  829. const widget: Widget = {
  830. id: '1',
  831. title: 'Errors over time',
  832. interval: '5m',
  833. displayType: DisplayType.LINE,
  834. queries: [
  835. {
  836. name: 'errors',
  837. conditions: 'event.type:error',
  838. fields: ['count()', 'count_unique(id)'],
  839. aggregates: ['count()', 'count_unique(id)'],
  840. columns: [],
  841. orderby: '',
  842. },
  843. {
  844. name: 'csp',
  845. conditions: 'event.type:csp',
  846. fields: ['count()', 'count_unique(id)'],
  847. aggregates: ['count()', 'count_unique(id)'],
  848. columns: [],
  849. orderby: '',
  850. },
  851. ],
  852. };
  853. const dashboard = mockDashboard({widgets: [widget]});
  854. renderTestComponent({onSave: handleSave, dashboard, params: {widgetIndex: '0'}});
  855. await userEvent.click(await screen.findByText('Delete'));
  856. renderGlobalModal();
  857. await userEvent.click(await screen.findByText('Confirm'));
  858. await waitFor(() => {
  859. // The only widget was deleted
  860. expect(handleSave).toHaveBeenCalledWith([]);
  861. });
  862. expect(handleSave).toHaveBeenCalledTimes(1);
  863. });
  864. it('persists the page filter period when updating a widget', async () => {
  865. const widget: Widget = {
  866. id: '1',
  867. title: 'Errors over time',
  868. interval: '5m',
  869. displayType: DisplayType.LINE,
  870. queries: [
  871. {
  872. name: 'errors',
  873. conditions: 'event.type:error',
  874. fields: ['count()', 'count_unique(id)'],
  875. aggregates: ['count()', 'count_unique(id)'],
  876. columns: [],
  877. orderby: '',
  878. },
  879. ],
  880. };
  881. const dashboard = mockDashboard({widgets: [widget]});
  882. const {router} = renderTestComponent({
  883. dashboard,
  884. params: {orgId: 'org-slug', widgetIndex: '0'},
  885. query: {statsPeriod: '90d'},
  886. });
  887. await userEvent.click(screen.getByText('Update Widget'));
  888. await waitFor(() => {
  889. expect(router.push).toHaveBeenLastCalledWith(
  890. expect.objectContaining({
  891. pathname: '/organizations/org-slug/dashboard/1/',
  892. query: expect.objectContaining({
  893. statsPeriod: '90d',
  894. }),
  895. })
  896. );
  897. });
  898. });
  899. it('renders page filters in the filter step', async () => {
  900. const mockReleases = MockApiClient.addMockResponse({
  901. url: '/organizations/org-slug/releases/',
  902. body: [TestStubs.Release()],
  903. });
  904. renderTestComponent({
  905. params: {orgId: 'org-slug'},
  906. query: {statsPeriod: '90d'},
  907. orgFeatures: defaultOrgFeatures,
  908. });
  909. expect(await screen.findByTestId('page-filter-timerange-selector')).toBeDisabled();
  910. expect(screen.getByTestId('page-filter-environment-selector')).toBeDisabled();
  911. expect(screen.getByTestId('page-filter-project-selector-loading')).toBeDisabled();
  912. expect(mockReleases).toHaveBeenCalled();
  913. expect(screen.getByRole('button', {name: /all releases/i})).toBeDisabled();
  914. });
  915. it('appends dashboard filters to widget builder fetch data request', async () => {
  916. MockApiClient.addMockResponse({
  917. url: '/organizations/org-slug/releases/',
  918. body: [TestStubs.Release()],
  919. });
  920. const mock = MockApiClient.addMockResponse({
  921. url: '/organizations/org-slug/events/',
  922. body: [],
  923. });
  924. renderTestComponent({
  925. dashboard: {
  926. id: 'new',
  927. title: 'Dashboard',
  928. createdBy: undefined,
  929. dateCreated: '2020-01-01T00:00:00.000Z',
  930. widgets: [],
  931. projects: [],
  932. filters: {release: ['abc@1.2.0']},
  933. },
  934. params: {orgId: 'org-slug'},
  935. query: {statsPeriod: '90d'},
  936. orgFeatures: defaultOrgFeatures,
  937. });
  938. await waitFor(() => {
  939. expect(mock).toHaveBeenCalledWith(
  940. '/organizations/org-slug/events/',
  941. expect.objectContaining({
  942. query: expect.objectContaining({
  943. query: ' release:abc@1.2.0 ',
  944. }),
  945. })
  946. );
  947. });
  948. });
  949. it('does not error when query conditions field is blurred', async function () {
  950. jest.useFakeTimers();
  951. const widget: Widget = {
  952. id: '0',
  953. title: 'sdk usage',
  954. interval: '5m',
  955. displayType: DisplayType.BAR,
  956. queries: [
  957. {
  958. name: 'filled in',
  959. conditions: 'event.type:error',
  960. fields: ['count()', 'count_unique(id)'],
  961. aggregates: ['count()', 'count_unique(id)'],
  962. columns: [],
  963. orderby: '-count()',
  964. },
  965. ],
  966. };
  967. const dashboard = mockDashboard({widgets: [widget]});
  968. const handleSave = jest.fn();
  969. renderTestComponent({dashboard, onSave: handleSave, params: {widgetIndex: '0'}});
  970. await userEvent.click(await screen.findByLabelText('Add Query'), {delay: null});
  971. // Triggering the onBlur of the new field should not error
  972. await userEvent.click(
  973. screen.getAllByPlaceholderText('Search for events, users, tags, and more')[1],
  974. {delay: null}
  975. );
  976. await userEvent.keyboard('{Escape}', {delay: null});
  977. // Run all timers because the handleBlur contains a setTimeout
  978. jest.runAllTimers();
  979. });
  980. it('does not wipe column changes when filters are modified', async function () {
  981. jest.useFakeTimers();
  982. // widgetIndex: undefined means creating a new widget
  983. renderTestComponent({params: {widgetIndex: undefined}});
  984. await userEvent.click(await screen.findByLabelText('Add a Column'), {delay: null});
  985. await selectEvent.select(screen.getByText('(Required)'), /project/);
  986. // Triggering the onBlur of the filter should not error
  987. await userEvent.click(
  988. screen.getByPlaceholderText('Search for events, users, tags, and more'),
  989. {delay: null}
  990. );
  991. await userEvent.keyboard('{enter}', {delay: null});
  992. expect(await screen.findAllByText('project')).toHaveLength(2);
  993. });
  994. it('renders fields with commas properly', async () => {
  995. const defaultWidgetQuery = {
  996. conditions: '',
  997. fields: ['equation|count_if(transaction.duration,equals,300)*2'],
  998. aggregates: ['equation|count_if(transaction.duration,equals,300)*2'],
  999. columns: [],
  1000. orderby: '',
  1001. name: '',
  1002. };
  1003. const defaultTableColumns = [
  1004. 'count_if(transaction.duration,equals,300)',
  1005. 'equation|count_if(transaction.duration,equals,300)*2',
  1006. ];
  1007. renderTestComponent({
  1008. query: {
  1009. source: DashboardWidgetSource.DISCOVERV2,
  1010. defaultWidgetQuery: urlEncode(defaultWidgetQuery),
  1011. defaultTableColumns,
  1012. yAxis: ['equation|count_if(transaction.duration,equals,300)*2'],
  1013. },
  1014. });
  1015. expect(
  1016. await screen.findByText('count_if(transaction.duration,equals,300)*2')
  1017. ).toBeInTheDocument();
  1018. });
  1019. it('sets the correct fields for a top n widget', async () => {
  1020. renderTestComponent({
  1021. orgFeatures: [...defaultOrgFeatures, 'performance-view'],
  1022. query: {
  1023. displayType: DisplayType.TOP_N,
  1024. },
  1025. });
  1026. // Top N now opens as Area Chart
  1027. expect(await screen.findByText('Area Chart')).toBeInTheDocument();
  1028. // Add a group by
  1029. await userEvent.click(screen.getByText('Add Overlay'));
  1030. await selectEvent.select(screen.getByText('Select group'), /project/);
  1031. // Change the y-axis
  1032. await selectEvent.select(screen.getAllByText('count()')[0], 'eps()');
  1033. await waitFor(() => {
  1034. expect(eventsStatsMock).toHaveBeenLastCalledWith(
  1035. '/organizations/org-slug/events-stats/',
  1036. expect.objectContaining({
  1037. query: expect.objectContaining({
  1038. query: '',
  1039. yAxis: ['eps()'],
  1040. field: ['project', 'eps()'],
  1041. topEvents: TOP_N,
  1042. orderby: '-eps()',
  1043. }),
  1044. })
  1045. );
  1046. });
  1047. });
  1048. it('fetches tags when tag store is empty', async function () {
  1049. renderTestComponent();
  1050. await waitFor(() => {
  1051. expect(tagsMock).toHaveBeenCalled();
  1052. });
  1053. });
  1054. it('does not fetch tags when tag store is not empty', async function () {
  1055. await act(async () => {
  1056. TagStore.loadTagsSuccess(TestStubs.Tags());
  1057. renderTestComponent();
  1058. await tick();
  1059. });
  1060. expect(tagsMock).not.toHaveBeenCalled();
  1061. });
  1062. it('excludes the Other series when grouping and using multiple y-axes', async function () {
  1063. renderTestComponent({
  1064. orgFeatures: [...defaultOrgFeatures],
  1065. query: {
  1066. displayType: DisplayType.LINE,
  1067. },
  1068. });
  1069. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1070. await userEvent.click(screen.getByText('Add Overlay'));
  1071. await selectEvent.select(screen.getByText('(Required)'), /count_unique/);
  1072. await waitFor(() => {
  1073. expect(eventsStatsMock).toHaveBeenCalledWith(
  1074. '/organizations/org-slug/events-stats/',
  1075. expect.objectContaining({
  1076. query: expect.objectContaining({excludeOther: '1'}),
  1077. })
  1078. );
  1079. });
  1080. });
  1081. it('excludes the Other series when grouping and using multiple queries', async function () {
  1082. renderTestComponent({
  1083. orgFeatures: [...defaultOrgFeatures],
  1084. query: {
  1085. displayType: DisplayType.LINE,
  1086. },
  1087. });
  1088. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1089. await userEvent.click(screen.getByText('Add Query'));
  1090. await waitFor(() => {
  1091. expect(eventsStatsMock).toHaveBeenCalledWith(
  1092. '/organizations/org-slug/events-stats/',
  1093. expect.objectContaining({
  1094. query: expect.objectContaining({excludeOther: '1'}),
  1095. })
  1096. );
  1097. });
  1098. });
  1099. it('includes Other series when there is only one query and one y-axis', async function () {
  1100. renderTestComponent({
  1101. orgFeatures: [...defaultOrgFeatures],
  1102. query: {
  1103. displayType: DisplayType.LINE,
  1104. },
  1105. });
  1106. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1107. await waitFor(() => {
  1108. expect(eventsStatsMock).toHaveBeenCalledWith(
  1109. '/organizations/org-slug/events-stats/',
  1110. expect.objectContaining({
  1111. query: expect.not.objectContaining({excludeOther: '1'}),
  1112. })
  1113. );
  1114. });
  1115. });
  1116. it('decreases the limit when more y-axes and queries are added', async function () {
  1117. renderTestComponent({
  1118. orgFeatures: [...defaultOrgFeatures],
  1119. query: {
  1120. displayType: DisplayType.LINE,
  1121. },
  1122. });
  1123. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1124. screen.getByText('Limit to 5 results');
  1125. await userEvent.click(screen.getByText('Add Query'));
  1126. await userEvent.click(screen.getByText('Add Overlay'));
  1127. expect(screen.getByText('Limit to 2 results')).toBeInTheDocument();
  1128. });
  1129. it('alerts the user if there are unsaved changes', async function () {
  1130. const {router} = renderTestComponent();
  1131. const alertMock = jest.fn();
  1132. const setRouteLeaveHookMock = jest.spyOn(router, 'setRouteLeaveHook');
  1133. setRouteLeaveHookMock.mockImplementationOnce((_route, _callback) => {
  1134. alertMock();
  1135. });
  1136. const customWidgetLabels = await screen.findAllByText('Custom Widget');
  1137. // EditableText and chart title
  1138. expect(customWidgetLabels).toHaveLength(2);
  1139. // Change title text
  1140. await userEvent.click(customWidgetLabels[0]);
  1141. await userEvent.clear(screen.getByRole('textbox', {name: 'Widget title'}));
  1142. await userEvent.click(screen.getByRole('textbox', {name: 'Widget title'}));
  1143. await userEvent.paste('Unique Users');
  1144. await userEvent.keyboard('{Enter}');
  1145. // Click Cancel
  1146. await userEvent.click(screen.getByText('Cancel'));
  1147. // Assert an alert was triggered
  1148. expect(alertMock).toHaveBeenCalled();
  1149. });
  1150. it('does not trigger alert dialog if no changes', async function () {
  1151. const {router} = renderTestComponent();
  1152. const alertMock = jest.fn();
  1153. const setRouteLeaveHookMock = jest.spyOn(router, 'setRouteLeaveHook');
  1154. setRouteLeaveHookMock.mockImplementationOnce((_route, _callback) => {
  1155. alertMock();
  1156. });
  1157. // Click Cancel
  1158. await userEvent.click(await screen.findByText('Cancel'));
  1159. // Assert an alert was triggered
  1160. expect(alertMock).not.toHaveBeenCalled();
  1161. });
  1162. describe('Widget creation coming from other verticals', function () {
  1163. it('redirects correctly when creating a new dashboard', async function () {
  1164. const {router} = renderTestComponent({
  1165. query: {source: DashboardWidgetSource.DISCOVERV2},
  1166. });
  1167. await userEvent.click(await screen.findByText('Add Widget'));
  1168. await waitFor(() => {
  1169. expect(router.push).toHaveBeenCalledWith(
  1170. expect.objectContaining({
  1171. pathname: '/organizations/org-slug/dashboards/new/',
  1172. query: {
  1173. displayType: 'table',
  1174. interval: '5m',
  1175. title: 'Custom Widget',
  1176. queryNames: [''],
  1177. queryConditions: [''],
  1178. queryFields: ['count()'],
  1179. queryOrderby: '-count()',
  1180. start: null,
  1181. end: null,
  1182. statsPeriod: '24h',
  1183. utc: null,
  1184. project: [],
  1185. environment: [],
  1186. },
  1187. })
  1188. );
  1189. });
  1190. });
  1191. it('redirects correctly when choosing an existing dashboard', async function () {
  1192. const {router} = renderTestComponent({
  1193. query: {source: DashboardWidgetSource.DISCOVERV2},
  1194. dashboard: testDashboard,
  1195. });
  1196. await userEvent.click(await screen.findByText('Add Widget'));
  1197. await waitFor(() => {
  1198. expect(router.push).toHaveBeenCalledWith(
  1199. expect.objectContaining({
  1200. pathname: '/organizations/org-slug/dashboard/2/',
  1201. query: {
  1202. displayType: 'table',
  1203. interval: '5m',
  1204. title: 'Custom Widget',
  1205. queryNames: [''],
  1206. queryConditions: [''],
  1207. queryFields: ['count()'],
  1208. queryOrderby: '-count()',
  1209. start: null,
  1210. end: null,
  1211. statsPeriod: '24h',
  1212. utc: null,
  1213. project: [],
  1214. environment: [],
  1215. },
  1216. })
  1217. );
  1218. });
  1219. });
  1220. it('shows the correct orderby when switching from a line chart to table', async function () {
  1221. const defaultWidgetQuery = {
  1222. name: '',
  1223. fields: ['count_unique(user)'],
  1224. columns: [],
  1225. aggregates: ['count_unique(user)'],
  1226. conditions: '',
  1227. orderby: 'count_unique(user)',
  1228. };
  1229. const defaultTableColumns = ['title', 'count_unique(user)'];
  1230. renderTestComponent({
  1231. orgFeatures: [...defaultOrgFeatures],
  1232. query: {
  1233. source: DashboardWidgetSource.DISCOVERV2,
  1234. defaultWidgetQuery: urlEncode(defaultWidgetQuery),
  1235. displayType: DisplayType.LINE,
  1236. defaultTableColumns,
  1237. },
  1238. });
  1239. await userEvent.click(await screen.findByText('Line Chart'));
  1240. await userEvent.click(screen.getByText('Table'));
  1241. expect(screen.getAllByText('count_unique(user)')[0]).toBeInTheDocument();
  1242. await waitFor(() => {
  1243. expect(eventsMock).toHaveBeenLastCalledWith(
  1244. '/organizations/org-slug/events/',
  1245. expect.objectContaining({
  1246. query: expect.objectContaining({
  1247. field: defaultTableColumns,
  1248. sort: ['count_unique(user)'],
  1249. }),
  1250. })
  1251. );
  1252. });
  1253. });
  1254. it('does not send request with orderby if a timeseries chart without grouping', async function () {
  1255. const defaultWidgetQuery = {
  1256. name: '',
  1257. fields: ['count_unique(user)'],
  1258. columns: [],
  1259. aggregates: ['count_unique(user)'],
  1260. conditions: '',
  1261. orderby: 'count_unique(user)',
  1262. };
  1263. const defaultTableColumns = ['title', 'count_unique(user)'];
  1264. renderTestComponent({
  1265. orgFeatures: [...defaultOrgFeatures],
  1266. query: {
  1267. source: DashboardWidgetSource.DISCOVERV2,
  1268. defaultWidgetQuery: urlEncode(defaultWidgetQuery),
  1269. displayType: DisplayType.LINE,
  1270. defaultTableColumns,
  1271. },
  1272. });
  1273. await waitFor(() => {
  1274. expect(eventsStatsMock).toHaveBeenLastCalledWith(
  1275. '/organizations/org-slug/events-stats/',
  1276. expect.objectContaining({
  1277. query: expect.objectContaining({
  1278. orderby: '',
  1279. }),
  1280. })
  1281. );
  1282. });
  1283. });
  1284. });
  1285. it('opens top-N widgets as area display', async function () {
  1286. const widget: Widget = {
  1287. id: '1',
  1288. title: 'Errors over time',
  1289. interval: '5m',
  1290. displayType: DisplayType.TOP_N,
  1291. queries: [
  1292. {
  1293. name: '',
  1294. conditions: '',
  1295. fields: ['count()', 'count_unique(id)'],
  1296. aggregates: ['count()', 'count_unique(id)'],
  1297. columns: [],
  1298. orderby: '-count()',
  1299. },
  1300. ],
  1301. };
  1302. const dashboard = mockDashboard({widgets: [widget]});
  1303. renderTestComponent({
  1304. orgFeatures: [...defaultOrgFeatures],
  1305. dashboard,
  1306. params: {
  1307. widgetIndex: '0',
  1308. },
  1309. });
  1310. expect(await screen.findByText('Area Chart')).toBeInTheDocument();
  1311. });
  1312. it('Update table header values (field alias)', async function () {
  1313. const handleSave = jest.fn();
  1314. renderTestComponent({
  1315. onSave: handleSave,
  1316. orgFeatures: [...defaultOrgFeatures],
  1317. });
  1318. await userEvent.click(screen.getByPlaceholderText('Alias'));
  1319. await userEvent.paste('First Alias');
  1320. await userEvent.click(screen.getByLabelText('Add a Column'));
  1321. await userEvent.click(screen.getAllByPlaceholderText('Alias')[1]);
  1322. await userEvent.paste('Second Alias');
  1323. await userEvent.click(screen.getByText('Add Widget'));
  1324. await waitFor(() => {
  1325. expect(handleSave).toHaveBeenCalledWith([
  1326. expect.objectContaining({
  1327. queries: [
  1328. expect.objectContaining({fieldAliases: ['First Alias', 'Second Alias']}),
  1329. ],
  1330. }),
  1331. ]);
  1332. });
  1333. });
  1334. it('does not wipe equation aliases when a column alias is updated', async function () {
  1335. renderTestComponent({
  1336. orgFeatures: [...defaultOrgFeatures],
  1337. });
  1338. await userEvent.click(screen.getByText('Add an Equation'));
  1339. await userEvent.click(screen.getAllByPlaceholderText('Alias')[1]);
  1340. await userEvent.paste('This should persist');
  1341. await userEvent.type(screen.getAllByPlaceholderText('Alias')[0], 'A');
  1342. expect(await screen.findByText('This should persist')).toBeInTheDocument();
  1343. });
  1344. it('does not wipe equation aliases when a column selection is made', async function () {
  1345. renderTestComponent({
  1346. orgFeatures: [...defaultOrgFeatures],
  1347. });
  1348. await userEvent.click(screen.getByText('Add an Equation'));
  1349. await userEvent.click(screen.getAllByPlaceholderText('Alias')[1]);
  1350. await userEvent.paste('This should persist');
  1351. // 1 for the table, 1 for the the column selector, 1 for the sort
  1352. await waitFor(() => expect(screen.getAllByText('count()')).toHaveLength(3));
  1353. await selectEvent.select(screen.getAllByText('count()')[1], /count_unique/);
  1354. expect(screen.getByText('This should persist')).toBeInTheDocument();
  1355. });
  1356. it('copies over the orderby from the previous query if adding another', async function () {
  1357. renderTestComponent({
  1358. orgFeatures: [...defaultOrgFeatures],
  1359. });
  1360. await userEvent.click(await screen.findByText('Table'));
  1361. await userEvent.click(screen.getByText('Line Chart'));
  1362. await selectEvent.select(screen.getByText('Select group'), 'project');
  1363. await selectEvent.select(screen.getAllByText('count()')[1], 'count_unique(…)');
  1364. MockApiClient.clearMockResponses();
  1365. eventsStatsMock = MockApiClient.addMockResponse({
  1366. url: '/organizations/org-slug/events-stats/',
  1367. body: [],
  1368. });
  1369. await userEvent.click(screen.getByText('Add Query'));
  1370. // Assert on two calls, one for each query
  1371. const expectedArgs = expect.objectContaining({
  1372. query: expect.objectContaining({
  1373. orderby: '-count_unique(user)',
  1374. }),
  1375. });
  1376. expect(eventsStatsMock).toHaveBeenNthCalledWith(
  1377. 1,
  1378. '/organizations/org-slug/events-stats/',
  1379. expectedArgs
  1380. );
  1381. expect(eventsStatsMock).toHaveBeenNthCalledWith(
  1382. 2,
  1383. '/organizations/org-slug/events-stats/',
  1384. expectedArgs
  1385. );
  1386. });
  1387. it('disables add widget button and prevents widget previewing from firing widget query if widget query condition is invalid', async function () {
  1388. renderTestComponent({
  1389. orgFeatures: [...defaultOrgFeatures],
  1390. });
  1391. await userEvent.click(await screen.findByText('Table'));
  1392. await userEvent.click(screen.getByText('Line Chart'));
  1393. expect(eventsStatsMock).toHaveBeenCalledTimes(1);
  1394. await userEvent.type(
  1395. screen.getByTestId('smart-search-input'),
  1396. 'transaction.duration:123a'
  1397. );
  1398. // Unfocus input
  1399. await userEvent.click(screen.getByText('Filter your results'));
  1400. expect(screen.getByText('Add Widget').closest('button')).toBeDisabled();
  1401. expect(screen.getByText('Widget query condition is invalid.')).toBeInTheDocument();
  1402. expect(eventsStatsMock).toHaveBeenCalledTimes(1);
  1403. });
  1404. describe('Widget Library', function () {
  1405. it('only opens the modal when the query data is changed', async function () {
  1406. const mockModal = jest.spyOn(modals, 'openWidgetBuilderOverwriteModal');
  1407. renderTestComponent();
  1408. await screen.findByText('Widget Library');
  1409. await userEvent.click(screen.getByText('Duration Distribution'));
  1410. // Widget Library, Builder title, and Chart title
  1411. expect(screen.getAllByText('Duration Distribution')).toHaveLength(3);
  1412. // Confirm modal doesn't open because no changes were made
  1413. expect(mockModal).not.toHaveBeenCalled();
  1414. await userEvent.click(screen.getAllByLabelText('Remove this Y-Axis')[0]);
  1415. await userEvent.click(screen.getByText('High Throughput Transactions'));
  1416. // Should not have overwritten widget data, and confirm modal should open
  1417. expect(screen.getAllByText('Duration Distribution')).toHaveLength(3);
  1418. expect(mockModal).toHaveBeenCalled();
  1419. });
  1420. });
  1421. describe('group by field', function () {
  1422. it('does not contain functions as options', async function () {
  1423. renderTestComponent({
  1424. query: {displayType: 'line'},
  1425. orgFeatures: [...defaultOrgFeatures],
  1426. });
  1427. expect(await screen.findByText('Select group')).toBeInTheDocument();
  1428. await userEvent.click(screen.getByText('Select group'));
  1429. // Only one f(x) field set in the y-axis selector
  1430. expect(screen.getByText('f(x)')).toBeInTheDocument();
  1431. });
  1432. it('adds more fields when Add Group is clicked', async function () {
  1433. renderTestComponent({
  1434. query: {displayType: 'line'},
  1435. orgFeatures: [...defaultOrgFeatures],
  1436. });
  1437. await userEvent.click(await screen.findByText('Add Group'));
  1438. expect(await screen.findAllByText('Select group')).toHaveLength(2);
  1439. });
  1440. it("doesn't reset group by when changing y-axis", async function () {
  1441. renderTestComponent({
  1442. query: {displayType: 'line'},
  1443. orgFeatures: [...defaultOrgFeatures],
  1444. });
  1445. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1446. await userEvent.click(screen.getAllByText('count()')[0], {
  1447. skipHover: true,
  1448. });
  1449. await userEvent.click(screen.getByText(/count_unique/), {
  1450. skipHover: true,
  1451. });
  1452. expect(await screen.findByText('project')).toBeInTheDocument();
  1453. });
  1454. it("doesn't erase the selection when switching to another time series", async function () {
  1455. renderTestComponent({
  1456. query: {displayType: 'line'},
  1457. orgFeatures: [...defaultOrgFeatures],
  1458. });
  1459. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1460. await userEvent.click(screen.getByText('Line Chart'));
  1461. await userEvent.click(screen.getByText('Area Chart'));
  1462. expect(await screen.findByText('project')).toBeInTheDocument();
  1463. });
  1464. it('sends a top N request when a grouping is selected', async function () {
  1465. renderTestComponent({
  1466. query: {displayType: 'line'},
  1467. orgFeatures: [...defaultOrgFeatures],
  1468. });
  1469. await userEvent.click(await screen.findByText('Group your results'));
  1470. await userEvent.type(screen.getByText('Select group'), 'project{enter}');
  1471. await waitFor(() =>
  1472. expect(eventsStatsMock).toHaveBeenNthCalledWith(
  1473. 2,
  1474. '/organizations/org-slug/events-stats/',
  1475. expect.objectContaining({
  1476. query: expect.objectContaining({
  1477. query: '',
  1478. yAxis: ['count()'],
  1479. field: ['project', 'count()'],
  1480. topEvents: TOP_N,
  1481. orderby: '-count()',
  1482. }),
  1483. })
  1484. )
  1485. );
  1486. });
  1487. it('allows deleting groups until there is one left', async function () {
  1488. renderTestComponent({
  1489. query: {displayType: 'line'},
  1490. orgFeatures: [...defaultOrgFeatures],
  1491. });
  1492. await userEvent.click(await screen.findByText('Add Group'));
  1493. expect(screen.getAllByLabelText('Remove group')).toHaveLength(2);
  1494. await userEvent.click(screen.getAllByLabelText('Remove group')[1]);
  1495. await waitFor(() =>
  1496. expect(screen.queryByLabelText('Remove group')).not.toBeInTheDocument()
  1497. );
  1498. });
  1499. it("display 'remove' and 'drag to reorder' buttons", async function () {
  1500. renderTestComponent({
  1501. query: {displayType: 'line'},
  1502. orgFeatures: [...defaultOrgFeatures],
  1503. });
  1504. expect(screen.queryByLabelText('Remove group')).not.toBeInTheDocument();
  1505. await selectEvent.select(screen.getByText('Select group'), 'project');
  1506. expect(screen.getByLabelText('Remove group')).toBeInTheDocument();
  1507. expect(screen.queryByLabelText('Drag to reorder')).not.toBeInTheDocument();
  1508. await userEvent.click(screen.getByText('Add Group'));
  1509. expect(screen.getAllByLabelText('Remove group')).toHaveLength(2);
  1510. expect(screen.getAllByLabelText('Drag to reorder')).toHaveLength(2);
  1511. });
  1512. it.todo(
  1513. 'Since simulate drag and drop with RTL is not recommended because of browser layout, remember to create acceptance test for this'
  1514. );
  1515. });
  1516. describe('limit field', function () {
  1517. it('renders if groupBy value is present', async function () {
  1518. const handleSave = jest.fn();
  1519. renderTestComponent({
  1520. query: {displayType: 'line'},
  1521. orgFeatures: [...defaultOrgFeatures],
  1522. onSave: handleSave,
  1523. });
  1524. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1525. expect(screen.getByText('Limit to 5 results')).toBeInTheDocument();
  1526. await userEvent.click(screen.getByText('Add Widget'));
  1527. await waitFor(() =>
  1528. expect(handleSave).toHaveBeenCalledWith([
  1529. expect.objectContaining({
  1530. limit: 5,
  1531. }),
  1532. ])
  1533. );
  1534. });
  1535. it('update value', async function () {
  1536. renderTestComponent({
  1537. query: {displayType: 'line'},
  1538. orgFeatures: [...defaultOrgFeatures],
  1539. });
  1540. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1541. await userEvent.click(screen.getByText('Limit to 5 results'));
  1542. await userEvent.click(screen.getByText('Limit to 2 results'));
  1543. await waitFor(() =>
  1544. expect(eventsStatsMock).toHaveBeenCalledWith(
  1545. '/organizations/org-slug/events-stats/',
  1546. expect.objectContaining({
  1547. query: expect.objectContaining({
  1548. query: '',
  1549. yAxis: ['count()'],
  1550. field: ['project', 'count()'],
  1551. topEvents: 2,
  1552. orderby: '-count()',
  1553. }),
  1554. })
  1555. )
  1556. );
  1557. });
  1558. it('gets removed if no groupBy value', async function () {
  1559. renderTestComponent({
  1560. query: {displayType: 'line'},
  1561. orgFeatures: [...defaultOrgFeatures],
  1562. });
  1563. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1564. expect(screen.getByText('Limit to 5 results')).toBeInTheDocument();
  1565. await userEvent.click(screen.getByLabelText('Remove group'));
  1566. await waitFor(() =>
  1567. expect(screen.queryByText('Limit to 5 results')).not.toBeInTheDocument()
  1568. );
  1569. });
  1570. it('applies a limit when switching from a table to timeseries chart with grouping', async function () {
  1571. const widget: Widget = {
  1572. displayType: DisplayType.TABLE,
  1573. interval: '1d',
  1574. queries: [
  1575. {
  1576. name: 'Test Widget',
  1577. fields: ['count()', 'count_unique(user)', 'epm()', 'project'],
  1578. columns: ['project'],
  1579. aggregates: ['count()', 'count_unique(user)', 'epm()'],
  1580. conditions: '',
  1581. orderby: '',
  1582. },
  1583. ],
  1584. title: 'Transactions',
  1585. id: '1',
  1586. };
  1587. const dashboard = mockDashboard({widgets: [widget]});
  1588. renderTestComponent({
  1589. dashboard,
  1590. orgFeatures: [...defaultOrgFeatures],
  1591. params: {
  1592. widgetIndex: '0',
  1593. },
  1594. });
  1595. await userEvent.click(await screen.findByText('Table'));
  1596. await userEvent.click(screen.getByText('Line Chart'));
  1597. expect(screen.getByText('Limit to 3 results')).toBeInTheDocument();
  1598. expect(eventsStatsMock).toHaveBeenCalledWith(
  1599. '/organizations/org-slug/events-stats/',
  1600. expect.objectContaining({
  1601. query: expect.objectContaining({
  1602. topEvents: 3,
  1603. }),
  1604. })
  1605. );
  1606. });
  1607. it('persists the limit when switching between timeseries charts', async function () {
  1608. const widget: Widget = {
  1609. displayType: DisplayType.AREA,
  1610. interval: '1d',
  1611. queries: [
  1612. {
  1613. name: 'Test Widget',
  1614. fields: ['count()', 'count_unique(user)', 'epm()', 'project'],
  1615. columns: ['project'],
  1616. aggregates: ['count()', 'count_unique(user)', 'epm()'],
  1617. conditions: '',
  1618. orderby: '',
  1619. },
  1620. ],
  1621. title: 'Transactions',
  1622. id: '1',
  1623. limit: 1,
  1624. };
  1625. const dashboard = mockDashboard({widgets: [widget]});
  1626. renderTestComponent({
  1627. dashboard,
  1628. orgFeatures: [...defaultOrgFeatures],
  1629. params: {
  1630. widgetIndex: '0',
  1631. },
  1632. });
  1633. await userEvent.click(await screen.findByText('Area Chart'));
  1634. await userEvent.click(screen.getByText('Line Chart'));
  1635. expect(screen.getByText('Limit to 1 result')).toBeInTheDocument();
  1636. expect(eventsStatsMock).toHaveBeenCalledWith(
  1637. '/organizations/org-slug/events-stats/',
  1638. expect.objectContaining({
  1639. query: expect.objectContaining({
  1640. topEvents: 1,
  1641. }),
  1642. })
  1643. );
  1644. });
  1645. it('unsets the limit when going from timeseries to table', async function () {
  1646. const widget: Widget = {
  1647. displayType: DisplayType.AREA,
  1648. interval: '1d',
  1649. queries: [
  1650. {
  1651. name: 'Test Widget',
  1652. fields: ['count()', 'count_unique(user)', 'epm()', 'project'],
  1653. columns: ['project'],
  1654. aggregates: ['count()', 'count_unique(user)', 'epm()'],
  1655. conditions: '',
  1656. orderby: '',
  1657. },
  1658. ],
  1659. title: 'Transactions',
  1660. id: '1',
  1661. limit: 1,
  1662. };
  1663. const dashboard = mockDashboard({widgets: [widget]});
  1664. renderTestComponent({
  1665. dashboard,
  1666. orgFeatures: [...defaultOrgFeatures],
  1667. params: {
  1668. widgetIndex: '0',
  1669. },
  1670. });
  1671. await userEvent.click(await screen.findByText('Area Chart'));
  1672. await userEvent.click(screen.getByText('Table'));
  1673. expect(screen.queryByText('Limit to 1 result')).not.toBeInTheDocument();
  1674. expect(eventsMock).toHaveBeenCalledWith(
  1675. '/organizations/org-slug/events/',
  1676. expect.objectContaining({
  1677. query: expect.objectContaining({
  1678. topEvents: undefined,
  1679. }),
  1680. })
  1681. );
  1682. });
  1683. });
  1684. });