index.spec.tsx 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831
  1. import type {Location} from 'history';
  2. import {OrganizationFixture} from 'sentry-fixture/organization';
  3. import {ProjectFixture} from 'sentry-fixture/project';
  4. import {initializeOrg} from 'sentry-test/initializeOrg';
  5. import type {InitializeDataSettings} from 'sentry-test/performance/initializePerformanceData';
  6. import {initializeData} from 'sentry-test/performance/initializePerformanceData';
  7. import {
  8. act,
  9. fireEvent,
  10. render,
  11. screen,
  12. userEvent,
  13. waitFor,
  14. within,
  15. } from 'sentry-test/reactTestingLibrary';
  16. import PageFiltersStore from 'sentry/stores/pageFiltersStore';
  17. import ProjectsStore from 'sentry/stores/projectsStore';
  18. import {browserHistory} from 'sentry/utils/browserHistory';
  19. import {WebVital} from 'sentry/utils/fields';
  20. import {useLocation} from 'sentry/utils/useLocation';
  21. import TrendsIndex from 'sentry/views/performance/trends/';
  22. import {defaultTrendsSelectionDate} from 'sentry/views/performance/trends/content';
  23. import {
  24. DEFAULT_MAX_DURATION,
  25. TRENDS_FUNCTIONS,
  26. TRENDS_PARAMETERS,
  27. } from 'sentry/views/performance/trends/utils';
  28. const trendsViewQuery = {
  29. query: `tpm():>0.01 transaction.duration:>0 transaction.duration:<${DEFAULT_MAX_DURATION}`,
  30. };
  31. jest.mock('sentry/utils/useLocation');
  32. const mockUseLocation = jest.mocked(useLocation);
  33. jest.mock('moment-timezone', () => {
  34. const moment = jest.requireActual('moment-timezone');
  35. moment.now = jest.fn().mockReturnValue(1601251200000);
  36. return moment;
  37. });
  38. async function getTrendDropdown() {
  39. const dropdown = await screen.findByRole('button', {name: /Percentile.+/});
  40. expect(dropdown).toBeInTheDocument();
  41. return dropdown;
  42. }
  43. async function getParameterDropdown() {
  44. const dropdown = await screen.findByRole('button', {name: /Parameter.+/});
  45. expect(dropdown).toBeInTheDocument();
  46. return dropdown;
  47. }
  48. async function waitForMockCall(mock: any) {
  49. await waitFor(() => {
  50. expect(mock).toHaveBeenCalled();
  51. });
  52. }
  53. function enterSearch(el: HTMLElement, text: string) {
  54. fireEvent.change(el, {target: {value: text}});
  55. fireEvent.submit(el);
  56. }
  57. // Might swap on/off the skiphover to check perf later.
  58. async function clickEl(el: HTMLElement) {
  59. await userEvent.click(el, {skipHover: true});
  60. }
  61. function _initializeData(
  62. settings: InitializeDataSettings,
  63. options?: {selectedProjectId?: string}
  64. ) {
  65. const newSettings = {...settings};
  66. newSettings.projects = settings.projects ?? [
  67. ProjectFixture({id: '1', firstTransactionEvent: false}),
  68. ProjectFixture({id: '2', firstTransactionEvent: true}),
  69. ];
  70. if (options?.selectedProjectId) {
  71. const selectedProject = newSettings.projects.find(
  72. p => p.id === options.selectedProjectId
  73. );
  74. if (!selectedProject) {
  75. throw new Error("Test is selecting project that isn't loaded");
  76. } else {
  77. PageFiltersStore.updateProjects(
  78. settings.selectedProject ? [Number(selectedProject)] : [],
  79. []
  80. );
  81. }
  82. newSettings.selectedProject = selectedProject.id;
  83. }
  84. newSettings.selectedProject = settings.selectedProject ?? newSettings.projects[0].id;
  85. const data = initializeData(newSettings);
  86. // Modify page filters store to stop rerendering due to the test harness.
  87. PageFiltersStore.onInitializeUrlState(
  88. {
  89. projects: [],
  90. environments: [],
  91. datetime: {start: null, end: null, period: '24h', utc: null},
  92. },
  93. new Set()
  94. );
  95. PageFiltersStore.updateDateTime(defaultTrendsSelectionDate);
  96. if (!options?.selectedProjectId) {
  97. PageFiltersStore.updateProjects(
  98. settings.selectedProject ? [Number(newSettings.projects[0].id)] : [],
  99. []
  100. );
  101. }
  102. act(() => ProjectsStore.loadInitialData(data.projects));
  103. return data;
  104. }
  105. function initializeTrendsData(
  106. projects: null | any[] = null,
  107. query = {},
  108. includeDefaultQuery = true,
  109. extraFeatures?: string[]
  110. ) {
  111. const _projects = Array.isArray(projects)
  112. ? projects
  113. : [
  114. ProjectFixture({id: '1', firstTransactionEvent: false}),
  115. ProjectFixture({id: '2', firstTransactionEvent: true}),
  116. ];
  117. const features = extraFeatures
  118. ? ['transaction-event', 'performance-view', ...extraFeatures]
  119. : ['transaction-event', 'performance-view'];
  120. const organization = OrganizationFixture({features});
  121. const newQuery = {...(includeDefaultQuery ? trendsViewQuery : {}), ...query};
  122. mockUseLocation.mockReturnValue({
  123. pathname: '/organizations/org-slug/performance/trends/',
  124. action: 'PUSH',
  125. hash: '',
  126. key: '',
  127. query: newQuery,
  128. search: '',
  129. state: undefined,
  130. });
  131. const initialData = initializeOrg({
  132. organization,
  133. router: {
  134. location: {
  135. pathname: '/trends/',
  136. query: newQuery,
  137. },
  138. },
  139. projects: _projects,
  140. });
  141. act(() => ProjectsStore.loadInitialData(initialData.projects));
  142. return initialData;
  143. }
  144. describe('Performance > Trends', function () {
  145. let trendsStatsMock: jest.Mock;
  146. beforeEach(function () {
  147. mockUseLocation.mockReturnValue({
  148. pathname: '/organizations/org-slug/performance/trends/',
  149. action: 'PUSH',
  150. hash: '',
  151. key: '',
  152. query: {},
  153. search: '',
  154. state: undefined,
  155. });
  156. browserHistory.push = jest.fn();
  157. MockApiClient.addMockResponse({
  158. url: '/organizations/org-slug/projects/',
  159. body: [],
  160. });
  161. MockApiClient.addMockResponse({
  162. url: '/organizations/org-slug/tags/',
  163. body: [],
  164. });
  165. MockApiClient.addMockResponse({
  166. url: '/organizations/org-slug/users/',
  167. body: [],
  168. });
  169. MockApiClient.addMockResponse({
  170. url: '/organizations/org-slug/recent-searches/',
  171. body: [],
  172. });
  173. MockApiClient.addMockResponse({
  174. url: '/organizations/org-slug/recent-searches/',
  175. method: 'POST',
  176. body: [],
  177. });
  178. MockApiClient.addMockResponse({
  179. url: '/organizations/org-slug/sdk-updates/',
  180. body: [],
  181. });
  182. MockApiClient.addMockResponse({
  183. url: '/organizations/org-slug/prompts-activity/',
  184. body: {},
  185. });
  186. MockApiClient.addMockResponse({
  187. url: '/organizations/org-slug/releases/stats/',
  188. body: [],
  189. });
  190. MockApiClient.addMockResponse({
  191. url: '/organizations/org-slug/tags/transaction.duration/values/',
  192. body: [],
  193. });
  194. trendsStatsMock = MockApiClient.addMockResponse({
  195. url: '/organizations/org-slug/events-trends-stats/',
  196. body: {
  197. stats: {
  198. 'internal,/organizations/:orgId/performance/': {
  199. data: [[123, []]],
  200. },
  201. order: 0,
  202. },
  203. events: {
  204. meta: {
  205. count_range_1: 'integer',
  206. count_range_2: 'integer',
  207. count_percentage: 'percentage',
  208. breakpoint: 'number',
  209. trend_percentage: 'percentage',
  210. trend_difference: 'number',
  211. aggregate_range_1: 'duration',
  212. aggregate_range_2: 'duration',
  213. transaction: 'string',
  214. },
  215. data: [
  216. {
  217. count: 8,
  218. project: 'internal',
  219. count_range_1: 2,
  220. count_range_2: 6,
  221. count_percentage: 3,
  222. breakpoint: 1686967200,
  223. trend_percentage: 1.9235225955967554,
  224. trend_difference: 797,
  225. aggregate_range_1: 863,
  226. aggregate_range_2: 1660,
  227. transaction: '/organizations/:orgId/performance/',
  228. },
  229. {
  230. count: 60,
  231. project: 'internal',
  232. count_range_1: 20,
  233. count_range_2: 40,
  234. count_percentage: 2,
  235. breakpoint: 1686967200,
  236. trend_percentage: 1.204968944099379,
  237. trend_difference: 66,
  238. aggregate_range_1: 322,
  239. aggregate_range_2: 388,
  240. transaction: '/api/0/internal/health/',
  241. },
  242. ],
  243. },
  244. },
  245. });
  246. MockApiClient.addMockResponse({
  247. url: '/organizations/org-slug/events/',
  248. body: {
  249. data: [
  250. {
  251. 'p95()': 1010.9232499999998,
  252. 'p50()': 47.34580982348902,
  253. 'tps()': 3.7226926286168966,
  254. 'count()': 34872349,
  255. 'failure_rate()': 0.43428379,
  256. 'examples()': ['djk3w308er', '3298a9ui3h'],
  257. },
  258. ],
  259. meta: {
  260. fields: {
  261. 'p95()': 'duration',
  262. '950()': 'duration',
  263. 'tps()': 'number',
  264. 'count()': 'number',
  265. 'failure_rate()': 'number',
  266. 'examples()': 'Array',
  267. },
  268. units: {
  269. 'p95()': 'millisecond',
  270. 'p50()': 'millisecond',
  271. 'tps()': null,
  272. 'count()': null,
  273. 'failure_rate()': null,
  274. 'examples()': null,
  275. },
  276. isMetricsData: true,
  277. tips: {},
  278. dataset: 'metrics',
  279. },
  280. },
  281. });
  282. MockApiClient.addMockResponse({
  283. url: '/organizations/org-slug/events-spans-performance/',
  284. body: [],
  285. });
  286. });
  287. afterEach(function () {
  288. MockApiClient.clearMockResponses();
  289. act(() => ProjectsStore.reset());
  290. });
  291. it('renders basic UI elements', async function () {
  292. const data = _initializeData({});
  293. render(
  294. <TrendsIndex location={data.router.location} organization={data.organization} />,
  295. {
  296. router: data.router,
  297. organization: data.organization,
  298. }
  299. );
  300. expect(await getTrendDropdown()).toBeInTheDocument();
  301. expect(await getParameterDropdown()).toBeInTheDocument();
  302. expect(screen.getAllByTestId('changed-transactions')).toHaveLength(2);
  303. });
  304. it('transaction list items are rendered', async function () {
  305. const data = _initializeData({});
  306. render(
  307. <TrendsIndex location={data.router.location} organization={data.organization} />,
  308. {
  309. router: data.router,
  310. organization: data.organization,
  311. }
  312. );
  313. expect(await screen.findAllByTestId('trends-list-item-regression')).toHaveLength(2);
  314. expect(await screen.findAllByTestId('trends-list-item-improved')).toHaveLength(2);
  315. });
  316. it('view summary menu action links to the correct view', async function () {
  317. const projects = [ProjectFixture({id: '1', slug: 'internal'}), ProjectFixture()];
  318. const data = initializeTrendsData(projects, {project: ['1']});
  319. render(
  320. <TrendsIndex location={data.router.location} organization={data.organization} />,
  321. {
  322. router: data.router,
  323. organization: data.organization,
  324. }
  325. );
  326. const transactions = await screen.findAllByTestId('trends-list-item-improved');
  327. expect(transactions).toHaveLength(2);
  328. const firstTransaction = transactions[0];
  329. const summaryLink = within(firstTransaction).getByTestId('item-transaction-name');
  330. expect(summaryLink.closest('a')).toHaveAttribute(
  331. 'href',
  332. '/organizations/org-slug/performance/summary/?display=trend&project=1&query=tpm%28%29%3A%3E0.01%20transaction.duration%3A%3E0%20transaction.duration%3A%3C15min%20count_percentage%28%29%3A%3E0.25%20count_percentage%28%29%3A%3C4%20trend_percentage%28%29%3A%3E0%25%20confidence%28%29%3A%3E6&referrer=performance-transaction-summary&statsPeriod=14d&transaction=%2Forganizations%2F%3AorgId%2Fperformance%2F&trendFunction=p95&unselectedSeries=p100%28%29&unselectedSeries=avg%28%29'
  333. );
  334. });
  335. it('view summary menu action opens performance change explorer with feature flag', async function () {
  336. const projects = [ProjectFixture({id: '1', slug: 'internal'}), ProjectFixture()];
  337. const data = initializeTrendsData(projects, {project: ['1']}, true, [
  338. 'performance-change-explorer',
  339. ]);
  340. render(
  341. <TrendsIndex location={data.router.location} organization={data.organization} />,
  342. {
  343. router: data.router,
  344. organization: data.organization,
  345. }
  346. );
  347. const transactions = await screen.findAllByTestId('trends-list-item-improved');
  348. expect(transactions).toHaveLength(2);
  349. const firstTransaction = transactions[0];
  350. const summaryLink = within(firstTransaction).getByTestId('item-transaction-name');
  351. expect(summaryLink.closest('a')).toHaveAttribute(
  352. 'href',
  353. '/trends/?project=1&query=tpm%28%29%3A%3E0.01%20transaction.duration%3A%3E0%20transaction.duration%3A%3C15min'
  354. );
  355. await clickEl(summaryLink);
  356. await waitFor(() => {
  357. expect(screen.getByText('Ongoing Improvement')).toBeInTheDocument();
  358. expect(screen.getByText('Throughput')).toBeInTheDocument();
  359. expect(screen.getByText('P95')).toBeInTheDocument();
  360. expect(screen.getByText('P50')).toBeInTheDocument();
  361. expect(screen.getByText('Failure Rate')).toBeInTheDocument();
  362. });
  363. });
  364. it('hide from list menu action modifies query', async function () {
  365. const projects = [ProjectFixture({id: '1', slug: 'internal'}), ProjectFixture()];
  366. const data = initializeTrendsData(projects, {project: ['1']});
  367. render(
  368. <TrendsIndex location={data.router.location} organization={data.organization} />,
  369. {
  370. router: data.router,
  371. organization: data.organization,
  372. }
  373. );
  374. const transactions = await screen.findAllByTestId('trends-list-item-improved');
  375. expect(transactions).toHaveLength(2);
  376. const firstTransaction = transactions[0];
  377. await userEvent.click(
  378. within(firstTransaction).getByRole('button', {name: 'Actions'})
  379. );
  380. await waitFor(() => {
  381. const menuActions = within(firstTransaction).getAllByRole('menuitemradio');
  382. expect(menuActions).toHaveLength(3);
  383. });
  384. const menuAction = within(firstTransaction).getAllByRole('menuitemradio')[2];
  385. await clickEl(menuAction);
  386. expect(browserHistory.push).toHaveBeenCalledWith({
  387. pathname: '/trends/',
  388. query: expect.objectContaining({
  389. project: expect.anything(),
  390. query: `tpm():>0.01 transaction.duration:>0 transaction.duration:<${DEFAULT_MAX_DURATION} !transaction:/organizations/:orgId/performance/`,
  391. }),
  392. });
  393. });
  394. it('Changing search causes cursors to be reset', async function () {
  395. const projects = [ProjectFixture({id: '1', slug: 'internal'}), ProjectFixture()];
  396. const data = initializeTrendsData(projects, {project: ['1']});
  397. render(
  398. <TrendsIndex location={data.router.location} organization={data.organization} />,
  399. {
  400. router: data.router,
  401. organization: data.organization,
  402. }
  403. );
  404. const input = await screen.findByTestId('smart-search-input');
  405. enterSearch(input, 'transaction.duration:>9000');
  406. await waitFor(() =>
  407. expect(browserHistory.push).toHaveBeenCalledWith({
  408. pathname: '/trends/',
  409. query: expect.objectContaining({
  410. project: ['1'],
  411. query: 'transaction.duration:>9000',
  412. improvedCursor: undefined,
  413. regressionCursor: undefined,
  414. }),
  415. })
  416. );
  417. });
  418. it('exclude greater than list menu action modifies query', async function () {
  419. const projects = [ProjectFixture({id: '1', slug: 'internal'}), ProjectFixture()];
  420. const data = initializeTrendsData(projects, {project: ['1']});
  421. render(
  422. <TrendsIndex location={data.router.location} organization={data.organization} />,
  423. {
  424. router: data.router,
  425. organization: data.organization,
  426. }
  427. );
  428. const transactions = await screen.findAllByTestId('trends-list-item-improved');
  429. expect(transactions).toHaveLength(2);
  430. const firstTransaction = transactions[0];
  431. await userEvent.click(
  432. within(firstTransaction).getByRole('button', {name: 'Actions'})
  433. );
  434. await waitFor(() => {
  435. const menuActions = within(firstTransaction).getAllByRole('menuitemradio');
  436. expect(menuActions).toHaveLength(3);
  437. });
  438. const menuAction = within(firstTransaction).getAllByRole('menuitemradio')[0];
  439. await clickEl(menuAction);
  440. expect(browserHistory.push).toHaveBeenCalledWith({
  441. pathname: '/trends/',
  442. query: expect.objectContaining({
  443. project: expect.anything(),
  444. query: 'tpm():>0.01 transaction.duration:>0 transaction.duration:<=863',
  445. }),
  446. });
  447. });
  448. it('exclude less than list menu action modifies query', async function () {
  449. const projects = [ProjectFixture({id: '1', slug: 'internal'}), ProjectFixture()];
  450. const data = initializeTrendsData(projects, {project: ['1']});
  451. render(
  452. <TrendsIndex location={data.router.location} organization={data.organization} />,
  453. {
  454. router: data.router,
  455. organization: data.organization,
  456. }
  457. );
  458. const transactions = await screen.findAllByTestId('trends-list-item-improved');
  459. expect(transactions).toHaveLength(2);
  460. const firstTransaction = transactions[0];
  461. await userEvent.click(
  462. within(firstTransaction).getByRole('button', {name: 'Actions'})
  463. );
  464. await waitFor(() => {
  465. const menuActions = within(firstTransaction).getAllByRole('menuitemradio');
  466. expect(menuActions).toHaveLength(3);
  467. });
  468. const menuAction = within(firstTransaction).getAllByRole('menuitemradio')[1];
  469. await clickEl(menuAction);
  470. expect(browserHistory.push).toHaveBeenCalledWith({
  471. pathname: '/trends/',
  472. query: expect.objectContaining({
  473. project: expect.anything(),
  474. query: 'tpm():>0.01 transaction.duration:<15min transaction.duration:>=863',
  475. }),
  476. });
  477. });
  478. it('choosing a trend function changes location', async function () {
  479. const projects = [ProjectFixture()];
  480. const data = initializeTrendsData(projects, {project: ['-1']});
  481. render(
  482. <TrendsIndex location={data.router.location} organization={data.organization} />,
  483. {
  484. router: data.router,
  485. organization: data.organization,
  486. }
  487. );
  488. for (const trendFunction of TRENDS_FUNCTIONS) {
  489. // Open dropdown
  490. const dropdown = await getTrendDropdown();
  491. await clickEl(dropdown);
  492. // Select function
  493. const option = screen.getByRole('option', {name: trendFunction.label});
  494. await clickEl(option);
  495. expect(browserHistory.push).toHaveBeenCalledWith({
  496. pathname: '/trends/',
  497. query: expect.objectContaining({
  498. regressionCursor: undefined,
  499. improvedCursor: undefined,
  500. trendFunction: trendFunction.field,
  501. }),
  502. });
  503. }
  504. });
  505. it('sets LCP as a default trend parameter for frontend project if query does not specify trend parameter', async function () {
  506. const projects = [ProjectFixture({id: '1', platform: 'javascript'})];
  507. const data = initializeTrendsData(projects, {project: [1]});
  508. render(
  509. <TrendsIndex location={data.router.location} organization={data.organization} />,
  510. {
  511. router: data.router,
  512. organization: data.organization,
  513. }
  514. );
  515. const trendDropdownButton = await getTrendDropdown();
  516. expect(trendDropdownButton).toHaveTextContent('Percentilep95');
  517. });
  518. it('sets duration as a default trend parameter for backend project if query does not specify trend parameter', async function () {
  519. const projects = [ProjectFixture({id: '1', platform: 'python'})];
  520. const data = initializeTrendsData(projects, {project: [1]});
  521. render(
  522. <TrendsIndex location={data.router.location} organization={data.organization} />,
  523. {
  524. router: data.router,
  525. organization: data.organization,
  526. }
  527. );
  528. const parameterDropdownButton = await getParameterDropdown();
  529. expect(parameterDropdownButton).toHaveTextContent('ParameterDuration');
  530. });
  531. it('sets trend parameter from query and ignores default trend parameter', async function () {
  532. const projects = [ProjectFixture({id: '1', platform: 'javascript'})];
  533. const data = initializeTrendsData(projects, {project: [1], trendParameter: 'FCP'});
  534. render(
  535. <TrendsIndex location={data.router.location} organization={data.organization} />,
  536. {
  537. router: data.router,
  538. organization: data.organization,
  539. }
  540. );
  541. const parameterDropdownButton = await getParameterDropdown();
  542. expect(parameterDropdownButton).toHaveTextContent('ParameterFCP');
  543. });
  544. it('choosing a parameter changes location', async function () {
  545. const projects = [ProjectFixture()];
  546. const data = initializeTrendsData(projects, {project: ['-1']});
  547. render(
  548. <TrendsIndex location={data.router.location} organization={data.organization} />,
  549. {
  550. router: data.router,
  551. organization: data.organization,
  552. }
  553. );
  554. for (const parameter of TRENDS_PARAMETERS) {
  555. // Open dropdown
  556. const dropdown = await getParameterDropdown();
  557. await clickEl(dropdown);
  558. // Select parameter
  559. const option = screen.getByRole('option', {name: parameter.label});
  560. await clickEl(option);
  561. expect(browserHistory.push).toHaveBeenCalledWith({
  562. pathname: '/trends/',
  563. query: expect.objectContaining({
  564. trendParameter: parameter.label,
  565. }),
  566. });
  567. }
  568. });
  569. it('choosing a web vitals parameter adds it as an additional condition to the query', async function () {
  570. const projects = [ProjectFixture()];
  571. const data = initializeTrendsData(projects, {project: ['-1']});
  572. const {rerender} = render(
  573. <TrendsIndex location={data.router.location} organization={data.organization} />,
  574. {
  575. router: data.router,
  576. organization: data.organization,
  577. }
  578. );
  579. for (const parameter of TRENDS_PARAMETERS) {
  580. if (Object.values(WebVital).includes(parameter.column as string as WebVital)) {
  581. trendsStatsMock.mockReset();
  582. const newLocation = {
  583. query: {...trendsViewQuery, trendParameter: parameter.label},
  584. };
  585. rerender(
  586. <TrendsIndex
  587. location={newLocation as unknown as Location}
  588. organization={data.organization}
  589. />
  590. );
  591. await waitForMockCall(trendsStatsMock);
  592. expect(trendsStatsMock).toHaveBeenCalledTimes(2);
  593. // Improved transactions call
  594. expect(trendsStatsMock).toHaveBeenNthCalledWith(
  595. 1,
  596. expect.anything(),
  597. expect.objectContaining({
  598. query: expect.objectContaining({
  599. query: expect.stringContaining(`has:${parameter.column}`),
  600. }),
  601. })
  602. );
  603. // Regression transactions call
  604. expect(trendsStatsMock).toHaveBeenNthCalledWith(
  605. 2,
  606. expect.anything(),
  607. expect.objectContaining({
  608. query: expect.objectContaining({
  609. query: expect.stringContaining(`has:${parameter.column}`),
  610. }),
  611. })
  612. );
  613. }
  614. }
  615. });
  616. it('trend functions in location make api calls', async function () {
  617. const projects = [ProjectFixture(), ProjectFixture()];
  618. const data = initializeTrendsData(projects, {project: ['-1']});
  619. const {rerender} = render(
  620. <TrendsIndex location={data.router.location} organization={data.organization} />,
  621. {
  622. router: data.router,
  623. organization: data.organization,
  624. }
  625. );
  626. for (const trendFunction of TRENDS_FUNCTIONS) {
  627. trendsStatsMock.mockReset();
  628. const newLocation = {
  629. query: {...trendsViewQuery, trendFunction: trendFunction.field},
  630. };
  631. rerender(
  632. <TrendsIndex
  633. location={newLocation as unknown as Location}
  634. organization={data.organization}
  635. />
  636. );
  637. await waitForMockCall(trendsStatsMock);
  638. expect(trendsStatsMock).toHaveBeenCalledTimes(2);
  639. const sort = 'trend_percentage()';
  640. const defaultTrendsFields = ['project'];
  641. const transactionFields = ['transaction', ...defaultTrendsFields];
  642. const projectFields = [...defaultTrendsFields];
  643. expect(transactionFields).toHaveLength(2);
  644. expect(projectFields).toHaveLength(transactionFields.length - 1);
  645. // Improved transactions call
  646. expect(trendsStatsMock).toHaveBeenNthCalledWith(
  647. 1,
  648. expect.anything(),
  649. expect.objectContaining({
  650. query: expect.objectContaining({
  651. trendFunction: `${trendFunction.field}(transaction.duration)`,
  652. sort,
  653. query: expect.stringContaining('trend_percentage():>0%'),
  654. interval: '1h',
  655. field: transactionFields,
  656. statsPeriod: '14d',
  657. }),
  658. })
  659. );
  660. // Regression transactions call
  661. expect(trendsStatsMock).toHaveBeenNthCalledWith(
  662. 2,
  663. expect.anything(),
  664. expect.objectContaining({
  665. query: expect.objectContaining({
  666. trendFunction: `${trendFunction.field}(transaction.duration)`,
  667. sort: '-' + sort,
  668. query: expect.stringContaining('trend_percentage():>0%'),
  669. interval: '1h',
  670. field: transactionFields,
  671. statsPeriod: '14d',
  672. }),
  673. })
  674. );
  675. }
  676. });
  677. it('Visiting trends with trends feature will update filters if none are set', async function () {
  678. const data = initializeTrendsData(undefined, {}, false);
  679. render(
  680. <TrendsIndex location={data.router.location} organization={data.organization} />,
  681. {
  682. router: data.router,
  683. organization: data.organization,
  684. }
  685. );
  686. await waitFor(() =>
  687. expect(browserHistory.push).toHaveBeenNthCalledWith(
  688. 1,
  689. expect.objectContaining({
  690. query: {
  691. query: `tpm():>0.01 transaction.duration:>0 transaction.duration:<${DEFAULT_MAX_DURATION}`,
  692. },
  693. })
  694. )
  695. );
  696. });
  697. it('Navigating away from trends will remove extra tags from query', async function () {
  698. const data = initializeTrendsData(
  699. undefined,
  700. {
  701. query: `device.family:Mac tpm():>0.01 transaction.duration:>0 transaction.duration:<${DEFAULT_MAX_DURATION}`,
  702. },
  703. false
  704. );
  705. render(
  706. <TrendsIndex location={data.router.location} organization={data.organization} />,
  707. {
  708. router: data.router,
  709. organization: data.organization,
  710. }
  711. );
  712. (browserHistory.push as any).mockReset();
  713. const byTransactionLink = await screen.findByTestId('breadcrumb-link');
  714. expect(byTransactionLink.closest('a')).toHaveAttribute(
  715. 'href',
  716. '/organizations/org-slug/performance/?query=device.family%3AMac'
  717. );
  718. });
  719. });