widgetBuilder.spec.tsx 59 KB

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