widgetBuilder.spec.tsx 64 KB

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