widgetBuilderSortBy.spec.tsx 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  1. import selectEvent from 'react-select-event';
  2. import {urlEncode} from '@sentry/utils';
  3. import {initializeOrg} from 'sentry-test/initializeOrg';
  4. import {render, screen, userEvent, waitFor} from 'sentry-test/reactTestingLibrary';
  5. import TagStore from 'sentry/stores/tagStore';
  6. import {
  7. DashboardDetails,
  8. DashboardWidgetSource,
  9. DisplayType,
  10. Widget,
  11. } from 'sentry/views/dashboards/types';
  12. import WidgetBuilder, {WidgetBuilderProps} from 'sentry/views/dashboards/widgetBuilder';
  13. const defaultOrgFeatures = [
  14. 'performance-view',
  15. 'dashboards-edit',
  16. 'global-views',
  17. 'dashboards-mep',
  18. ];
  19. // Mocking worldMapChart to avoid act warnings
  20. jest.mock('sentry/components/charts/worldMapChart');
  21. function mockDashboard(dashboard: Partial<DashboardDetails>): DashboardDetails {
  22. return {
  23. id: '1',
  24. title: 'Dashboard',
  25. createdBy: undefined,
  26. dateCreated: '2020-01-01T00:00:00.000Z',
  27. widgets: [],
  28. projects: [],
  29. filters: {},
  30. ...dashboard,
  31. };
  32. }
  33. function renderTestComponent({
  34. dashboard,
  35. query,
  36. orgFeatures,
  37. onSave,
  38. params,
  39. }: {
  40. dashboard?: WidgetBuilderProps['dashboard'];
  41. onSave?: WidgetBuilderProps['onSave'];
  42. orgFeatures?: string[];
  43. params?: Partial<WidgetBuilderProps['params']>;
  44. query?: Record<string, any>;
  45. } = {}) {
  46. const {organization, router, routerContext} = initializeOrg({
  47. ...initializeOrg(),
  48. organization: {
  49. features: orgFeatures ?? defaultOrgFeatures,
  50. },
  51. router: {
  52. location: {
  53. query: {
  54. source: DashboardWidgetSource.DASHBOARDS,
  55. ...query,
  56. },
  57. },
  58. },
  59. });
  60. render(
  61. <WidgetBuilder
  62. route={{}}
  63. router={router}
  64. routes={router.routes}
  65. routeParams={router.params}
  66. location={router.location}
  67. dashboard={{
  68. id: 'new',
  69. title: 'Dashboard',
  70. createdBy: undefined,
  71. dateCreated: '2020-01-01T00:00:00.000Z',
  72. widgets: [],
  73. projects: [],
  74. filters: {},
  75. ...dashboard,
  76. }}
  77. onSave={onSave ?? jest.fn()}
  78. params={{
  79. orgId: organization.slug,
  80. dashboardId: dashboard?.id ?? 'new',
  81. ...params,
  82. }}
  83. />,
  84. {
  85. context: routerContext,
  86. organization,
  87. }
  88. );
  89. return {router};
  90. }
  91. describe('WidgetBuilder', function () {
  92. const untitledDashboard: DashboardDetails = {
  93. id: '1',
  94. title: 'Untitled Dashboard',
  95. createdBy: undefined,
  96. dateCreated: '2020-01-01T00:00:00.000Z',
  97. widgets: [],
  98. projects: [],
  99. filters: {},
  100. };
  101. const testDashboard: DashboardDetails = {
  102. id: '2',
  103. title: 'Test Dashboard',
  104. createdBy: undefined,
  105. dateCreated: '2020-01-01T00:00:00.000Z',
  106. widgets: [],
  107. projects: [],
  108. filters: {},
  109. };
  110. let eventsStatsMock: jest.Mock | undefined;
  111. let eventsMock: jest.Mock | undefined;
  112. beforeEach(function () {
  113. MockApiClient.addMockResponse({
  114. url: '/organizations/org-slug/dashboards/',
  115. body: [
  116. {...untitledDashboard, widgetDisplay: [DisplayType.TABLE]},
  117. {...testDashboard, widgetDisplay: [DisplayType.AREA]},
  118. ],
  119. });
  120. MockApiClient.addMockResponse({
  121. url: '/organizations/org-slug/dashboards/widgets/',
  122. method: 'POST',
  123. statusCode: 200,
  124. body: [],
  125. });
  126. eventsMock = MockApiClient.addMockResponse({
  127. url: '/organizations/org-slug/events/',
  128. method: 'GET',
  129. statusCode: 200,
  130. body: {
  131. meta: {fields: {}},
  132. data: [],
  133. },
  134. });
  135. MockApiClient.addMockResponse({
  136. url: '/organizations/org-slug/projects/',
  137. method: 'GET',
  138. body: [],
  139. });
  140. MockApiClient.addMockResponse({
  141. url: '/organizations/org-slug/recent-searches/',
  142. method: 'GET',
  143. body: [],
  144. });
  145. MockApiClient.addMockResponse({
  146. url: '/organizations/org-slug/recent-searches/',
  147. method: 'POST',
  148. body: [],
  149. });
  150. MockApiClient.addMockResponse({
  151. url: '/organizations/org-slug/issues/',
  152. method: 'GET',
  153. body: [],
  154. });
  155. eventsStatsMock = MockApiClient.addMockResponse({
  156. url: '/organizations/org-slug/events-stats/',
  157. body: [],
  158. });
  159. MockApiClient.addMockResponse({
  160. url: '/organizations/org-slug/tags/event.type/values/',
  161. body: [{count: 2, name: 'Nvidia 1080ti'}],
  162. });
  163. MockApiClient.addMockResponse({
  164. url: '/organizations/org-slug/events-geo/',
  165. body: {data: [], meta: {}},
  166. });
  167. MockApiClient.addMockResponse({
  168. url: '/organizations/org-slug/users/',
  169. body: [],
  170. });
  171. MockApiClient.addMockResponse({
  172. method: 'GET',
  173. url: '/organizations/org-slug/sessions/',
  174. body: TestStubs.SessionsField({
  175. field: `sum(session)`,
  176. }),
  177. });
  178. MockApiClient.addMockResponse({
  179. method: 'GET',
  180. url: '/organizations/org-slug/metrics/data/',
  181. body: TestStubs.MetricsField({
  182. field: 'sum(sentry.sessions.session)',
  183. }),
  184. });
  185. MockApiClient.addMockResponse({
  186. url: '/organizations/org-slug/tags/',
  187. method: 'GET',
  188. body: TestStubs.Tags(),
  189. });
  190. MockApiClient.addMockResponse({
  191. url: '/organizations/org-slug/measurements-meta/',
  192. method: 'GET',
  193. body: {},
  194. });
  195. MockApiClient.addMockResponse({
  196. url: '/organizations/org-slug/tags/is/values/',
  197. method: 'GET',
  198. body: [],
  199. });
  200. MockApiClient.addMockResponse({
  201. url: '/organizations/org-slug/releases/',
  202. body: [],
  203. });
  204. TagStore.reset();
  205. });
  206. afterEach(function () {
  207. MockApiClient.clearMockResponses();
  208. jest.clearAllMocks();
  209. jest.useRealTimers();
  210. });
  211. describe('with events > Sort by selectors', function () {
  212. it('renders', async function () {
  213. renderTestComponent();
  214. expect(await screen.findByText('Sort by a column')).toBeInTheDocument();
  215. expect(
  216. screen.getByText("Choose one of the columns you've created to sort by.")
  217. ).toBeInTheDocument();
  218. // Selector "sortDirection"
  219. expect(screen.getByText('High to low')).toBeInTheDocument();
  220. // Selector "sortBy"
  221. expect(screen.getAllByText('count()')).toHaveLength(3);
  222. });
  223. it('sortBy defaults to the first field value when changing display type to table', async function () {
  224. const widget: Widget = {
  225. id: '1',
  226. title: 'Errors over time',
  227. interval: '5m',
  228. displayType: DisplayType.LINE,
  229. queries: [
  230. {
  231. name: 'errors',
  232. conditions: 'event.type:error',
  233. fields: ['count()', 'count_unique(id)'],
  234. aggregates: ['count()', 'count_unique(id)'],
  235. columns: [],
  236. orderby: '',
  237. },
  238. {
  239. name: 'csp',
  240. conditions: 'event.type:csp',
  241. fields: ['count()', 'count_unique(id)'],
  242. aggregates: ['count()', 'count_unique(id)'],
  243. columns: [],
  244. orderby: '',
  245. },
  246. ],
  247. };
  248. const dashboard = mockDashboard({widgets: [widget]});
  249. renderTestComponent({
  250. dashboard,
  251. params: {
  252. widgetIndex: '0',
  253. },
  254. });
  255. // Click on the displayType selector
  256. userEvent.click(await screen.findByText('Line Chart'));
  257. // Choose the table visualization
  258. userEvent.click(screen.getByText('Table'));
  259. expect(await screen.findByText('Sort by a column')).toBeInTheDocument();
  260. // Selector "sortDirection"
  261. expect(screen.getByText('High to low')).toBeInTheDocument();
  262. // Selector "sortBy"
  263. expect(screen.getAllByText('count()')).toHaveLength(3);
  264. });
  265. it('can update selectors values', async function () {
  266. const handleSave = jest.fn();
  267. const widget: Widget = {
  268. id: '1',
  269. title: 'Errors over time',
  270. interval: '5m',
  271. displayType: DisplayType.TABLE,
  272. queries: [
  273. {
  274. name: '',
  275. conditions: '',
  276. fields: ['count()', 'count_unique(id)'],
  277. aggregates: ['count()', 'count_unique(id)'],
  278. columns: [],
  279. orderby: '-count()',
  280. },
  281. ],
  282. };
  283. const dashboard = mockDashboard({widgets: [widget]});
  284. renderTestComponent({
  285. dashboard,
  286. onSave: handleSave,
  287. params: {
  288. widgetIndex: '0',
  289. },
  290. });
  291. expect(await screen.findByText('Sort by a column')).toBeInTheDocument();
  292. // Selector "sortDirection"
  293. expect(screen.getByText('High to low')).toBeInTheDocument();
  294. // Selector "sortBy"
  295. expect(screen.getAllByText('count()')).toHaveLength(3);
  296. await selectEvent.select(screen.getAllByText('count()')[2], 'count_unique(id)');
  297. // Wait for the Builder update the widget values
  298. await waitFor(() => {
  299. expect(screen.getAllByText('count()')).toHaveLength(2);
  300. });
  301. // Now count_unique(id) is selected in the "sortBy" selector
  302. expect(screen.getAllByText('count_unique(id)')).toHaveLength(2);
  303. await selectEvent.select(screen.getByText('High to low'), 'Low to high');
  304. // Saves the widget
  305. userEvent.click(screen.getByText('Update Widget'));
  306. await waitFor(() => {
  307. expect(handleSave).toHaveBeenCalledWith([
  308. expect.objectContaining({
  309. queries: [expect.objectContaining({orderby: 'count_unique(id)'})],
  310. }),
  311. ]);
  312. });
  313. });
  314. it('sortBy defaults to the first field value when coming from discover', async function () {
  315. const defaultWidgetQuery = {
  316. name: '',
  317. fields: ['title', 'count()', 'count_unique(user)', 'epm()', 'count()'],
  318. columns: ['title'],
  319. aggregates: ['count()', 'count_unique(user)', 'epm()', 'count()'],
  320. conditions: 'tag:value',
  321. orderby: '',
  322. };
  323. const {router} = renderTestComponent({
  324. query: {
  325. source: DashboardWidgetSource.DISCOVERV2,
  326. defaultWidgetQuery: urlEncode(defaultWidgetQuery),
  327. displayType: DisplayType.TABLE,
  328. defaultTableColumns: ['title', 'count()', 'count_unique(user)', 'epm()'],
  329. },
  330. });
  331. expect(await screen.findByText('Sort by a column')).toBeInTheDocument();
  332. // Selector "sortDirection"
  333. expect(screen.getByText('Low to high')).toBeInTheDocument();
  334. // Selector "sortBy"
  335. expect(screen.getAllByText('title')).toHaveLength(2);
  336. // Saves the widget
  337. userEvent.click(screen.getByText('Add Widget'));
  338. await waitFor(() => {
  339. expect(router.push).toHaveBeenCalledWith(
  340. expect.objectContaining({
  341. query: expect.objectContaining({queryOrderby: 'count()'}),
  342. })
  343. );
  344. });
  345. });
  346. it('sortBy is only visible on tabular visualizations or when there is a groupBy value selected on time-series visualizations', async function () {
  347. renderTestComponent();
  348. // Sort by shall be visible on table visualization
  349. expect(await screen.findByText('Sort by a column')).toBeInTheDocument();
  350. // Update visualization to be a time-series
  351. userEvent.click(screen.getByText('Table'));
  352. userEvent.click(screen.getByText('Line Chart'));
  353. // Time-series visualizations display GroupBy step
  354. expect(await screen.findByText('Group your results')).toBeInTheDocument();
  355. // Do not show sortBy when empty columns (groupBys) are added
  356. userEvent.click(screen.getByText('Add Group'));
  357. expect(screen.getAllByText('Select group')).toHaveLength(2);
  358. // SortBy step shall not be visible
  359. expect(screen.queryByText('Sort by a y-axis')).not.toBeInTheDocument();
  360. // Select GroupBy value
  361. await selectEvent.select(screen.getAllByText('Select group')[0], 'project');
  362. // Now that at least one groupBy value is selected, the SortBy step shall be visible
  363. expect(screen.getByText('Sort by a y-axis')).toBeInTheDocument();
  364. // Remove selected GroupBy value
  365. userEvent.click(screen.getAllByLabelText('Remove group')[0]);
  366. // SortBy step shall no longer be visible
  367. expect(screen.queryByText('Sort by a y-axis')).not.toBeInTheDocument();
  368. });
  369. it('allows for sorting by a custom equation', async function () {
  370. renderTestComponent({
  371. query: {
  372. source: DashboardWidgetSource.DASHBOARDS,
  373. displayType: DisplayType.LINE,
  374. },
  375. });
  376. await selectEvent.select(await screen.findByText('Select group'), 'project');
  377. expect(screen.getAllByText('count()')).toHaveLength(2);
  378. await selectEvent.select(screen.getAllByText('count()')[1], 'Custom Equation');
  379. userEvent.paste(
  380. screen.getByPlaceholderText('Enter Equation'),
  381. 'count_unique(user) * 2'
  382. );
  383. userEvent.keyboard('{enter}');
  384. await waitFor(() => {
  385. expect(eventsStatsMock).toHaveBeenCalledWith(
  386. '/organizations/org-slug/events-stats/',
  387. expect.objectContaining({
  388. query: expect.objectContaining({
  389. field: expect.arrayContaining(['equation|count_unique(user) * 2']),
  390. orderby: '-equation[0]',
  391. }),
  392. })
  393. );
  394. });
  395. }, 10000);
  396. it('persists the state when toggling between sorting options', async function () {
  397. renderTestComponent({
  398. query: {
  399. source: DashboardWidgetSource.DASHBOARDS,
  400. displayType: DisplayType.LINE,
  401. },
  402. });
  403. await selectEvent.select(await screen.findByText('Select group'), 'project');
  404. expect(screen.getAllByText('count()')).toHaveLength(2);
  405. await selectEvent.select(screen.getAllByText('count()')[1], 'Custom Equation');
  406. userEvent.paste(
  407. screen.getByPlaceholderText('Enter Equation'),
  408. 'count_unique(user) * 2'
  409. );
  410. userEvent.keyboard('{enter}');
  411. // Switch away from the Custom Equation
  412. expect(screen.getByText('project')).toBeInTheDocument();
  413. await selectEvent.select(screen.getByText('Custom Equation'), 'project');
  414. expect(screen.getAllByText('project')).toHaveLength(2);
  415. // Switch back, the equation should still be visible
  416. await selectEvent.select(screen.getAllByText('project')[1], 'Custom Equation');
  417. expect(screen.getByPlaceholderText('Enter Equation')).toHaveValue(
  418. 'count_unique(user) * 2'
  419. );
  420. });
  421. it('persists the state when updating y-axes', async function () {
  422. renderTestComponent({
  423. query: {
  424. source: DashboardWidgetSource.DASHBOARDS,
  425. displayType: DisplayType.LINE,
  426. },
  427. });
  428. await selectEvent.select(await screen.findByText('Select group'), 'project');
  429. expect(screen.getAllByText('count()')).toHaveLength(2);
  430. await selectEvent.select(screen.getAllByText('count()')[1], 'Custom Equation');
  431. userEvent.paste(
  432. screen.getByPlaceholderText('Enter Equation'),
  433. 'count_unique(user) * 2'
  434. );
  435. userEvent.keyboard('{enter}');
  436. // Add a y-axis
  437. userEvent.click(screen.getByText('Add Overlay'));
  438. // The equation should still be visible
  439. expect(screen.getByPlaceholderText('Enter Equation')).toHaveValue(
  440. 'count_unique(user) * 2'
  441. );
  442. });
  443. it('displays the custom equation if the widget has it saved', async function () {
  444. const widget: Widget = {
  445. id: '1',
  446. title: 'Test Widget',
  447. interval: '5m',
  448. displayType: DisplayType.LINE,
  449. queries: [
  450. {
  451. name: '',
  452. conditions: '',
  453. fields: ['count()', 'project'],
  454. aggregates: ['count()'],
  455. columns: ['project'],
  456. orderby: '-equation|count_unique(user) * 2',
  457. },
  458. ],
  459. };
  460. const dashboard = mockDashboard({widgets: [widget]});
  461. renderTestComponent({
  462. query: {
  463. source: DashboardWidgetSource.DASHBOARDS,
  464. displayType: DisplayType.LINE,
  465. },
  466. params: {
  467. widgetIndex: '0',
  468. },
  469. dashboard,
  470. });
  471. expect(await screen.findByPlaceholderText('Enter Equation')).toHaveValue(
  472. 'count_unique(user) * 2'
  473. );
  474. });
  475. it('displays Operators in the input dropdown', async function () {
  476. renderTestComponent({
  477. query: {
  478. source: DashboardWidgetSource.DASHBOARDS,
  479. displayType: DisplayType.LINE,
  480. },
  481. });
  482. await selectEvent.select(await screen.findByText('Select group'), 'project');
  483. expect(screen.getAllByText('count()')).toHaveLength(2);
  484. await selectEvent.select(screen.getAllByText('count()')[1], 'Custom Equation');
  485. selectEvent.openMenu(screen.getByPlaceholderText('Enter Equation'));
  486. userEvent.click(screen.getByPlaceholderText('Enter Equation'));
  487. expect(screen.getByText('Operators')).toBeInTheDocument();
  488. expect(screen.queryByText('Fields')).not.toBeInTheDocument();
  489. });
  490. it('hides Custom Equation input and resets orderby when switching to table', async function () {
  491. renderTestComponent({
  492. query: {
  493. source: DashboardWidgetSource.DASHBOARDS,
  494. displayType: DisplayType.LINE,
  495. },
  496. });
  497. await selectEvent.select(await screen.findByText('Select group'), 'project');
  498. expect(screen.getAllByText('count()')).toHaveLength(2);
  499. await selectEvent.select(screen.getAllByText('count()')[1], 'Custom Equation');
  500. userEvent.paste(
  501. screen.getByPlaceholderText('Enter Equation'),
  502. 'count_unique(user) * 2'
  503. );
  504. userEvent.keyboard('{enter}');
  505. // Switch the display type to Table
  506. userEvent.click(screen.getByText('Line Chart'));
  507. userEvent.click(screen.getByText('Table'));
  508. expect(screen.getAllByText('count()')).toHaveLength(2);
  509. expect(screen.queryByPlaceholderText('Enter Equation')).not.toBeInTheDocument();
  510. await waitFor(() => {
  511. expect(eventsMock).toHaveBeenCalledWith(
  512. '/organizations/org-slug/events/',
  513. expect.objectContaining({
  514. query: expect.objectContaining({
  515. sort: ['-count()'],
  516. }),
  517. })
  518. );
  519. });
  520. });
  521. it('does not show the Custom Equation input if the only y-axis left is an empty equation', async function () {
  522. renderTestComponent({
  523. query: {
  524. source: DashboardWidgetSource.DASHBOARDS,
  525. displayType: DisplayType.LINE,
  526. },
  527. });
  528. await selectEvent.select(await screen.findByText('Select group'), 'project');
  529. userEvent.click(screen.getByText('Add an Equation'));
  530. userEvent.click(screen.getAllByLabelText('Remove this Y-Axis')[0]);
  531. expect(screen.queryByPlaceholderText('Enter Equation')).not.toBeInTheDocument();
  532. });
  533. it('persists a sort by a grouping when changing y-axes', async function () {
  534. renderTestComponent({
  535. query: {
  536. source: DashboardWidgetSource.DASHBOARDS,
  537. displayType: DisplayType.LINE,
  538. },
  539. });
  540. await selectEvent.select(await screen.findByText('Select group'), 'project');
  541. expect(screen.getAllByText('count()')).toHaveLength(2);
  542. // Change the sort option to a grouping field, and then change a y-axis
  543. await selectEvent.select(screen.getAllByText('count()')[1], 'project');
  544. await selectEvent.select(screen.getAllByText('count()')[0], /count_unique/);
  545. // project should appear in the group by field, as well as the sort field
  546. expect(screen.getAllByText('project')).toHaveLength(2);
  547. });
  548. it('persists sort by a y-axis when grouping changes', async function () {
  549. renderTestComponent({
  550. query: {
  551. source: DashboardWidgetSource.DASHBOARDS,
  552. displayType: DisplayType.LINE,
  553. },
  554. });
  555. userEvent.click(await screen.findByText('Add Overlay'));
  556. await selectEvent.select(screen.getByText('Select group'), 'project');
  557. // Change the sort by to count_unique
  558. await selectEvent.select(screen.getAllByText('count()')[1], /count_unique/);
  559. // Change the grouping
  560. await selectEvent.select(screen.getByText('project'), 'environment');
  561. // count_unique(user) should still be the sorting field
  562. expect(screen.getByText(/count_unique/)).toBeInTheDocument();
  563. expect(screen.getByText('user')).toBeInTheDocument();
  564. });
  565. it('does not remove the Custom Equation field if a grouping is updated', async function () {
  566. renderTestComponent({
  567. query: {
  568. source: DashboardWidgetSource.DASHBOARDS,
  569. displayType: DisplayType.LINE,
  570. },
  571. });
  572. await selectEvent.select(await screen.findByText('Select group'), 'project');
  573. await selectEvent.select(screen.getAllByText('count()')[1], 'Custom Equation');
  574. userEvent.paste(
  575. screen.getByPlaceholderText('Enter Equation'),
  576. 'count_unique(user) * 2'
  577. );
  578. userEvent.keyboard('{enter}');
  579. userEvent.click(screen.getByText('Add Group'));
  580. expect(screen.getByPlaceholderText('Enter Equation')).toHaveValue(
  581. 'count_unique(user) * 2'
  582. );
  583. });
  584. it.each`
  585. directionPrefix | expectedOrderSelection | displayType
  586. ${'-'} | ${'High to low'} | ${DisplayType.TABLE}
  587. ${''} | ${'Low to high'} | ${DisplayType.TABLE}
  588. ${'-'} | ${'High to low'} | ${DisplayType.LINE}
  589. ${''} | ${'Low to high'} | ${DisplayType.LINE}
  590. `(
  591. `opens a widget with the '$expectedOrderSelection' sort order when the widget was saved with that direction`,
  592. async function ({directionPrefix, expectedOrderSelection}) {
  593. const widget: Widget = {
  594. id: '1',
  595. title: 'Test Widget',
  596. interval: '5m',
  597. displayType: DisplayType.LINE,
  598. queries: [
  599. {
  600. name: '',
  601. conditions: '',
  602. fields: ['count_unique(user)'],
  603. aggregates: ['count_unique(user)'],
  604. columns: ['project'],
  605. orderby: `${directionPrefix}count_unique(user)`,
  606. },
  607. ],
  608. };
  609. const dashboard = mockDashboard({widgets: [widget]});
  610. renderTestComponent({
  611. dashboard,
  612. params: {
  613. widgetIndex: '0',
  614. },
  615. });
  616. await screen.findByText(expectedOrderSelection);
  617. }
  618. );
  619. it('saved widget with aggregate alias as orderby should persist alias when y-axes change', async function () {
  620. const widget: Widget = {
  621. id: '1',
  622. title: 'Test Widget',
  623. interval: '5m',
  624. displayType: DisplayType.TABLE,
  625. queries: [
  626. {
  627. name: '',
  628. conditions: '',
  629. fields: ['project', 'count_unique(user)'],
  630. aggregates: ['count_unique(user)'],
  631. columns: ['project'],
  632. orderby: 'count_unique(user)',
  633. },
  634. ],
  635. };
  636. const dashboard = mockDashboard({widgets: [widget]});
  637. renderTestComponent({
  638. dashboard,
  639. params: {
  640. widgetIndex: '0',
  641. },
  642. });
  643. await screen.findByText('Sort by a column');
  644. // Assert for length 2 since one in the table header and one in sort by
  645. expect(screen.getAllByText('count_unique(user)')).toHaveLength(2);
  646. userEvent.click(screen.getByText('Add a Column'));
  647. // The sort by should still have count_unique(user)
  648. await waitFor(() =>
  649. expect(screen.getAllByText('count_unique(user)')).toHaveLength(2)
  650. );
  651. });
  652. it('will reset the sort field when going from line to table when sorting by a value not in fields', async function () {
  653. renderTestComponent({
  654. query: {
  655. displayType: DisplayType.LINE,
  656. },
  657. });
  658. await selectEvent.select(await screen.findByText('Select group'), 'project');
  659. expect(screen.getAllByText('count()')).toHaveLength(2);
  660. await selectEvent.select(screen.getAllByText('count()')[1], /count_unique/);
  661. userEvent.click(screen.getByText('Line Chart'));
  662. userEvent.click(screen.getByText('Table'));
  663. // 1 for table header, 1 for column selection, and 1 for sorting
  664. await waitFor(() => {
  665. expect(screen.getAllByText('count()')).toHaveLength(3);
  666. });
  667. });
  668. it('equations in y-axis appear in sort by field for grouped timeseries', async function () {
  669. renderTestComponent({
  670. query: {
  671. displayType: DisplayType.LINE,
  672. },
  673. });
  674. userEvent.click(await screen.findByText('Add an Equation'));
  675. userEvent.paste(screen.getByPlaceholderText('Equation'), 'count() * 100');
  676. userEvent.keyboard('{enter}');
  677. await selectEvent.select(screen.getByText('Select group'), 'project');
  678. expect(screen.getAllByText('count()')).toHaveLength(2);
  679. await selectEvent.select(screen.getAllByText('count()')[1], 'count() * 100');
  680. });
  681. it('does not reset the orderby when ordered by an equation in table', async function () {
  682. const widget: Widget = {
  683. id: '1',
  684. title: 'Errors over time',
  685. interval: '5m',
  686. displayType: DisplayType.TABLE,
  687. queries: [
  688. {
  689. name: '',
  690. conditions: '',
  691. fields: [
  692. 'count()',
  693. 'count_unique(id)',
  694. 'equation|count() + count_unique(id)',
  695. ],
  696. aggregates: [
  697. 'count()',
  698. 'count_unique(id)',
  699. 'equation|count() + count_unique(id)',
  700. ],
  701. columns: [],
  702. orderby: '-equation[0]',
  703. },
  704. ],
  705. };
  706. const dashboard = mockDashboard({widgets: [widget]});
  707. renderTestComponent({
  708. dashboard,
  709. params: {
  710. widgetIndex: '0',
  711. },
  712. });
  713. await screen.findByText('Sort by a column');
  714. // 1 in the column selector, 1 in the sort by field
  715. expect(screen.getAllByText('count() + count_unique(id)')).toHaveLength(2);
  716. });
  717. });
  718. it('ordering by column uses field form when selecting orderby', async function () {
  719. const widget: Widget = {
  720. id: '1',
  721. title: 'Test Widget',
  722. interval: '5m',
  723. displayType: DisplayType.TABLE,
  724. queries: [
  725. {
  726. name: 'errors',
  727. conditions: 'event.type:error',
  728. fields: ['count()'],
  729. aggregates: ['count()'],
  730. columns: ['project'],
  731. orderby: '-project',
  732. },
  733. ],
  734. };
  735. const dashboard = mockDashboard({widgets: [widget]});
  736. renderTestComponent({
  737. orgFeatures: [...defaultOrgFeatures],
  738. dashboard,
  739. params: {
  740. widgetIndex: '0',
  741. },
  742. });
  743. const projectElements = screen.getAllByText('project');
  744. await selectEvent.select(projectElements[projectElements.length - 1], 'count()');
  745. await waitFor(() => {
  746. expect(eventsMock).toHaveBeenCalledWith(
  747. '/organizations/org-slug/events/',
  748. expect.objectContaining({
  749. query: expect.objectContaining({
  750. sort: ['-count()'],
  751. }),
  752. })
  753. );
  754. });
  755. });
  756. it('hides Custom Equation input and resets orderby when switching to table', async function () {
  757. renderTestComponent({
  758. orgFeatures: [...defaultOrgFeatures],
  759. query: {
  760. source: DashboardWidgetSource.DASHBOARDS,
  761. displayType: DisplayType.LINE,
  762. },
  763. });
  764. await selectEvent.select(await screen.findByText('Select group'), 'project');
  765. expect(screen.getAllByText('count()')).toHaveLength(2);
  766. await selectEvent.select(screen.getAllByText('count()')[1], 'Custom Equation');
  767. userEvent.paste(
  768. screen.getByPlaceholderText('Enter Equation'),
  769. 'count_unique(user) * 2'
  770. );
  771. userEvent.keyboard('{enter}');
  772. // Switch the display type to Table
  773. userEvent.click(screen.getByText('Line Chart'));
  774. userEvent.click(screen.getByText('Table'));
  775. expect(screen.getAllByText('count()')).toHaveLength(2);
  776. expect(screen.queryByPlaceholderText('Enter Equation')).not.toBeInTheDocument();
  777. await waitFor(() => {
  778. expect(eventsMock).toHaveBeenCalledWith(
  779. '/organizations/org-slug/events/',
  780. expect.objectContaining({
  781. query: expect.objectContaining({
  782. sort: ['-count()'],
  783. }),
  784. })
  785. );
  786. });
  787. });
  788. });