widgetBuilderSortBy.spec.tsx 28 KB

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