widgetBuilder.spec.tsx 59 KB

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