index.spec.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  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. const menuActions = within(firstTransaction).getAllByTestId('menu-action');
  378. expect(menuActions).toHaveLength(3);
  379. const menuAction = menuActions[2];
  380. await clickEl(menuAction);
  381. expect(browserHistory.push).toHaveBeenCalledWith({
  382. pathname: '/trends/',
  383. query: expect.objectContaining({
  384. project: expect.anything(),
  385. query: `tpm():>0.01 transaction.duration:>0 transaction.duration:<${DEFAULT_MAX_DURATION} !transaction:/organizations/:orgId/performance/`,
  386. }),
  387. });
  388. });
  389. it('Changing search causes cursors to be reset', async function () {
  390. const projects = [ProjectFixture({id: '1', slug: 'internal'}), ProjectFixture()];
  391. const data = initializeTrendsData(projects, {project: ['1']});
  392. render(
  393. <TrendsIndex location={data.router.location} organization={data.organization} />,
  394. {
  395. router: data.router,
  396. organization: data.organization,
  397. }
  398. );
  399. const input = await screen.findByTestId('smart-search-input');
  400. enterSearch(input, 'transaction.duration:>9000');
  401. await waitFor(() =>
  402. expect(browserHistory.push).toHaveBeenCalledWith({
  403. pathname: '/trends/',
  404. query: expect.objectContaining({
  405. project: ['1'],
  406. query: 'transaction.duration:>9000',
  407. improvedCursor: undefined,
  408. regressionCursor: undefined,
  409. }),
  410. })
  411. );
  412. });
  413. it('exclude greater than list menu action modifies query', async function () {
  414. const projects = [ProjectFixture({id: '1', slug: 'internal'}), ProjectFixture()];
  415. const data = initializeTrendsData(projects, {project: ['1']});
  416. render(
  417. <TrendsIndex location={data.router.location} organization={data.organization} />,
  418. {
  419. router: data.router,
  420. organization: data.organization,
  421. }
  422. );
  423. const transactions = await screen.findAllByTestId('trends-list-item-improved');
  424. expect(transactions).toHaveLength(2);
  425. const firstTransaction = transactions[0];
  426. const menuActions = within(firstTransaction).getAllByTestId('menu-action');
  427. expect(menuActions).toHaveLength(3);
  428. const menuAction = menuActions[0];
  429. await clickEl(menuAction);
  430. expect(browserHistory.push).toHaveBeenCalledWith({
  431. pathname: '/trends/',
  432. query: expect.objectContaining({
  433. project: expect.anything(),
  434. query: 'tpm():>0.01 transaction.duration:>0 transaction.duration:<=863',
  435. }),
  436. });
  437. });
  438. it('exclude less than list menu action modifies query', async function () {
  439. const projects = [ProjectFixture({id: '1', slug: 'internal'}), ProjectFixture()];
  440. const data = initializeTrendsData(projects, {project: ['1']});
  441. render(
  442. <TrendsIndex location={data.router.location} organization={data.organization} />,
  443. {
  444. router: data.router,
  445. organization: data.organization,
  446. }
  447. );
  448. const transactions = await screen.findAllByTestId('trends-list-item-improved');
  449. expect(transactions).toHaveLength(2);
  450. const firstTransaction = transactions[0];
  451. const menuActions = within(firstTransaction).getAllByTestId('menu-action');
  452. expect(menuActions).toHaveLength(3);
  453. const menuAction = menuActions[1];
  454. await clickEl(menuAction);
  455. expect(browserHistory.push).toHaveBeenCalledWith({
  456. pathname: '/trends/',
  457. query: expect.objectContaining({
  458. project: expect.anything(),
  459. query: 'tpm():>0.01 transaction.duration:<15min transaction.duration:>=863',
  460. }),
  461. });
  462. });
  463. it('choosing a trend function changes location', async function () {
  464. const projects = [ProjectFixture()];
  465. const data = initializeTrendsData(projects, {project: ['-1']});
  466. render(
  467. <TrendsIndex location={data.router.location} organization={data.organization} />,
  468. {
  469. router: data.router,
  470. organization: data.organization,
  471. }
  472. );
  473. for (const trendFunction of TRENDS_FUNCTIONS) {
  474. // Open dropdown
  475. const dropdown = await getTrendDropdown();
  476. await clickEl(dropdown);
  477. // Select function
  478. const option = screen.getByRole('option', {name: trendFunction.label});
  479. await clickEl(option);
  480. expect(browserHistory.push).toHaveBeenCalledWith({
  481. pathname: '/trends/',
  482. query: expect.objectContaining({
  483. regressionCursor: undefined,
  484. improvedCursor: undefined,
  485. trendFunction: trendFunction.field,
  486. }),
  487. });
  488. }
  489. });
  490. it('sets LCP as a default trend parameter for frontend project if query does not specify trend parameter', async function () {
  491. const projects = [ProjectFixture({id: '1', platform: 'javascript'})];
  492. const data = initializeTrendsData(projects, {project: [1]});
  493. render(
  494. <TrendsIndex location={data.router.location} organization={data.organization} />,
  495. {
  496. router: data.router,
  497. organization: data.organization,
  498. }
  499. );
  500. const trendDropdownButton = await getTrendDropdown();
  501. expect(trendDropdownButton).toHaveTextContent('Percentilep95');
  502. });
  503. it('sets duration as a default trend parameter for backend project if query does not specify trend parameter', async function () {
  504. const projects = [ProjectFixture({id: '1', platform: 'python'})];
  505. const data = initializeTrendsData(projects, {project: [1]});
  506. render(
  507. <TrendsIndex location={data.router.location} organization={data.organization} />,
  508. {
  509. router: data.router,
  510. organization: data.organization,
  511. }
  512. );
  513. const parameterDropdownButton = await getParameterDropdown();
  514. expect(parameterDropdownButton).toHaveTextContent('ParameterDuration');
  515. });
  516. it('sets trend parameter from query and ignores default trend parameter', async function () {
  517. const projects = [ProjectFixture({id: '1', platform: 'javascript'})];
  518. const data = initializeTrendsData(projects, {project: [1], trendParameter: 'FCP'});
  519. render(
  520. <TrendsIndex location={data.router.location} organization={data.organization} />,
  521. {
  522. router: data.router,
  523. organization: data.organization,
  524. }
  525. );
  526. const parameterDropdownButton = await getParameterDropdown();
  527. expect(parameterDropdownButton).toHaveTextContent('ParameterFCP');
  528. });
  529. it('choosing a parameter changes location', async function () {
  530. const projects = [ProjectFixture()];
  531. const data = initializeTrendsData(projects, {project: ['-1']});
  532. render(
  533. <TrendsIndex location={data.router.location} organization={data.organization} />,
  534. {
  535. router: data.router,
  536. organization: data.organization,
  537. }
  538. );
  539. for (const parameter of TRENDS_PARAMETERS) {
  540. // Open dropdown
  541. const dropdown = await getParameterDropdown();
  542. await clickEl(dropdown);
  543. // Select parameter
  544. const option = screen.getByRole('option', {name: parameter.label});
  545. await clickEl(option);
  546. expect(browserHistory.push).toHaveBeenCalledWith({
  547. pathname: '/trends/',
  548. query: expect.objectContaining({
  549. trendParameter: parameter.label,
  550. }),
  551. });
  552. }
  553. });
  554. it('choosing a web vitals parameter adds it as an additional condition to the query', async function () {
  555. const projects = [ProjectFixture()];
  556. const data = initializeTrendsData(projects, {project: ['-1']});
  557. const {rerender} = render(
  558. <TrendsIndex location={data.router.location} organization={data.organization} />,
  559. {
  560. router: data.router,
  561. organization: data.organization,
  562. }
  563. );
  564. for (const parameter of TRENDS_PARAMETERS) {
  565. if (Object.values(WebVital).includes(parameter.column as string as WebVital)) {
  566. trendsStatsMock.mockReset();
  567. const newLocation = {
  568. query: {...trendsViewQuery, trendParameter: parameter.label},
  569. };
  570. rerender(
  571. <TrendsIndex
  572. location={newLocation as unknown as Location}
  573. organization={data.organization}
  574. />
  575. );
  576. await waitForMockCall(trendsStatsMock);
  577. expect(trendsStatsMock).toHaveBeenCalledTimes(2);
  578. // Improved transactions call
  579. expect(trendsStatsMock).toHaveBeenNthCalledWith(
  580. 1,
  581. expect.anything(),
  582. expect.objectContaining({
  583. query: expect.objectContaining({
  584. query: expect.stringContaining(`has:${parameter.column}`),
  585. }),
  586. })
  587. );
  588. // Regression transactions call
  589. expect(trendsStatsMock).toHaveBeenNthCalledWith(
  590. 2,
  591. expect.anything(),
  592. expect.objectContaining({
  593. query: expect.objectContaining({
  594. query: expect.stringContaining(`has:${parameter.column}`),
  595. }),
  596. })
  597. );
  598. }
  599. }
  600. });
  601. it('trend functions in location make api calls', async function () {
  602. const projects = [ProjectFixture(), ProjectFixture()];
  603. const data = initializeTrendsData(projects, {project: ['-1']});
  604. const {rerender} = render(
  605. <TrendsIndex location={data.router.location} organization={data.organization} />,
  606. {
  607. router: data.router,
  608. organization: data.organization,
  609. }
  610. );
  611. for (const trendFunction of TRENDS_FUNCTIONS) {
  612. trendsStatsMock.mockReset();
  613. const newLocation = {
  614. query: {...trendsViewQuery, trendFunction: trendFunction.field},
  615. };
  616. rerender(
  617. <TrendsIndex
  618. location={newLocation as unknown as Location}
  619. organization={data.organization}
  620. />
  621. );
  622. await waitForMockCall(trendsStatsMock);
  623. expect(trendsStatsMock).toHaveBeenCalledTimes(2);
  624. const sort = 'trend_percentage()';
  625. const defaultTrendsFields = ['project'];
  626. const transactionFields = ['transaction', ...defaultTrendsFields];
  627. const projectFields = [...defaultTrendsFields];
  628. expect(transactionFields).toHaveLength(2);
  629. expect(projectFields).toHaveLength(transactionFields.length - 1);
  630. // Improved transactions call
  631. expect(trendsStatsMock).toHaveBeenNthCalledWith(
  632. 1,
  633. expect.anything(),
  634. expect.objectContaining({
  635. query: expect.objectContaining({
  636. trendFunction: `${trendFunction.field}(transaction.duration)`,
  637. sort,
  638. query: expect.stringContaining('trend_percentage():>0%'),
  639. interval: '1h',
  640. field: transactionFields,
  641. statsPeriod: '14d',
  642. }),
  643. })
  644. );
  645. // Regression transactions call
  646. expect(trendsStatsMock).toHaveBeenNthCalledWith(
  647. 2,
  648. expect.anything(),
  649. expect.objectContaining({
  650. query: expect.objectContaining({
  651. trendFunction: `${trendFunction.field}(transaction.duration)`,
  652. sort: '-' + sort,
  653. query: expect.stringContaining('trend_percentage():>0%'),
  654. interval: '1h',
  655. field: transactionFields,
  656. statsPeriod: '14d',
  657. }),
  658. })
  659. );
  660. }
  661. });
  662. it('Visiting trends with trends feature will update filters if none are set', async function () {
  663. const data = initializeTrendsData(undefined, {}, false);
  664. render(
  665. <TrendsIndex location={data.router.location} organization={data.organization} />,
  666. {
  667. router: data.router,
  668. organization: data.organization,
  669. }
  670. );
  671. await waitFor(() =>
  672. expect(browserHistory.push).toHaveBeenNthCalledWith(
  673. 1,
  674. expect.objectContaining({
  675. query: {
  676. query: `tpm():>0.01 transaction.duration:>0 transaction.duration:<${DEFAULT_MAX_DURATION}`,
  677. },
  678. })
  679. )
  680. );
  681. });
  682. it('Navigating away from trends will remove extra tags from query', async function () {
  683. const data = initializeTrendsData(
  684. undefined,
  685. {
  686. query: `device.family:Mac tpm():>0.01 transaction.duration:>0 transaction.duration:<${DEFAULT_MAX_DURATION}`,
  687. },
  688. false
  689. );
  690. render(
  691. <TrendsIndex location={data.router.location} organization={data.organization} />,
  692. {
  693. router: data.router,
  694. organization: data.organization,
  695. }
  696. );
  697. (browserHistory.push as any).mockReset();
  698. const byTransactionLink = await screen.findByTestId('breadcrumb-link');
  699. expect(byTransactionLink.closest('a')).toHaveAttribute(
  700. 'href',
  701. '/organizations/org-slug/performance/?query=device.family%3AMac'
  702. );
  703. });
  704. });