widgetBuilder.spec.tsx 59 KB

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