widgetBuilder.spec.tsx 117 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629
  1. import selectEvent from 'react-select-event';
  2. import {urlEncode} from '@sentry/utils';
  3. import {initializeOrg} from 'sentry-test/initializeOrg';
  4. import {mountGlobalModal} from 'sentry-test/modal';
  5. import {act, render, screen, userEvent, waitFor} from 'sentry-test/reactTestingLibrary';
  6. import * as indicators from 'sentry/actionCreators/indicator';
  7. import * as modals from 'sentry/actionCreators/modal';
  8. import TagStore from 'sentry/stores/tagStore';
  9. import {TOP_N} from 'sentry/utils/discover/types';
  10. import {
  11. DashboardDetails,
  12. DashboardWidgetSource,
  13. DisplayType,
  14. Widget,
  15. WidgetType,
  16. } from 'sentry/views/dashboardsV2/types';
  17. import WidgetBuilder, {WidgetBuilderProps} from 'sentry/views/dashboardsV2/widgetBuilder';
  18. const defaultOrgFeatures = [
  19. 'performance-view',
  20. 'new-widget-builder-experience-design',
  21. 'dashboards-edit',
  22. 'global-views',
  23. 'dashboard-custom-measurement-widgets',
  24. ];
  25. // Mocking worldMapChart to avoid act warnings
  26. jest.mock('sentry/components/charts/worldMapChart');
  27. function mockDashboard(dashboard: Partial<DashboardDetails>): DashboardDetails {
  28. return {
  29. id: '1',
  30. title: 'Dashboard',
  31. createdBy: undefined,
  32. dateCreated: '2020-01-01T00:00:00.000Z',
  33. widgets: [],
  34. projects: [],
  35. filters: {},
  36. ...dashboard,
  37. };
  38. }
  39. function renderTestComponent({
  40. dashboard,
  41. query,
  42. orgFeatures,
  43. onSave,
  44. params,
  45. }: {
  46. dashboard?: WidgetBuilderProps['dashboard'];
  47. onSave?: WidgetBuilderProps['onSave'];
  48. orgFeatures?: string[];
  49. params?: Partial<WidgetBuilderProps['params']>;
  50. query?: Record<string, any>;
  51. } = {}) {
  52. const {organization, router, routerContext} = initializeOrg({
  53. ...initializeOrg(),
  54. organization: {
  55. features: orgFeatures ?? defaultOrgFeatures,
  56. },
  57. router: {
  58. location: {
  59. query: {
  60. source: DashboardWidgetSource.DASHBOARDS,
  61. ...query,
  62. },
  63. },
  64. },
  65. });
  66. render(
  67. <WidgetBuilder
  68. route={{}}
  69. router={router}
  70. routes={router.routes}
  71. routeParams={router.params}
  72. location={router.location}
  73. dashboard={{
  74. id: 'new',
  75. title: 'Dashboard',
  76. createdBy: undefined,
  77. dateCreated: '2020-01-01T00:00:00.000Z',
  78. widgets: [],
  79. projects: [],
  80. filters: {},
  81. ...dashboard,
  82. }}
  83. onSave={onSave ?? jest.fn()}
  84. params={{
  85. orgId: organization.slug,
  86. dashboardId: dashboard?.id ?? 'new',
  87. ...params,
  88. }}
  89. />,
  90. {
  91. context: routerContext,
  92. organization,
  93. }
  94. );
  95. return {router};
  96. }
  97. describe('WidgetBuilder', function () {
  98. const untitledDashboard: DashboardDetails = {
  99. id: '1',
  100. title: 'Untitled Dashboard',
  101. createdBy: undefined,
  102. dateCreated: '2020-01-01T00:00:00.000Z',
  103. widgets: [],
  104. projects: [],
  105. filters: {},
  106. };
  107. const testDashboard: DashboardDetails = {
  108. id: '2',
  109. title: 'Test Dashboard',
  110. createdBy: undefined,
  111. dateCreated: '2020-01-01T00:00:00.000Z',
  112. widgets: [],
  113. projects: [],
  114. filters: {},
  115. };
  116. let eventsStatsMock: jest.Mock | undefined;
  117. let eventsv2Mock: jest.Mock | undefined;
  118. let eventsMock: jest.Mock | undefined;
  119. let sessionsDataMock: jest.Mock | undefined;
  120. let metricsDataMock: jest.Mock | undefined;
  121. let tagsMock: jest.Mock | undefined;
  122. let measurementsMetaMock: jest.Mock | undefined;
  123. beforeEach(function () {
  124. MockApiClient.addMockResponse({
  125. url: '/organizations/org-slug/dashboards/',
  126. body: [
  127. {...untitledDashboard, widgetDisplay: [DisplayType.TABLE]},
  128. {...testDashboard, widgetDisplay: [DisplayType.AREA]},
  129. ],
  130. });
  131. MockApiClient.addMockResponse({
  132. url: '/organizations/org-slug/dashboards/widgets/',
  133. method: 'POST',
  134. statusCode: 200,
  135. body: [],
  136. });
  137. eventsv2Mock = MockApiClient.addMockResponse({
  138. url: '/organizations/org-slug/eventsv2/',
  139. method: 'GET',
  140. statusCode: 200,
  141. body: {
  142. meta: {},
  143. data: [],
  144. },
  145. });
  146. eventsMock = MockApiClient.addMockResponse({
  147. url: '/organizations/org-slug/events/',
  148. method: 'GET',
  149. statusCode: 200,
  150. body: {
  151. meta: {fields: {}},
  152. data: [],
  153. },
  154. });
  155. MockApiClient.addMockResponse({
  156. url: '/organizations/org-slug/projects/',
  157. method: 'GET',
  158. body: [],
  159. });
  160. MockApiClient.addMockResponse({
  161. url: '/organizations/org-slug/recent-searches/',
  162. method: 'GET',
  163. body: [],
  164. });
  165. MockApiClient.addMockResponse({
  166. url: '/organizations/org-slug/recent-searches/',
  167. method: 'POST',
  168. body: [],
  169. });
  170. MockApiClient.addMockResponse({
  171. url: '/organizations/org-slug/issues/',
  172. method: 'GET',
  173. body: [],
  174. });
  175. eventsStatsMock = MockApiClient.addMockResponse({
  176. url: '/organizations/org-slug/events-stats/',
  177. body: [],
  178. });
  179. MockApiClient.addMockResponse({
  180. url: '/organizations/org-slug/tags/event.type/values/',
  181. body: [{count: 2, name: 'Nvidia 1080ti'}],
  182. });
  183. MockApiClient.addMockResponse({
  184. url: '/organizations/org-slug/events-geo/',
  185. body: {data: [], meta: {}},
  186. });
  187. MockApiClient.addMockResponse({
  188. url: '/organizations/org-slug/users/',
  189. body: [],
  190. });
  191. sessionsDataMock = MockApiClient.addMockResponse({
  192. method: 'GET',
  193. url: '/organizations/org-slug/sessions/',
  194. body: TestStubs.SessionsField({
  195. field: `sum(session)`,
  196. }),
  197. });
  198. metricsDataMock = MockApiClient.addMockResponse({
  199. method: 'GET',
  200. url: '/organizations/org-slug/metrics/data/',
  201. body: TestStubs.MetricsField({
  202. field: 'sum(sentry.sessions.session)',
  203. }),
  204. });
  205. tagsMock = MockApiClient.addMockResponse({
  206. url: '/organizations/org-slug/tags/',
  207. method: 'GET',
  208. body: TestStubs.Tags(),
  209. });
  210. measurementsMetaMock = MockApiClient.addMockResponse({
  211. url: '/organizations/org-slug/measurements-meta/',
  212. method: 'GET',
  213. body: {},
  214. });
  215. TagStore.reset();
  216. });
  217. afterEach(function () {
  218. MockApiClient.clearMockResponses();
  219. jest.clearAllMocks();
  220. jest.useRealTimers();
  221. });
  222. describe('with eventsv2', function () {
  223. it('no feature access', function () {
  224. renderTestComponent({orgFeatures: []});
  225. expect(
  226. screen.getByText("You don't have access to this feature")
  227. ).toBeInTheDocument();
  228. });
  229. it('widget not found', function () {
  230. const widget: Widget = {
  231. displayType: DisplayType.AREA,
  232. interval: '1d',
  233. queries: [
  234. {
  235. name: 'Known Users',
  236. fields: [],
  237. columns: [],
  238. aggregates: [],
  239. conditions: '',
  240. orderby: '-time',
  241. },
  242. {
  243. name: 'Anonymous Users',
  244. fields: [],
  245. columns: [],
  246. aggregates: [],
  247. conditions: '',
  248. orderby: '-time',
  249. },
  250. ],
  251. title: 'Transactions',
  252. id: '1',
  253. };
  254. const dashboard = mockDashboard({widgets: [widget]});
  255. renderTestComponent({
  256. dashboard,
  257. orgFeatures: ['new-widget-builder-experience-design', 'dashboards-edit'],
  258. params: {
  259. widgetIndex: '2', // Out of bounds, only one widget
  260. },
  261. });
  262. expect(
  263. screen.getByText('The widget you want to edit was not found.')
  264. ).toBeInTheDocument();
  265. });
  266. it('renders a widget not found message if the widget index url is not an integer', function () {
  267. const widget: Widget = {
  268. displayType: DisplayType.AREA,
  269. interval: '1d',
  270. queries: [
  271. {
  272. name: 'Known Users',
  273. fields: [],
  274. columns: [],
  275. aggregates: [],
  276. conditions: '',
  277. orderby: '-time',
  278. },
  279. ],
  280. title: 'Transactions',
  281. id: '1',
  282. };
  283. const dashboard = mockDashboard({widgets: [widget]});
  284. renderTestComponent({
  285. dashboard,
  286. orgFeatures: ['new-widget-builder-experience-design', 'dashboards-edit'],
  287. params: {
  288. widgetIndex: '0.5', // Invalid index
  289. },
  290. });
  291. expect(
  292. screen.getByText('The widget you want to edit was not found.')
  293. ).toBeInTheDocument();
  294. });
  295. it('renders', async function () {
  296. renderTestComponent();
  297. // Header - Breadcrumbs
  298. expect(await screen.findByRole('link', {name: 'Dashboards'})).toHaveAttribute(
  299. 'href',
  300. '/organizations/org-slug/dashboards/'
  301. );
  302. expect(screen.getByRole('link', {name: 'Dashboard'})).toHaveAttribute(
  303. 'href',
  304. '/organizations/org-slug/dashboards/new/'
  305. );
  306. expect(screen.getByText('Widget Builder')).toBeInTheDocument();
  307. // Header - Widget Title
  308. expect(screen.getByRole('heading', {name: 'Custom Widget'})).toBeInTheDocument();
  309. // Footer - Actions
  310. expect(screen.getByLabelText('Cancel')).toBeInTheDocument();
  311. expect(screen.getByLabelText('Add Widget')).toBeInTheDocument();
  312. // Content - Step 1
  313. expect(
  314. screen.getByRole('heading', {name: 'Choose your dataset'})
  315. ).toBeInTheDocument();
  316. expect(screen.getByLabelText('Select Errors and Transactions')).toBeChecked();
  317. // Content - Step 2
  318. expect(
  319. screen.getByRole('heading', {name: 'Choose your visualization'})
  320. ).toBeInTheDocument();
  321. // Content - Step 3
  322. expect(
  323. screen.getByRole('heading', {name: 'Choose your columns'})
  324. ).toBeInTheDocument();
  325. // Content - Step 4
  326. expect(
  327. screen.getByRole('heading', {name: 'Filter your results'})
  328. ).toBeInTheDocument();
  329. // Content - Step 5
  330. expect(screen.getByRole('heading', {name: 'Sort by a column'})).toBeInTheDocument();
  331. });
  332. it('has links back to the new dashboard if creating', async function () {
  333. // Dashboard has undefined dashboardId when creating from a new dashboard
  334. // because of route setup
  335. renderTestComponent({params: {dashboardId: undefined}});
  336. expect(await screen.findByRole('link', {name: 'Dashboard'})).toHaveAttribute(
  337. 'href',
  338. '/organizations/org-slug/dashboards/new/'
  339. );
  340. expect(screen.getByLabelText('Cancel')).toHaveAttribute(
  341. 'href',
  342. '/organizations/org-slug/dashboards/new/'
  343. );
  344. });
  345. it('renders new design', async function () {
  346. renderTestComponent({
  347. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  348. });
  349. // Switch to line chart for time series
  350. userEvent.click(await screen.findByText('Table'));
  351. userEvent.click(screen.getByText('Line Chart'));
  352. // Header - Breadcrumbs
  353. expect(await screen.findByRole('link', {name: 'Dashboards'})).toHaveAttribute(
  354. 'href',
  355. '/organizations/org-slug/dashboards/'
  356. );
  357. expect(screen.getByRole('link', {name: 'Dashboard'})).toHaveAttribute(
  358. 'href',
  359. '/organizations/org-slug/dashboards/new/'
  360. );
  361. expect(screen.getByText('Widget Builder')).toBeInTheDocument();
  362. // Header - Widget Title
  363. expect(screen.getByRole('heading', {name: 'Custom Widget'})).toBeInTheDocument();
  364. // Footer - Actions
  365. expect(screen.getByLabelText('Cancel')).toBeInTheDocument();
  366. expect(screen.getByLabelText('Add Widget')).toBeInTheDocument();
  367. // Content - Step 1
  368. expect(
  369. screen.getByRole('heading', {name: 'Choose your dataset'})
  370. ).toBeInTheDocument();
  371. expect(screen.getByLabelText('Select Errors and Transactions')).toBeChecked();
  372. // Content - Step 2
  373. expect(
  374. screen.getByRole('heading', {name: 'Choose your visualization'})
  375. ).toBeInTheDocument();
  376. // Content - Step 3
  377. expect(
  378. screen.getByRole('heading', {name: 'Choose what to plot in the y-axis'})
  379. ).toBeInTheDocument();
  380. // Content - Step 4
  381. expect(
  382. screen.getByRole('heading', {name: 'Filter your results'})
  383. ).toBeInTheDocument();
  384. // Content - Step 5
  385. expect(
  386. screen.getByRole('heading', {name: 'Group your results'})
  387. ).toBeInTheDocument();
  388. });
  389. it('can update the title', async function () {
  390. renderTestComponent({
  391. query: {source: DashboardWidgetSource.DISCOVERV2},
  392. });
  393. const customWidgetLabels = await screen.findAllByText('Custom Widget');
  394. // EditableText and chart title
  395. expect(customWidgetLabels).toHaveLength(2);
  396. userEvent.click(customWidgetLabels[0]);
  397. userEvent.clear(screen.getByRole('textbox', {name: 'Widget title'}));
  398. userEvent.paste(
  399. screen.getByRole('textbox', {name: 'Widget title'}),
  400. 'Unique Users'
  401. );
  402. userEvent.keyboard('{enter}');
  403. expect(screen.queryByText('Custom Widget')).not.toBeInTheDocument();
  404. expect(screen.getAllByText('Unique Users')).toHaveLength(2);
  405. });
  406. it('can add query conditions', async function () {
  407. const {router} = renderTestComponent({
  408. query: {source: DashboardWidgetSource.DISCOVERV2},
  409. dashboard: testDashboard,
  410. });
  411. userEvent.type(
  412. await screen.findByRole('textbox', {name: 'Search events'}),
  413. 'color:blue{enter}'
  414. );
  415. userEvent.click(screen.getByText('Add Widget'));
  416. await waitFor(() => {
  417. expect(router.push).toHaveBeenCalledWith(
  418. expect.objectContaining({
  419. pathname: '/organizations/org-slug/dashboard/2/',
  420. query: {
  421. displayType: 'table',
  422. interval: '5m',
  423. title: 'Custom Widget',
  424. queryNames: [''],
  425. queryConditions: ['color:blue'],
  426. queryFields: ['count()'],
  427. queryOrderby: '-count()',
  428. start: null,
  429. end: null,
  430. statsPeriod: '24h',
  431. utc: false,
  432. project: [],
  433. environment: [],
  434. },
  435. })
  436. );
  437. });
  438. });
  439. it('can choose a field', async function () {
  440. const {router} = renderTestComponent({
  441. query: {source: DashboardWidgetSource.DISCOVERV2},
  442. dashboard: testDashboard,
  443. });
  444. expect(await screen.findAllByText('Custom Widget')).toHaveLength(2);
  445. // No delete button as there is only one query.
  446. expect(screen.queryByLabelText('Remove query')).not.toBeInTheDocument();
  447. // 1 in the table header, 1 in the column selector, 1 in the sort field
  448. const countFields = screen.getAllByText('count()');
  449. expect(countFields).toHaveLength(3);
  450. await selectEvent.select(countFields[1], ['last_seen()']);
  451. userEvent.click(screen.getByText('Add Widget'));
  452. await waitFor(() => {
  453. expect(router.push).toHaveBeenCalledWith(
  454. expect.objectContaining({
  455. pathname: '/organizations/org-slug/dashboard/2/',
  456. query: {
  457. displayType: 'table',
  458. interval: '5m',
  459. title: 'Custom Widget',
  460. queryNames: [''],
  461. queryConditions: [''],
  462. queryFields: ['last_seen()'],
  463. queryOrderby: '-last_seen()',
  464. start: null,
  465. end: null,
  466. statsPeriod: '24h',
  467. utc: false,
  468. project: [],
  469. environment: [],
  470. },
  471. })
  472. );
  473. });
  474. });
  475. it('can add additional fields', async function () {
  476. const handleSave = jest.fn();
  477. renderTestComponent({onSave: handleSave});
  478. userEvent.click(await screen.findByText('Table'));
  479. // Select line chart display
  480. userEvent.click(screen.getByText('Line Chart'));
  481. // Click the add overlay button
  482. userEvent.click(screen.getByLabelText('Add Overlay'));
  483. await selectEvent.select(screen.getByText('(Required)'), ['count_unique(…)']);
  484. userEvent.click(screen.getByLabelText('Add Widget'));
  485. await waitFor(() => {
  486. expect(handleSave).toHaveBeenCalledWith([
  487. expect.objectContaining({
  488. title: 'Custom Widget',
  489. displayType: DisplayType.LINE,
  490. interval: '5m',
  491. widgetType: WidgetType.DISCOVER,
  492. queries: [
  493. {
  494. conditions: '',
  495. fields: ['count()', 'count_unique(user)'],
  496. aggregates: ['count()', 'count_unique(user)'],
  497. fieldAliases: [],
  498. columns: [],
  499. orderby: '',
  500. name: '',
  501. },
  502. ],
  503. }),
  504. ]);
  505. });
  506. expect(handleSave).toHaveBeenCalledTimes(1);
  507. });
  508. it('can add equation fields', async function () {
  509. const handleSave = jest.fn();
  510. renderTestComponent({onSave: handleSave});
  511. userEvent.click(await screen.findByText('Table'));
  512. // Select line chart display
  513. userEvent.click(screen.getByText('Line Chart'));
  514. // Click the add an equation button
  515. userEvent.click(screen.getByLabelText('Add an Equation'));
  516. expect(screen.getByPlaceholderText('Equation')).toBeInTheDocument();
  517. userEvent.paste(screen.getByPlaceholderText('Equation'), 'count() + 100');
  518. userEvent.click(screen.getByLabelText('Add Widget'));
  519. await waitFor(() => {
  520. expect(handleSave).toHaveBeenCalledWith([
  521. expect.objectContaining({
  522. title: 'Custom Widget',
  523. displayType: DisplayType.LINE,
  524. interval: '5m',
  525. widgetType: WidgetType.DISCOVER,
  526. queries: [
  527. {
  528. name: '',
  529. fields: ['count()', 'equation|count() + 100'],
  530. aggregates: ['count()', 'equation|count() + 100'],
  531. columns: [],
  532. fieldAliases: [],
  533. conditions: '',
  534. orderby: '',
  535. },
  536. ],
  537. }),
  538. ]);
  539. });
  540. expect(handleSave).toHaveBeenCalledTimes(1);
  541. });
  542. it('can respond to validation feedback', async function () {
  543. jest.spyOn(indicators, 'addErrorMessage');
  544. renderTestComponent();
  545. userEvent.click(await screen.findByText('Table'));
  546. const customWidgetLabels = await screen.findAllByText('Custom Widget');
  547. // EditableText and chart title
  548. expect(customWidgetLabels).toHaveLength(2);
  549. userEvent.click(customWidgetLabels[0]);
  550. userEvent.clear(screen.getByRole('textbox', {name: 'Widget title'}));
  551. userEvent.keyboard('{enter}');
  552. expect(indicators.addErrorMessage).toHaveBeenCalledWith('Widget title is required');
  553. });
  554. it('sets up widget data in edit correctly', async function () {
  555. const widget: Widget = {
  556. id: '1',
  557. title: 'Errors over time',
  558. interval: '5m',
  559. displayType: DisplayType.LINE,
  560. queries: [
  561. {
  562. name: 'errors',
  563. conditions: 'event.type:error',
  564. fields: ['count()', 'count_unique(id)'],
  565. aggregates: ['count()', 'count_unique(id)'],
  566. columns: [],
  567. orderby: '',
  568. },
  569. {
  570. name: 'csp',
  571. conditions: 'event.type:csp',
  572. fields: ['count()', 'count_unique(id)'],
  573. aggregates: ['count()', 'count_unique(id)'],
  574. columns: [],
  575. orderby: '',
  576. },
  577. ],
  578. };
  579. const dashboard = mockDashboard({widgets: [widget]});
  580. renderTestComponent({dashboard, params: {widgetIndex: '0'}});
  581. await screen.findByText('Line Chart');
  582. // Should be in edit 'mode'
  583. expect(await screen.findByText('Update Widget')).toBeInTheDocument();
  584. // Should set widget data up.
  585. expect(screen.getByText('Update Widget')).toBeInTheDocument();
  586. // Filters
  587. expect(
  588. screen.getAllByPlaceholderText('Search for events, users, tags, and more')
  589. ).toHaveLength(2);
  590. expect(screen.getByText('event.type:csp')).toBeInTheDocument();
  591. expect(screen.getByText('event.type:error')).toBeInTheDocument();
  592. // Y-axis
  593. expect(screen.getAllByRole('button', {name: 'Remove query'})).toHaveLength(2);
  594. expect(screen.getByText('count()')).toBeInTheDocument();
  595. expect(screen.getByText('count_unique(…)')).toBeInTheDocument();
  596. expect(screen.getByText('id')).toBeInTheDocument();
  597. // Expect events-stats endpoint to be called for each search conditions with
  598. // the same y-axis parameters
  599. expect(eventsStatsMock).toHaveBeenNthCalledWith(
  600. 1,
  601. '/organizations/org-slug/events-stats/',
  602. expect.objectContaining({
  603. query: expect.objectContaining({
  604. query: 'event.type:error',
  605. yAxis: ['count()', 'count_unique(id)'],
  606. }),
  607. })
  608. );
  609. expect(eventsStatsMock).toHaveBeenNthCalledWith(
  610. 2,
  611. '/organizations/org-slug/events-stats/',
  612. expect.objectContaining({
  613. query: expect.objectContaining({
  614. query: 'event.type:csp',
  615. yAxis: ['count()', 'count_unique(id)'],
  616. }),
  617. })
  618. );
  619. });
  620. it('can edit a widget', async function () {
  621. const widget: Widget = {
  622. id: '1',
  623. title: 'Errors over time',
  624. interval: '5m',
  625. displayType: DisplayType.LINE,
  626. queries: [
  627. {
  628. name: 'errors',
  629. conditions: 'event.type:error',
  630. fields: ['count()', 'count_unique(id)'],
  631. aggregates: ['count()', 'count_unique(id)'],
  632. columns: [],
  633. orderby: '',
  634. },
  635. {
  636. name: 'csp',
  637. conditions: 'event.type:csp',
  638. fields: ['count()', 'count_unique(id)'],
  639. aggregates: ['count()', 'count_unique(id)'],
  640. columns: [],
  641. orderby: '',
  642. },
  643. ],
  644. };
  645. const dashboard = mockDashboard({widgets: [widget]});
  646. const handleSave = jest.fn();
  647. renderTestComponent({onSave: handleSave, dashboard, params: {widgetIndex: '0'}});
  648. await screen.findByText('Line Chart');
  649. // Should be in edit 'mode'
  650. expect(await screen.findByText('Update Widget')).toBeInTheDocument();
  651. const customWidgetLabels = await screen.findAllByText(widget.title);
  652. // EditableText and chart title
  653. expect(customWidgetLabels).toHaveLength(2);
  654. userEvent.click(customWidgetLabels[0]);
  655. userEvent.clear(screen.getByRole('textbox', {name: 'Widget title'}));
  656. userEvent.paste(screen.getByRole('textbox', {name: 'Widget title'}), 'New Title');
  657. userEvent.click(screen.getByRole('button', {name: 'Update Widget'}));
  658. await waitFor(() => {
  659. expect(handleSave).toHaveBeenCalledWith([
  660. expect.objectContaining({
  661. ...widget,
  662. title: 'New Title',
  663. }),
  664. ]);
  665. });
  666. expect(handleSave).toHaveBeenCalledTimes(1);
  667. });
  668. it('renders column inputs for table widgets', async function () {
  669. const widget: Widget = {
  670. id: '0',
  671. title: 'sdk usage',
  672. interval: '5m',
  673. displayType: DisplayType.TABLE,
  674. queries: [
  675. {
  676. name: 'errors',
  677. conditions: 'event.type:error',
  678. fields: ['sdk.name', 'count()'],
  679. columns: ['sdk.name'],
  680. aggregates: ['count()'],
  681. orderby: '',
  682. },
  683. ],
  684. };
  685. const dashboard = mockDashboard({widgets: [widget]});
  686. renderTestComponent({dashboard, params: {widgetIndex: '0'}});
  687. // Should be in edit 'mode'
  688. expect(await screen.findByText('Update Widget')).toBeInTheDocument();
  689. // Should set widget data up.
  690. expect(screen.getByRole('heading', {name: widget.title})).toBeInTheDocument();
  691. expect(screen.getByText('Table')).toBeInTheDocument();
  692. expect(screen.getByLabelText('Search events')).toBeInTheDocument();
  693. // Should have an orderby select
  694. expect(screen.getByText('Sort by a column')).toBeInTheDocument();
  695. // Add a column, and choose a value,
  696. expect(screen.getByLabelText('Add a Column')).toBeInTheDocument();
  697. });
  698. it('can save table widgets', async function () {
  699. const widget: Widget = {
  700. id: '0',
  701. title: 'sdk usage',
  702. interval: '5m',
  703. displayType: DisplayType.TABLE,
  704. queries: [
  705. {
  706. name: 'errors',
  707. conditions: 'event.type:error',
  708. fields: ['sdk.name', 'count()'],
  709. columns: ['sdk.name'],
  710. aggregates: ['count()'],
  711. orderby: '-count()',
  712. },
  713. ],
  714. };
  715. const dashboard = mockDashboard({widgets: [widget]});
  716. const handleSave = jest.fn();
  717. renderTestComponent({dashboard, onSave: handleSave, params: {widgetIndex: '0'}});
  718. // Should be in edit 'mode'
  719. expect(await screen.findByText('Update Widget')).toBeInTheDocument();
  720. // Add a column, and choose a value,
  721. userEvent.click(screen.getByLabelText('Add a Column'));
  722. await selectEvent.select(screen.getByText('(Required)'), 'trace');
  723. // Save widget
  724. userEvent.click(screen.getByLabelText('Update Widget'));
  725. await waitFor(() => {
  726. expect(handleSave).toHaveBeenCalledWith([
  727. expect.objectContaining({
  728. id: '0',
  729. title: 'sdk usage',
  730. displayType: DisplayType.TABLE,
  731. interval: '5m',
  732. queries: [
  733. {
  734. name: 'errors',
  735. conditions: 'event.type:error',
  736. fields: ['sdk.name', 'count()', 'trace'],
  737. aggregates: ['count()'],
  738. columns: ['sdk.name', 'trace'],
  739. orderby: '-count()',
  740. fieldAliases: ['', '', ''],
  741. },
  742. ],
  743. widgetType: WidgetType.DISCOVER,
  744. }),
  745. ]);
  746. });
  747. expect(handleSave).toHaveBeenCalledTimes(1);
  748. });
  749. it('should properly query for table fields', async function () {
  750. const defaultWidgetQuery = {
  751. name: '',
  752. fields: ['title', 'count()'],
  753. columns: ['title'],
  754. aggregates: ['count()'],
  755. conditions: '',
  756. orderby: '',
  757. };
  758. const defaultTableColumns = ['title', 'count()', 'count_unique(user)', 'epm()'];
  759. renderTestComponent({
  760. query: {
  761. source: DashboardWidgetSource.DISCOVERV2,
  762. defaultWidgetQuery: urlEncode(defaultWidgetQuery),
  763. displayType: DisplayType.LINE,
  764. defaultTableColumns,
  765. },
  766. });
  767. expect(await screen.findByText('Line Chart')).toBeInTheDocument();
  768. userEvent.click(screen.getByText('Line Chart'));
  769. userEvent.click(screen.getByText('Table'));
  770. await waitFor(() => {
  771. expect(eventsv2Mock).toHaveBeenLastCalledWith(
  772. '/organizations/org-slug/eventsv2/',
  773. expect.objectContaining({
  774. query: expect.objectContaining({
  775. field: defaultTableColumns,
  776. }),
  777. })
  778. );
  779. });
  780. });
  781. it('should use defaultWidgetQuery Y-Axis and Conditions if given a defaultWidgetQuery', async function () {
  782. const defaultWidgetQuery = {
  783. name: '',
  784. fields: ['count()', 'failure_count()', 'count_unique(user)'],
  785. columns: [],
  786. aggregates: ['count()', 'failure_count()', 'count_unique(user)'],
  787. conditions: 'tag:value',
  788. orderby: '',
  789. };
  790. renderTestComponent({
  791. query: {
  792. source: DashboardWidgetSource.DISCOVERV2,
  793. defaultWidgetQuery: urlEncode(defaultWidgetQuery),
  794. },
  795. });
  796. expect(await screen.findByText('tag:value')).toBeInTheDocument();
  797. // Table display, column, and sort field
  798. expect(screen.getAllByText('count()')).toHaveLength(3);
  799. // Table display and column
  800. expect(screen.getAllByText('failure_count()')).toHaveLength(2);
  801. // Table display
  802. expect(screen.getByText('count_unique(user)')).toBeInTheDocument();
  803. // Column
  804. expect(screen.getByText('count_unique(…)')).toBeInTheDocument();
  805. // Column
  806. expect(screen.getByText('user')).toBeInTheDocument();
  807. });
  808. it('uses displayType if given a displayType', async function () {
  809. renderTestComponent({
  810. query: {
  811. displayType: DisplayType.BAR,
  812. },
  813. });
  814. expect(await screen.findByText('Bar Chart')).toBeInTheDocument();
  815. });
  816. it('deletes the widget when the modal is confirmed', async () => {
  817. const handleSave = jest.fn();
  818. const widget: Widget = {
  819. id: '1',
  820. title: 'Errors over time',
  821. interval: '5m',
  822. displayType: DisplayType.LINE,
  823. queries: [
  824. {
  825. name: 'errors',
  826. conditions: 'event.type:error',
  827. fields: ['count()', 'count_unique(id)'],
  828. aggregates: ['count()', 'count_unique(id)'],
  829. columns: [],
  830. orderby: '',
  831. },
  832. {
  833. name: 'csp',
  834. conditions: 'event.type:csp',
  835. fields: ['count()', 'count_unique(id)'],
  836. aggregates: ['count()', 'count_unique(id)'],
  837. columns: [],
  838. orderby: '',
  839. },
  840. ],
  841. };
  842. const dashboard = mockDashboard({widgets: [widget]});
  843. renderTestComponent({onSave: handleSave, dashboard, params: {widgetIndex: '0'}});
  844. userEvent.click(await screen.findByText('Delete'));
  845. await mountGlobalModal();
  846. userEvent.click(await screen.findByText('Confirm'));
  847. await waitFor(() => {
  848. // The only widget was deleted
  849. expect(handleSave).toHaveBeenCalledWith([]);
  850. });
  851. expect(handleSave).toHaveBeenCalledTimes(1);
  852. });
  853. it('persists the page filter period when updating a widget', async () => {
  854. const widget: Widget = {
  855. id: '1',
  856. title: 'Errors over time',
  857. interval: '5m',
  858. displayType: DisplayType.LINE,
  859. queries: [
  860. {
  861. name: 'errors',
  862. conditions: 'event.type:error',
  863. fields: ['count()', 'count_unique(id)'],
  864. aggregates: ['count()', 'count_unique(id)'],
  865. columns: [],
  866. orderby: '',
  867. },
  868. ],
  869. };
  870. const dashboard = mockDashboard({widgets: [widget]});
  871. const {router} = renderTestComponent({
  872. dashboard,
  873. params: {orgId: 'org-slug', widgetIndex: '0'},
  874. query: {statsPeriod: '90d'},
  875. });
  876. await screen.findByText('Update Widget');
  877. await screen.findByText('90D');
  878. expect(screen.getByTestId('page-filter-timerange-selector')).toBeEnabled();
  879. userEvent.click(screen.getByText('Update Widget'));
  880. await waitFor(() => {
  881. expect(router.push).toHaveBeenLastCalledWith(
  882. expect.objectContaining({
  883. pathname: '/organizations/org-slug/dashboard/1/',
  884. query: expect.objectContaining({
  885. statsPeriod: '90d',
  886. }),
  887. })
  888. );
  889. });
  890. });
  891. it('renders page filters in the filter step', async () => {
  892. const mockReleases = MockApiClient.addMockResponse({
  893. url: '/organizations/org-slug/releases/',
  894. body: [TestStubs.Release()],
  895. });
  896. renderTestComponent({
  897. params: {orgId: 'org-slug'},
  898. query: {statsPeriod: '90d'},
  899. orgFeatures: [...defaultOrgFeatures, 'dashboards-top-level-filter'],
  900. });
  901. await screen.findByText('90D');
  902. expect(screen.getByTestId('page-filter-timerange-selector')).toBeDisabled();
  903. expect(screen.getByTestId('page-filter-environment-selector')).toBeDisabled();
  904. expect(screen.getByTestId('page-filter-project-selector-loading')).toBeDisabled();
  905. await waitFor(() => {
  906. expect(mockReleases).toHaveBeenCalled();
  907. });
  908. expect(screen.getByRole('button', {name: /all releases/i})).toBeDisabled();
  909. });
  910. it('appends dashboard filters to widget builder fetch data request', async () => {
  911. MockApiClient.addMockResponse({
  912. url: '/organizations/org-slug/releases/',
  913. body: [TestStubs.Release()],
  914. });
  915. const mock = MockApiClient.addMockResponse({
  916. url: '/organizations/org-slug/eventsv2/',
  917. body: [],
  918. });
  919. renderTestComponent({
  920. dashboard: {
  921. id: 'new',
  922. title: 'Dashboard',
  923. createdBy: undefined,
  924. dateCreated: '2020-01-01T00:00:00.000Z',
  925. widgets: [],
  926. projects: [],
  927. filters: {release: ['abc@1.2.0']},
  928. },
  929. params: {orgId: 'org-slug'},
  930. query: {statsPeriod: '90d'},
  931. orgFeatures: [...defaultOrgFeatures, 'dashboards-top-level-filter'],
  932. });
  933. await waitFor(() => {
  934. expect(mock).toHaveBeenCalledWith(
  935. '/organizations/org-slug/eventsv2/',
  936. expect.objectContaining({
  937. query: expect.objectContaining({
  938. query: ' release:abc@1.2.0 ',
  939. }),
  940. })
  941. );
  942. });
  943. });
  944. it('does not error when query conditions field is blurred', async function () {
  945. jest.useFakeTimers();
  946. const widget: Widget = {
  947. id: '0',
  948. title: 'sdk usage',
  949. interval: '5m',
  950. displayType: DisplayType.BAR,
  951. queries: [
  952. {
  953. name: 'filled in',
  954. conditions: 'event.type:error',
  955. fields: ['count()', 'count_unique(id)'],
  956. aggregates: ['count()', 'count_unique(id)'],
  957. columns: [],
  958. orderby: '-count()',
  959. },
  960. ],
  961. };
  962. const dashboard = mockDashboard({widgets: [widget]});
  963. const handleSave = jest.fn();
  964. renderTestComponent({dashboard, onSave: handleSave, params: {widgetIndex: '0'}});
  965. userEvent.click(await screen.findByLabelText('Add Query'));
  966. // Triggering the onBlur of the new field should not error
  967. userEvent.click(
  968. screen.getAllByPlaceholderText('Search for events, users, tags, and more')[1]
  969. );
  970. userEvent.keyboard('{esc}');
  971. act(() => {
  972. // Run all timers because the handleBlur contains a setTimeout
  973. jest.runAllTimers();
  974. });
  975. });
  976. it('does not wipe column changes when filters are modified', async function () {
  977. jest.useFakeTimers();
  978. // widgetIndex: undefined means creating a new widget
  979. renderTestComponent({params: {widgetIndex: undefined}});
  980. userEvent.click(await screen.findByLabelText('Add a Column'));
  981. await selectEvent.select(screen.getByText('(Required)'), /project/);
  982. // Triggering the onBlur of the filter should not error
  983. userEvent.click(
  984. screen.getByPlaceholderText('Search for events, users, tags, and more')
  985. );
  986. userEvent.keyboard('{enter}');
  987. act(() => {
  988. // Run all timers because the handleBlur contains a setTimeout
  989. jest.runAllTimers();
  990. });
  991. expect(await screen.findAllByText('project')).toHaveLength(2);
  992. });
  993. it('renders fields with commas properly', async () => {
  994. const defaultWidgetQuery = {
  995. conditions: '',
  996. fields: ['equation|count_if(transaction.duration,equals,300)*2'],
  997. aggregates: ['equation|count_if(transaction.duration,equals,300)*2'],
  998. columns: [],
  999. orderby: '',
  1000. name: '',
  1001. };
  1002. const defaultTableColumns = [
  1003. 'count_if(transaction.duration,equals,300)',
  1004. 'equation|count_if(transaction.duration,equals,300)*2',
  1005. ];
  1006. renderTestComponent({
  1007. query: {
  1008. source: DashboardWidgetSource.DISCOVERV2,
  1009. defaultWidgetQuery: urlEncode(defaultWidgetQuery),
  1010. defaultTableColumns,
  1011. yAxis: ['equation|count_if(transaction.duration,equals,300)*2'],
  1012. },
  1013. });
  1014. expect(
  1015. await screen.findByText('count_if(transaction.duration,equals,300)*2')
  1016. ).toBeInTheDocument();
  1017. });
  1018. it('sets the correct fields for a top n widget', async () => {
  1019. renderTestComponent({
  1020. orgFeatures: [...defaultOrgFeatures, 'performance-view'],
  1021. query: {
  1022. displayType: DisplayType.TOP_N,
  1023. },
  1024. });
  1025. // Top N now opens as Area Chart
  1026. await screen.findByText('Area Chart');
  1027. // Add a group by
  1028. userEvent.click(screen.getByText('Add Overlay'));
  1029. await selectEvent.select(screen.getByText('Select group'), /project/);
  1030. // Change the y-axis
  1031. await selectEvent.select(screen.getAllByText('count()')[0], 'eps()');
  1032. await waitFor(() => {
  1033. expect(eventsStatsMock).toHaveBeenLastCalledWith(
  1034. '/organizations/org-slug/events-stats/',
  1035. expect.objectContaining({
  1036. query: expect.objectContaining({
  1037. query: '',
  1038. yAxis: ['eps()'],
  1039. field: ['project', 'eps()'],
  1040. topEvents: TOP_N,
  1041. orderby: '-eps()',
  1042. }),
  1043. })
  1044. );
  1045. });
  1046. });
  1047. it('fetches tags when tag store is empty', function () {
  1048. renderTestComponent();
  1049. expect(tagsMock).toHaveBeenCalled();
  1050. });
  1051. it('does not fetch tags when tag store is not empty', function () {
  1052. TagStore.loadTagsSuccess(TestStubs.Tags());
  1053. renderTestComponent();
  1054. expect(tagsMock).not.toHaveBeenCalled();
  1055. });
  1056. it('excludes the Other series when grouping and using multiple y-axes', async function () {
  1057. renderTestComponent({
  1058. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1059. query: {
  1060. displayType: DisplayType.LINE,
  1061. },
  1062. });
  1063. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1064. userEvent.click(screen.getByText('Add Overlay'));
  1065. await selectEvent.select(screen.getByText('(Required)'), /count_unique/);
  1066. await waitFor(() => {
  1067. expect(eventsStatsMock).toBeCalledWith(
  1068. '/organizations/org-slug/events-stats/',
  1069. expect.objectContaining({
  1070. query: expect.objectContaining({excludeOther: '1'}),
  1071. })
  1072. );
  1073. });
  1074. });
  1075. it('excludes the Other series when grouping and using multiple queries', async function () {
  1076. renderTestComponent({
  1077. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1078. query: {
  1079. displayType: DisplayType.LINE,
  1080. },
  1081. });
  1082. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1083. userEvent.click(screen.getByText('Add Query'));
  1084. await waitFor(() => {
  1085. expect(eventsStatsMock).toBeCalledWith(
  1086. '/organizations/org-slug/events-stats/',
  1087. expect.objectContaining({
  1088. query: expect.objectContaining({excludeOther: '1'}),
  1089. })
  1090. );
  1091. });
  1092. });
  1093. it('includes Other series when there is only one query and one y-axis', async function () {
  1094. renderTestComponent({
  1095. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1096. query: {
  1097. displayType: DisplayType.LINE,
  1098. },
  1099. });
  1100. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1101. await waitFor(() => {
  1102. expect(eventsStatsMock).toBeCalledWith(
  1103. '/organizations/org-slug/events-stats/',
  1104. expect.objectContaining({
  1105. query: expect.not.objectContaining({excludeOther: '1'}),
  1106. })
  1107. );
  1108. });
  1109. });
  1110. it('decreases the limit when more y-axes and queries are added', async function () {
  1111. renderTestComponent({
  1112. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1113. query: {
  1114. displayType: DisplayType.LINE,
  1115. },
  1116. });
  1117. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1118. screen.getByText('Limit to 5 results');
  1119. userEvent.click(screen.getByText('Add Query'));
  1120. userEvent.click(screen.getByText('Add Overlay'));
  1121. await screen.findByText('Limit to 2 results');
  1122. });
  1123. it('alerts the user if there are unsaved changes', async function () {
  1124. const {router} = renderTestComponent();
  1125. const alertMock = jest.fn();
  1126. const setRouteLeaveHookMock = jest.spyOn(router, 'setRouteLeaveHook');
  1127. setRouteLeaveHookMock.mockImplementationOnce((_route, _callback) => {
  1128. alertMock();
  1129. });
  1130. const customWidgetLabels = await screen.findAllByText('Custom Widget');
  1131. // EditableText and chart title
  1132. expect(customWidgetLabels).toHaveLength(2);
  1133. // Change title text
  1134. userEvent.click(customWidgetLabels[0]);
  1135. userEvent.clear(screen.getByRole('textbox', {name: 'Widget title'}));
  1136. userEvent.paste(
  1137. screen.getByRole('textbox', {name: 'Widget title'}),
  1138. 'Unique Users'
  1139. );
  1140. userEvent.keyboard('{enter}');
  1141. // Click Cancel
  1142. userEvent.click(screen.getByText('Cancel'));
  1143. // Assert an alert was triggered
  1144. expect(alertMock).toHaveBeenCalled();
  1145. });
  1146. it('does not trigger alert dialog if no changes', async function () {
  1147. const {router} = renderTestComponent();
  1148. const alertMock = jest.fn();
  1149. const setRouteLeaveHookMock = jest.spyOn(router, 'setRouteLeaveHook');
  1150. setRouteLeaveHookMock.mockImplementationOnce((_route, _callback) => {
  1151. alertMock();
  1152. });
  1153. await screen.findAllByText('Custom Widget');
  1154. // Click Cancel
  1155. userEvent.click(screen.getByText('Cancel'));
  1156. // Assert an alert was triggered
  1157. expect(alertMock).not.toHaveBeenCalled();
  1158. });
  1159. describe('Sort by selectors', function () {
  1160. it('renders', async function () {
  1161. renderTestComponent({
  1162. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1163. });
  1164. expect(await screen.findByText('Sort by a column')).toBeInTheDocument();
  1165. expect(
  1166. screen.getByText("Choose one of the columns you've created to sort by.")
  1167. ).toBeInTheDocument();
  1168. // Selector "sortDirection"
  1169. expect(screen.getByText('High to low')).toBeInTheDocument();
  1170. // Selector "sortBy"
  1171. expect(screen.getAllByText('count()')).toHaveLength(3);
  1172. });
  1173. it('ordering by column uses field form when selecting orderby', async function () {
  1174. const widget: Widget = {
  1175. id: '1',
  1176. title: 'Test Widget',
  1177. interval: '5m',
  1178. displayType: DisplayType.TABLE,
  1179. queries: [
  1180. {
  1181. name: 'errors',
  1182. conditions: 'event.type:error',
  1183. fields: ['count()'],
  1184. aggregates: ['count()'],
  1185. columns: ['project'],
  1186. orderby: '-project',
  1187. },
  1188. ],
  1189. };
  1190. const dashboard = mockDashboard({widgets: [widget]});
  1191. renderTestComponent({
  1192. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1193. dashboard,
  1194. params: {
  1195. widgetIndex: '0',
  1196. },
  1197. });
  1198. await waitFor(async () => {
  1199. expect(await screen.findAllByText('project')).toHaveLength(3);
  1200. });
  1201. await selectEvent.select(screen.getAllByText('project')[2], 'count()');
  1202. await waitFor(() => {
  1203. expect(eventsv2Mock).toHaveBeenCalledWith(
  1204. '/organizations/org-slug/eventsv2/',
  1205. expect.objectContaining({
  1206. query: expect.objectContaining({
  1207. sort: ['-count()'],
  1208. }),
  1209. })
  1210. );
  1211. });
  1212. });
  1213. it('sortBy defaults to the first field value when changing display type to table', async function () {
  1214. const widget: Widget = {
  1215. id: '1',
  1216. title: 'Errors over time',
  1217. interval: '5m',
  1218. displayType: DisplayType.LINE,
  1219. queries: [
  1220. {
  1221. name: 'errors',
  1222. conditions: 'event.type:error',
  1223. fields: ['count()', 'count_unique(id)'],
  1224. aggregates: ['count()', 'count_unique(id)'],
  1225. columns: [],
  1226. orderby: '',
  1227. },
  1228. {
  1229. name: 'csp',
  1230. conditions: 'event.type:csp',
  1231. fields: ['count()', 'count_unique(id)'],
  1232. aggregates: ['count()', 'count_unique(id)'],
  1233. columns: [],
  1234. orderby: '',
  1235. },
  1236. ],
  1237. };
  1238. const dashboard = mockDashboard({widgets: [widget]});
  1239. renderTestComponent({
  1240. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1241. dashboard,
  1242. params: {
  1243. widgetIndex: '0',
  1244. },
  1245. });
  1246. // Click on the displayType selector
  1247. userEvent.click(await screen.findByText('Line Chart'));
  1248. // Choose the table visualization
  1249. userEvent.click(screen.getByText('Table'));
  1250. expect(await screen.findByText('Sort by a column')).toBeInTheDocument();
  1251. // Selector "sortDirection"
  1252. expect(screen.getByText('High to low')).toBeInTheDocument();
  1253. // Selector "sortBy"
  1254. expect(screen.getAllByText('count()')).toHaveLength(3);
  1255. });
  1256. it('can update selectors values', async function () {
  1257. const handleSave = jest.fn();
  1258. const widget: Widget = {
  1259. id: '1',
  1260. title: 'Errors over time',
  1261. interval: '5m',
  1262. displayType: DisplayType.TABLE,
  1263. queries: [
  1264. {
  1265. name: '',
  1266. conditions: '',
  1267. fields: ['count()', 'count_unique(id)'],
  1268. aggregates: ['count()', 'count_unique(id)'],
  1269. columns: [],
  1270. orderby: '-count()',
  1271. },
  1272. ],
  1273. };
  1274. const dashboard = mockDashboard({widgets: [widget]});
  1275. renderTestComponent({
  1276. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1277. dashboard,
  1278. onSave: handleSave,
  1279. params: {
  1280. widgetIndex: '0',
  1281. },
  1282. });
  1283. expect(await screen.findByText('Sort by a column')).toBeInTheDocument();
  1284. // Selector "sortDirection"
  1285. expect(screen.getByText('High to low')).toBeInTheDocument();
  1286. // Selector "sortBy"
  1287. expect(screen.getAllByText('count()')).toHaveLength(3);
  1288. await selectEvent.select(screen.getAllByText('count()')[2], 'count_unique(id)');
  1289. // Wait for the Builder update the widget values
  1290. await waitFor(() => {
  1291. expect(screen.getAllByText('count()')).toHaveLength(2);
  1292. });
  1293. // Now count_unique(id) is selected in the "sortBy" selector
  1294. expect(screen.getAllByText('count_unique(id)')).toHaveLength(2);
  1295. await selectEvent.select(screen.getByText('High to low'), 'Low to high');
  1296. // Saves the widget
  1297. userEvent.click(screen.getByText('Update Widget'));
  1298. await waitFor(() => {
  1299. expect(handleSave).toHaveBeenCalledWith([
  1300. expect.objectContaining({
  1301. queries: [expect.objectContaining({orderby: 'count_unique(id)'})],
  1302. }),
  1303. ]);
  1304. });
  1305. });
  1306. it('sortBy defaults to the first field value when coming from discover', async function () {
  1307. const defaultWidgetQuery = {
  1308. name: '',
  1309. fields: ['title', 'count()', 'count_unique(user)', 'epm()', 'count()'],
  1310. columns: ['title'],
  1311. aggregates: ['count()', 'count_unique(user)', 'epm()', 'count()'],
  1312. conditions: 'tag:value',
  1313. orderby: '',
  1314. };
  1315. const {router} = renderTestComponent({
  1316. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1317. query: {
  1318. source: DashboardWidgetSource.DISCOVERV2,
  1319. defaultWidgetQuery: urlEncode(defaultWidgetQuery),
  1320. displayType: DisplayType.TABLE,
  1321. defaultTableColumns: ['title', 'count()', 'count_unique(user)', 'epm()'],
  1322. },
  1323. });
  1324. expect(await screen.findByText('Sort by a column')).toBeInTheDocument();
  1325. // Selector "sortDirection"
  1326. expect(screen.getByText('Low to high')).toBeInTheDocument();
  1327. // Selector "sortBy"
  1328. expect(screen.getAllByText('title')).toHaveLength(2);
  1329. // Saves the widget
  1330. userEvent.click(screen.getByText('Add Widget'));
  1331. await waitFor(() => {
  1332. expect(router.push).toHaveBeenCalledWith(
  1333. expect.objectContaining({
  1334. query: expect.objectContaining({queryOrderby: 'count()'}),
  1335. })
  1336. );
  1337. });
  1338. });
  1339. it('sortBy is only visible on tabular visualizations or when there is a groupBy value selected on time-series visualizations', async function () {
  1340. renderTestComponent({
  1341. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1342. });
  1343. // Sort by shall be visible on table visualization
  1344. expect(await screen.findByText('Sort by a column')).toBeInTheDocument();
  1345. // Update visualization to be a time-series
  1346. userEvent.click(screen.getByText('Table'));
  1347. userEvent.click(screen.getByText('Line Chart'));
  1348. // Time-series visualizations display GroupBy step
  1349. expect(await screen.findByText('Group your results')).toBeInTheDocument();
  1350. // Do not show sortBy when empty columns (groupBys) are added
  1351. userEvent.click(screen.getByText('Add Group'));
  1352. expect(screen.getAllByText('Select group')).toHaveLength(2);
  1353. // SortBy step shall not be visible
  1354. expect(screen.queryByText('Sort by a y-axis')).not.toBeInTheDocument();
  1355. // Select GroupBy value
  1356. await selectEvent.select(screen.getAllByText('Select group')[0], 'project');
  1357. // Now that at least one groupBy value is selected, the SortBy step shall be visible
  1358. expect(screen.getByText('Sort by a y-axis')).toBeInTheDocument();
  1359. // Remove selected GroupBy value
  1360. userEvent.click(screen.getAllByLabelText('Remove group')[0]);
  1361. // SortBy step shall no longer be visible
  1362. expect(screen.queryByText('Sort by a y-axis')).not.toBeInTheDocument();
  1363. });
  1364. it('allows for sorting by a custom equation', async function () {
  1365. renderTestComponent({
  1366. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1367. query: {
  1368. source: DashboardWidgetSource.DASHBOARDS,
  1369. displayType: DisplayType.LINE,
  1370. },
  1371. });
  1372. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1373. expect(screen.getAllByText('count()')).toHaveLength(2);
  1374. await selectEvent.select(screen.getAllByText('count()')[1], 'Custom Equation');
  1375. userEvent.paste(
  1376. screen.getByPlaceholderText('Enter Equation'),
  1377. 'count_unique(user) * 2'
  1378. );
  1379. userEvent.keyboard('{enter}');
  1380. await waitFor(() => {
  1381. expect(eventsStatsMock).toHaveBeenCalledWith(
  1382. '/organizations/org-slug/events-stats/',
  1383. expect.objectContaining({
  1384. query: expect.objectContaining({
  1385. field: expect.arrayContaining(['equation|count_unique(user) * 2']),
  1386. orderby: '-equation[0]',
  1387. }),
  1388. })
  1389. );
  1390. });
  1391. }, 10000);
  1392. it('persists the state when toggling between sorting options', async function () {
  1393. renderTestComponent({
  1394. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1395. query: {
  1396. source: DashboardWidgetSource.DASHBOARDS,
  1397. displayType: DisplayType.LINE,
  1398. },
  1399. });
  1400. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1401. expect(screen.getAllByText('count()')).toHaveLength(2);
  1402. await selectEvent.select(screen.getAllByText('count()')[1], 'Custom Equation');
  1403. userEvent.paste(
  1404. screen.getByPlaceholderText('Enter Equation'),
  1405. 'count_unique(user) * 2'
  1406. );
  1407. userEvent.keyboard('{enter}');
  1408. // Switch away from the Custom Equation
  1409. expect(screen.getByText('project')).toBeInTheDocument();
  1410. await selectEvent.select(screen.getByText('Custom Equation'), 'project');
  1411. expect(screen.getAllByText('project')).toHaveLength(2);
  1412. // Switch back, the equation should still be visible
  1413. await selectEvent.select(screen.getAllByText('project')[1], 'Custom Equation');
  1414. expect(screen.getByPlaceholderText('Enter Equation')).toHaveValue(
  1415. 'count_unique(user) * 2'
  1416. );
  1417. });
  1418. it('persists the state when updating y-axes', async function () {
  1419. renderTestComponent({
  1420. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1421. query: {
  1422. source: DashboardWidgetSource.DASHBOARDS,
  1423. displayType: DisplayType.LINE,
  1424. },
  1425. });
  1426. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1427. expect(screen.getAllByText('count()')).toHaveLength(2);
  1428. await selectEvent.select(screen.getAllByText('count()')[1], 'Custom Equation');
  1429. userEvent.paste(
  1430. screen.getByPlaceholderText('Enter Equation'),
  1431. 'count_unique(user) * 2'
  1432. );
  1433. userEvent.keyboard('{enter}');
  1434. // Add a y-axis
  1435. userEvent.click(screen.getByText('Add Overlay'));
  1436. // The equation should still be visible
  1437. expect(screen.getByPlaceholderText('Enter Equation')).toHaveValue(
  1438. 'count_unique(user) * 2'
  1439. );
  1440. });
  1441. it('displays the custom equation if the widget has it saved', async function () {
  1442. const widget: Widget = {
  1443. id: '1',
  1444. title: 'Test Widget',
  1445. interval: '5m',
  1446. displayType: DisplayType.LINE,
  1447. queries: [
  1448. {
  1449. name: '',
  1450. conditions: '',
  1451. fields: ['count()', 'project'],
  1452. aggregates: ['count()'],
  1453. columns: ['project'],
  1454. orderby: '-equation|count_unique(user) * 2',
  1455. },
  1456. ],
  1457. };
  1458. const dashboard = mockDashboard({widgets: [widget]});
  1459. renderTestComponent({
  1460. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1461. query: {
  1462. source: DashboardWidgetSource.DASHBOARDS,
  1463. displayType: DisplayType.LINE,
  1464. },
  1465. params: {
  1466. widgetIndex: '0',
  1467. },
  1468. dashboard,
  1469. });
  1470. expect(await screen.findByPlaceholderText('Enter Equation')).toHaveValue(
  1471. 'count_unique(user) * 2'
  1472. );
  1473. });
  1474. it('displays Operators in the input dropdown', async function () {
  1475. renderTestComponent({
  1476. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1477. query: {
  1478. source: DashboardWidgetSource.DASHBOARDS,
  1479. displayType: DisplayType.LINE,
  1480. },
  1481. });
  1482. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1483. expect(screen.getAllByText('count()')).toHaveLength(2);
  1484. await selectEvent.select(screen.getAllByText('count()')[1], 'Custom Equation');
  1485. selectEvent.openMenu(screen.getByPlaceholderText('Enter Equation'));
  1486. expect(screen.getByText('Operators')).toBeInTheDocument();
  1487. expect(screen.queryByText('Fields')).not.toBeInTheDocument();
  1488. });
  1489. it('hides Custom Equation input and resets orderby when switching to table', async function () {
  1490. renderTestComponent({
  1491. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1492. query: {
  1493. source: DashboardWidgetSource.DASHBOARDS,
  1494. displayType: DisplayType.LINE,
  1495. },
  1496. });
  1497. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1498. expect(screen.getAllByText('count()')).toHaveLength(2);
  1499. await selectEvent.select(screen.getAllByText('count()')[1], 'Custom Equation');
  1500. userEvent.paste(
  1501. screen.getByPlaceholderText('Enter Equation'),
  1502. 'count_unique(user) * 2'
  1503. );
  1504. userEvent.keyboard('{enter}');
  1505. // Switch the display type to Table
  1506. userEvent.click(screen.getByText('Line Chart'));
  1507. userEvent.click(screen.getByText('Table'));
  1508. expect(screen.getAllByText('count()')).toHaveLength(2);
  1509. expect(screen.queryByPlaceholderText('Enter Equation')).not.toBeInTheDocument();
  1510. await waitFor(() => {
  1511. expect(eventsv2Mock).toHaveBeenCalledWith(
  1512. '/organizations/org-slug/eventsv2/',
  1513. expect.objectContaining({
  1514. query: expect.objectContaining({
  1515. sort: ['-count()'],
  1516. }),
  1517. })
  1518. );
  1519. });
  1520. });
  1521. it('does not show the Custom Equation input if the only y-axis left is an empty equation', async function () {
  1522. renderTestComponent({
  1523. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1524. query: {
  1525. source: DashboardWidgetSource.DASHBOARDS,
  1526. displayType: DisplayType.LINE,
  1527. },
  1528. });
  1529. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1530. userEvent.click(screen.getByText('Add an Equation'));
  1531. userEvent.click(screen.getAllByLabelText('Remove this Y-Axis')[0]);
  1532. expect(screen.queryByPlaceholderText('Enter Equation')).not.toBeInTheDocument();
  1533. });
  1534. it('persists a sort by a grouping when changing y-axes', async function () {
  1535. renderTestComponent({
  1536. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1537. query: {
  1538. source: DashboardWidgetSource.DASHBOARDS,
  1539. displayType: DisplayType.LINE,
  1540. },
  1541. });
  1542. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1543. expect(screen.getAllByText('count()')).toHaveLength(2);
  1544. // Change the sort option to a grouping field, and then change a y-axis
  1545. await selectEvent.select(screen.getAllByText('count()')[1], 'project');
  1546. await selectEvent.select(screen.getAllByText('count()')[0], /count_unique/);
  1547. // project should appear in the group by field, as well as the sort field
  1548. expect(screen.getAllByText('project')).toHaveLength(2);
  1549. });
  1550. it('persists sort by a y-axis when grouping changes', async function () {
  1551. renderTestComponent({
  1552. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1553. query: {
  1554. source: DashboardWidgetSource.DASHBOARDS,
  1555. displayType: DisplayType.LINE,
  1556. },
  1557. });
  1558. userEvent.click(await screen.findByText('Add Overlay'));
  1559. await selectEvent.select(screen.getByText('Select group'), 'project');
  1560. // Change the sort by to count_unique
  1561. await selectEvent.select(screen.getAllByText('count()')[1], /count_unique/);
  1562. // Change the grouping
  1563. await selectEvent.select(screen.getByText('project'), 'environment');
  1564. // count_unique(user) should still be the sorting field
  1565. expect(screen.getByText(/count_unique/)).toBeInTheDocument();
  1566. expect(screen.getByText('user')).toBeInTheDocument();
  1567. });
  1568. it('does not remove the Custom Equation field if a grouping is updated', async function () {
  1569. renderTestComponent({
  1570. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1571. query: {
  1572. source: DashboardWidgetSource.DASHBOARDS,
  1573. displayType: DisplayType.LINE,
  1574. },
  1575. });
  1576. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1577. await selectEvent.select(screen.getAllByText('count()')[1], 'Custom Equation');
  1578. userEvent.paste(
  1579. screen.getByPlaceholderText('Enter Equation'),
  1580. 'count_unique(user) * 2'
  1581. );
  1582. userEvent.keyboard('{enter}');
  1583. userEvent.click(screen.getByText('Add Group'));
  1584. expect(screen.getByPlaceholderText('Enter Equation')).toHaveValue(
  1585. 'count_unique(user) * 2'
  1586. );
  1587. });
  1588. it.each`
  1589. directionPrefix | expectedOrderSelection | displayType
  1590. ${'-'} | ${'High to low'} | ${DisplayType.TABLE}
  1591. ${''} | ${'Low to high'} | ${DisplayType.TABLE}
  1592. ${'-'} | ${'High to low'} | ${DisplayType.LINE}
  1593. ${''} | ${'Low to high'} | ${DisplayType.LINE}
  1594. `(
  1595. `opens a widget with the '$expectedOrderSelection' sort order when the widget was saved with that direction`,
  1596. async function ({directionPrefix, expectedOrderSelection}) {
  1597. const widget: Widget = {
  1598. id: '1',
  1599. title: 'Test Widget',
  1600. interval: '5m',
  1601. displayType: DisplayType.LINE,
  1602. queries: [
  1603. {
  1604. name: '',
  1605. conditions: '',
  1606. fields: ['count_unique(user)'],
  1607. aggregates: ['count_unique(user)'],
  1608. columns: ['project'],
  1609. orderby: `${directionPrefix}count_unique(user)`,
  1610. },
  1611. ],
  1612. };
  1613. const dashboard = mockDashboard({widgets: [widget]});
  1614. renderTestComponent({
  1615. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1616. dashboard,
  1617. params: {
  1618. widgetIndex: '0',
  1619. },
  1620. });
  1621. await screen.findByText(expectedOrderSelection);
  1622. }
  1623. );
  1624. it('saved widget with aggregate alias as orderby should persist alias when y-axes change', async function () {
  1625. const widget: Widget = {
  1626. id: '1',
  1627. title: 'Test Widget',
  1628. interval: '5m',
  1629. displayType: DisplayType.TABLE,
  1630. queries: [
  1631. {
  1632. name: '',
  1633. conditions: '',
  1634. fields: ['project', 'count_unique(user)'],
  1635. aggregates: ['count_unique(user)'],
  1636. columns: ['project'],
  1637. orderby: 'count_unique(user)',
  1638. },
  1639. ],
  1640. };
  1641. const dashboard = mockDashboard({widgets: [widget]});
  1642. renderTestComponent({
  1643. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1644. dashboard,
  1645. params: {
  1646. widgetIndex: '0',
  1647. },
  1648. });
  1649. await screen.findByText('Sort by a column');
  1650. // Assert for length 2 since one in the table header and one in sort by
  1651. expect(screen.getAllByText('count_unique(user)')).toHaveLength(2);
  1652. userEvent.click(screen.getByText('Add a Column'));
  1653. // The sort by should still have count_unique(user)
  1654. await waitFor(() =>
  1655. expect(screen.getAllByText('count_unique(user)')).toHaveLength(2)
  1656. );
  1657. });
  1658. it('will reset the sort field when going from line to table when sorting by a value not in fields', async function () {
  1659. renderTestComponent({
  1660. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1661. query: {
  1662. displayType: DisplayType.LINE,
  1663. },
  1664. });
  1665. await selectEvent.select(await screen.findByText('Select group'), 'project');
  1666. expect(screen.getAllByText('count()')).toHaveLength(2);
  1667. await selectEvent.select(screen.getAllByText('count()')[1], /count_unique/);
  1668. userEvent.click(screen.getByText('Line Chart'));
  1669. userEvent.click(screen.getByText('Table'));
  1670. // 1 for table header, 1 for column selection, and 1 for sorting
  1671. await waitFor(() => {
  1672. expect(screen.getAllByText('count()')).toHaveLength(3);
  1673. });
  1674. });
  1675. it('equations in y-axis appear in sort by field for grouped timeseries', async function () {
  1676. renderTestComponent({
  1677. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1678. query: {
  1679. displayType: DisplayType.LINE,
  1680. },
  1681. });
  1682. userEvent.click(await screen.findByText('Add an Equation'));
  1683. userEvent.paste(screen.getByPlaceholderText('Equation'), 'count() * 100');
  1684. userEvent.keyboard('{enter}');
  1685. await selectEvent.select(screen.getByText('Select group'), 'project');
  1686. expect(screen.getAllByText('count()')).toHaveLength(2);
  1687. await selectEvent.select(screen.getAllByText('count()')[1], 'count() * 100');
  1688. });
  1689. it('does not reset the orderby when ordered by an equation in table', async function () {
  1690. const widget: Widget = {
  1691. id: '1',
  1692. title: 'Errors over time',
  1693. interval: '5m',
  1694. displayType: DisplayType.TABLE,
  1695. queries: [
  1696. {
  1697. name: '',
  1698. conditions: '',
  1699. fields: [
  1700. 'count()',
  1701. 'count_unique(id)',
  1702. 'equation|count() + count_unique(id)',
  1703. ],
  1704. aggregates: [
  1705. 'count()',
  1706. 'count_unique(id)',
  1707. 'equation|count() + count_unique(id)',
  1708. ],
  1709. columns: [],
  1710. orderby: '-equation[0]',
  1711. },
  1712. ],
  1713. };
  1714. const dashboard = mockDashboard({widgets: [widget]});
  1715. renderTestComponent({
  1716. dashboard,
  1717. params: {
  1718. widgetIndex: '0',
  1719. },
  1720. });
  1721. await screen.findByText('Sort by a column');
  1722. // 1 in the column selector, 1 in the sort by field
  1723. expect(screen.getAllByText('count() + count_unique(id)')).toHaveLength(2);
  1724. });
  1725. });
  1726. describe('Widget creation coming from other verticals', function () {
  1727. it('redirects correctly when creating a new dashboard', async function () {
  1728. const {router} = renderTestComponent({
  1729. query: {source: DashboardWidgetSource.DISCOVERV2},
  1730. });
  1731. userEvent.click(await screen.findByText('Add Widget'));
  1732. await waitFor(() => {
  1733. expect(router.push).toHaveBeenCalledWith(
  1734. expect.objectContaining({
  1735. pathname: '/organizations/org-slug/dashboards/new/',
  1736. query: {
  1737. displayType: 'table',
  1738. interval: '5m',
  1739. title: 'Custom Widget',
  1740. queryNames: [''],
  1741. queryConditions: [''],
  1742. queryFields: ['count()'],
  1743. queryOrderby: '-count()',
  1744. start: null,
  1745. end: null,
  1746. statsPeriod: '24h',
  1747. utc: false,
  1748. project: [],
  1749. environment: [],
  1750. },
  1751. })
  1752. );
  1753. });
  1754. });
  1755. it('redirects correctly when choosing an existing dashboard', async function () {
  1756. const {router} = renderTestComponent({
  1757. query: {source: DashboardWidgetSource.DISCOVERV2},
  1758. dashboard: testDashboard,
  1759. });
  1760. userEvent.click(await screen.findByText('Add Widget'));
  1761. await waitFor(() => {
  1762. expect(router.push).toHaveBeenCalledWith(
  1763. expect.objectContaining({
  1764. pathname: '/organizations/org-slug/dashboard/2/',
  1765. query: {
  1766. displayType: 'table',
  1767. interval: '5m',
  1768. title: 'Custom Widget',
  1769. queryNames: [''],
  1770. queryConditions: [''],
  1771. queryFields: ['count()'],
  1772. queryOrderby: '-count()',
  1773. start: null,
  1774. end: null,
  1775. statsPeriod: '24h',
  1776. utc: false,
  1777. project: [],
  1778. environment: [],
  1779. },
  1780. })
  1781. );
  1782. });
  1783. });
  1784. it('shows the correct orderby when switching from a line chart to table', async function () {
  1785. const defaultWidgetQuery = {
  1786. name: '',
  1787. fields: ['count_unique(user)'],
  1788. columns: [],
  1789. aggregates: ['count_unique(user)'],
  1790. conditions: '',
  1791. orderby: 'count_unique(user)',
  1792. };
  1793. const defaultTableColumns = ['title', 'count_unique(user)'];
  1794. renderTestComponent({
  1795. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1796. query: {
  1797. source: DashboardWidgetSource.DISCOVERV2,
  1798. defaultWidgetQuery: urlEncode(defaultWidgetQuery),
  1799. displayType: DisplayType.LINE,
  1800. defaultTableColumns,
  1801. },
  1802. });
  1803. userEvent.click(await screen.findByText('Line Chart'));
  1804. userEvent.click(screen.getByText('Table'));
  1805. expect(screen.getByText('count_unique(user)')).toBeInTheDocument();
  1806. await waitFor(() => {
  1807. expect(eventsv2Mock).toHaveBeenLastCalledWith(
  1808. '/organizations/org-slug/eventsv2/',
  1809. expect.objectContaining({
  1810. query: expect.objectContaining({
  1811. field: defaultTableColumns,
  1812. sort: ['count_unique(user)'],
  1813. }),
  1814. })
  1815. );
  1816. });
  1817. });
  1818. it('does not send request with orderby if a timeseries chart without grouping', async function () {
  1819. const defaultWidgetQuery = {
  1820. name: '',
  1821. fields: ['count_unique(user)'],
  1822. columns: [],
  1823. aggregates: ['count_unique(user)'],
  1824. conditions: '',
  1825. orderby: 'count_unique(user)',
  1826. };
  1827. const defaultTableColumns = ['title', 'count_unique(user)'];
  1828. renderTestComponent({
  1829. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1830. query: {
  1831. source: DashboardWidgetSource.DISCOVERV2,
  1832. defaultWidgetQuery: urlEncode(defaultWidgetQuery),
  1833. displayType: DisplayType.LINE,
  1834. defaultTableColumns,
  1835. },
  1836. });
  1837. await waitFor(() => {
  1838. expect(eventsStatsMock).toHaveBeenLastCalledWith(
  1839. '/organizations/org-slug/events-stats/',
  1840. expect.objectContaining({
  1841. query: expect.objectContaining({
  1842. orderby: '',
  1843. }),
  1844. })
  1845. );
  1846. });
  1847. });
  1848. });
  1849. it('opens top-N widgets as area display', async function () {
  1850. const widget: Widget = {
  1851. id: '1',
  1852. title: 'Errors over time',
  1853. interval: '5m',
  1854. displayType: DisplayType.TOP_N,
  1855. queries: [
  1856. {
  1857. name: '',
  1858. conditions: '',
  1859. fields: ['count()', 'count_unique(id)'],
  1860. aggregates: ['count()', 'count_unique(id)'],
  1861. columns: [],
  1862. orderby: '-count()',
  1863. },
  1864. ],
  1865. };
  1866. const dashboard = mockDashboard({widgets: [widget]});
  1867. renderTestComponent({
  1868. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1869. dashboard,
  1870. params: {
  1871. widgetIndex: '0',
  1872. },
  1873. });
  1874. expect(await screen.findByText('Area Chart')).toBeInTheDocument();
  1875. });
  1876. it('Update table header values (field alias)', async function () {
  1877. const handleSave = jest.fn();
  1878. renderTestComponent({
  1879. onSave: handleSave,
  1880. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1881. });
  1882. await screen.findByText('Table');
  1883. userEvent.paste(screen.getByPlaceholderText('Alias'), 'First Alias');
  1884. userEvent.click(screen.getByLabelText('Add a Column'));
  1885. userEvent.paste(screen.getAllByPlaceholderText('Alias')[1], 'Second Alias');
  1886. userEvent.click(screen.getByText('Add Widget'));
  1887. await waitFor(() => {
  1888. expect(handleSave).toHaveBeenCalledWith([
  1889. expect.objectContaining({
  1890. queries: [
  1891. expect.objectContaining({fieldAliases: ['First Alias', 'Second Alias']}),
  1892. ],
  1893. }),
  1894. ]);
  1895. });
  1896. });
  1897. it('does not wipe equation aliases when a column alias is updated', async function () {
  1898. renderTestComponent({
  1899. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1900. });
  1901. await screen.findByText('Table');
  1902. userEvent.click(screen.getByText('Add an Equation'));
  1903. userEvent.paste(screen.getAllByPlaceholderText('Alias')[1], 'This should persist');
  1904. userEvent.type(screen.getAllByPlaceholderText('Alias')[0], 'A');
  1905. expect(await screen.findByText('This should persist')).toBeInTheDocument();
  1906. });
  1907. it('does not wipe equation aliases when a column selection is made', async function () {
  1908. renderTestComponent({
  1909. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1910. });
  1911. await screen.findByText('Table');
  1912. userEvent.click(screen.getByText('Add an Equation'));
  1913. userEvent.paste(screen.getAllByPlaceholderText('Alias')[1], 'This should persist');
  1914. // 1 for the table, 1 for the the column selector, 1 for the sort
  1915. await waitFor(() => expect(screen.getAllByText('count()')).toHaveLength(3));
  1916. await selectEvent.select(screen.getAllByText('count()')[1], /count_unique/);
  1917. expect(screen.getByText('This should persist')).toBeInTheDocument();
  1918. });
  1919. it('copies over the orderby from the previous query if adding another', async function () {
  1920. renderTestComponent({
  1921. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  1922. });
  1923. userEvent.click(await screen.findByText('Table'));
  1924. userEvent.click(screen.getByText('Line Chart'));
  1925. await selectEvent.select(screen.getByText('Select group'), 'project');
  1926. await selectEvent.select(screen.getAllByText('count()')[1], 'count_unique(…)');
  1927. MockApiClient.clearMockResponses();
  1928. eventsStatsMock = MockApiClient.addMockResponse({
  1929. url: '/organizations/org-slug/events-stats/',
  1930. body: [],
  1931. });
  1932. userEvent.click(screen.getByText('Add Query'));
  1933. // Assert on two calls, one for each query
  1934. const expectedArgs = expect.objectContaining({
  1935. query: expect.objectContaining({
  1936. orderby: '-count_unique(user)',
  1937. }),
  1938. });
  1939. expect(eventsStatsMock).toHaveBeenNthCalledWith(
  1940. 1,
  1941. '/organizations/org-slug/events-stats/',
  1942. expectedArgs
  1943. );
  1944. expect(eventsStatsMock).toHaveBeenNthCalledWith(
  1945. 2,
  1946. '/organizations/org-slug/events-stats/',
  1947. expectedArgs
  1948. );
  1949. });
  1950. describe('Issue Widgets', function () {
  1951. it('sets widgetType to issues', async function () {
  1952. const handleSave = jest.fn();
  1953. renderTestComponent({onSave: handleSave});
  1954. userEvent.click(
  1955. await screen.findByText('Issues (States, Assignment, Time, etc.)')
  1956. );
  1957. userEvent.click(screen.getByLabelText('Add Widget'));
  1958. await waitFor(() => {
  1959. expect(handleSave).toHaveBeenCalledWith([
  1960. expect.objectContaining({
  1961. title: 'Custom Widget',
  1962. displayType: DisplayType.TABLE,
  1963. interval: '5m',
  1964. widgetType: WidgetType.ISSUE,
  1965. queries: [
  1966. {
  1967. conditions: '',
  1968. fields: ['issue', 'assignee', 'title'],
  1969. columns: ['issue', 'assignee', 'title'],
  1970. aggregates: [],
  1971. fieldAliases: [],
  1972. name: '',
  1973. orderby: 'date',
  1974. },
  1975. ],
  1976. }),
  1977. ]);
  1978. });
  1979. expect(handleSave).toHaveBeenCalledTimes(1);
  1980. });
  1981. it('render issues dataset disabled when the display type is not set to table', async function () {
  1982. renderTestComponent({
  1983. query: {
  1984. source: DashboardWidgetSource.DISCOVERV2,
  1985. },
  1986. });
  1987. userEvent.click(await screen.findByText('Table'));
  1988. userEvent.click(screen.getByText('Line Chart'));
  1989. expect(
  1990. screen.getByRole('radio', {
  1991. name: 'Select Errors and Transactions',
  1992. })
  1993. ).toBeEnabled();
  1994. expect(
  1995. screen.getByRole('radio', {
  1996. name: 'Select Issues (States, Assignment, Time, etc.)',
  1997. })
  1998. ).toBeDisabled();
  1999. });
  2000. it('disables moving and deleting issue column', async function () {
  2001. renderTestComponent();
  2002. userEvent.click(
  2003. await screen.findByText('Issues (States, Assignment, Time, etc.)')
  2004. );
  2005. expect(screen.getByText('issue')).toBeInTheDocument();
  2006. expect(screen.getByText('assignee')).toBeInTheDocument();
  2007. expect(screen.getByText('title')).toBeInTheDocument();
  2008. expect(screen.getAllByLabelText('Remove column')).toHaveLength(2);
  2009. expect(screen.getAllByLabelText('Drag to reorder')).toHaveLength(3);
  2010. userEvent.click(screen.getAllByLabelText('Remove column')[1]);
  2011. userEvent.click(screen.getAllByLabelText('Remove column')[0]);
  2012. expect(screen.getByText('issue')).toBeInTheDocument();
  2013. expect(screen.queryByText('assignee')).not.toBeInTheDocument();
  2014. expect(screen.queryByText('title')).not.toBeInTheDocument();
  2015. expect(screen.queryByLabelText('Remove column')).not.toBeInTheDocument();
  2016. expect(screen.queryByLabelText('Drag to reorder')).not.toBeInTheDocument();
  2017. });
  2018. it('issue query does not work on default search bar', async function () {
  2019. renderTestComponent();
  2020. const input = (await screen.findByPlaceholderText(
  2021. 'Search for events, users, tags, and more'
  2022. )) as HTMLTextAreaElement;
  2023. userEvent.paste(input, 'bookmarks', {
  2024. clipboardData: {getData: () => ''},
  2025. } as unknown as React.ClipboardEvent<HTMLTextAreaElement>);
  2026. input.setSelectionRange(9, 9);
  2027. expect(await screen.findByText('No items found')).toBeInTheDocument();
  2028. });
  2029. it('renders with an issues search bar when selected in dataset selection', async function () {
  2030. renderTestComponent();
  2031. userEvent.click(
  2032. await screen.findByText('Issues (States, Assignment, Time, etc.)')
  2033. );
  2034. const input = (await screen.findByPlaceholderText(
  2035. 'Search for issues, status, assigned, and more'
  2036. )) as HTMLTextAreaElement;
  2037. userEvent.paste(input, 'is:', {
  2038. clipboardData: {getData: () => ''},
  2039. } as unknown as React.ClipboardEvent<HTMLTextAreaElement>);
  2040. input.setSelectionRange(3, 3);
  2041. expect(await screen.findByText('resolved')).toBeInTheDocument();
  2042. });
  2043. it('Update table header values (field alias)', async function () {
  2044. const handleSave = jest.fn();
  2045. renderTestComponent({
  2046. onSave: handleSave,
  2047. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  2048. });
  2049. await screen.findByText('Table');
  2050. userEvent.click(screen.getByText('Issues (States, Assignment, Time, etc.)'));
  2051. userEvent.paste(screen.getAllByPlaceholderText('Alias')[0], 'First Alias');
  2052. userEvent.click(screen.getByText('Add Widget'));
  2053. await waitFor(() => {
  2054. expect(handleSave).toHaveBeenCalledWith([
  2055. expect.objectContaining({
  2056. queries: [
  2057. expect.objectContaining({
  2058. fieldAliases: ['First Alias', '', ''],
  2059. }),
  2060. ],
  2061. }),
  2062. ]);
  2063. });
  2064. });
  2065. });
  2066. describe('Release Widgets', function () {
  2067. const releaseHealthFeatureFlags = [
  2068. ...defaultOrgFeatures,
  2069. 'new-widget-builder-experience-design',
  2070. 'dashboards-releases',
  2071. ];
  2072. it('does not show the Release Health dataset if there is no dashboards-releases flag', async function () {
  2073. renderTestComponent({
  2074. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  2075. });
  2076. expect(await screen.findByText('Errors and Transactions')).toBeInTheDocument();
  2077. expect(
  2078. screen.queryByText('Releases (sessions, crash rates)')
  2079. ).not.toBeInTheDocument();
  2080. });
  2081. it('shows the Release Health dataset if there is the dashboards-releases flag', async function () {
  2082. renderTestComponent({
  2083. orgFeatures: releaseHealthFeatureFlags,
  2084. });
  2085. expect(await screen.findByText('Errors and Transactions')).toBeInTheDocument();
  2086. expect(screen.getByText('Releases (sessions, crash rates)')).toBeInTheDocument();
  2087. });
  2088. it('maintains the selected dataset when display type is changed', async function () {
  2089. renderTestComponent({
  2090. orgFeatures: releaseHealthFeatureFlags,
  2091. });
  2092. expect(
  2093. await screen.findByText('Releases (sessions, crash rates)')
  2094. ).toBeInTheDocument();
  2095. expect(screen.getByLabelText(/releases/i)).not.toBeChecked();
  2096. userEvent.click(screen.getByLabelText(/releases/i));
  2097. await waitFor(() => expect(screen.getByLabelText(/releases/i)).toBeChecked());
  2098. userEvent.click(screen.getByText('Table'));
  2099. userEvent.click(screen.getByText('Line Chart'));
  2100. await waitFor(() => expect(screen.getByLabelText(/releases/i)).toBeChecked());
  2101. });
  2102. it('displays releases tags', async function () {
  2103. renderTestComponent({
  2104. orgFeatures: releaseHealthFeatureFlags,
  2105. });
  2106. expect(
  2107. await screen.findByText('Releases (sessions, crash rates)')
  2108. ).toBeInTheDocument();
  2109. userEvent.click(screen.getByLabelText(/releases/i));
  2110. expect(screen.getByText('crash_free_rate(…)')).toBeInTheDocument();
  2111. expect(screen.getByText('session')).toBeInTheDocument();
  2112. userEvent.click(screen.getByText('crash_free_rate(…)'));
  2113. expect(screen.getByText('count_unique(…)')).toBeInTheDocument();
  2114. expect(screen.getByText('release')).toBeInTheDocument();
  2115. expect(screen.getByText('environment')).toBeInTheDocument();
  2116. expect(screen.getByText('session.status')).toBeInTheDocument();
  2117. userEvent.click(screen.getByText('count_unique(…)'));
  2118. expect(screen.getByText('user')).toBeInTheDocument();
  2119. });
  2120. it('does not display tags as params', async function () {
  2121. renderTestComponent({
  2122. orgFeatures: releaseHealthFeatureFlags,
  2123. });
  2124. expect(
  2125. await screen.findByText('Releases (sessions, crash rates)')
  2126. ).toBeInTheDocument();
  2127. userEvent.click(screen.getByLabelText(/releases/i));
  2128. expect(screen.getByText('crash_free_rate(…)')).toBeInTheDocument();
  2129. await selectEvent.select(
  2130. screen.getByText('crash_free_rate(…)'),
  2131. 'count_unique(…)'
  2132. );
  2133. userEvent.click(screen.getByText('user'));
  2134. expect(screen.queryByText('release')).not.toBeInTheDocument();
  2135. expect(screen.queryByText('environment')).not.toBeInTheDocument();
  2136. expect(screen.queryByText('session.status')).not.toBeInTheDocument();
  2137. });
  2138. it('does not allow sort by when session.status is selected', async function () {
  2139. renderTestComponent({
  2140. orgFeatures: releaseHealthFeatureFlags,
  2141. });
  2142. expect(
  2143. await screen.findByText('Releases (sessions, crash rates)')
  2144. ).toBeInTheDocument();
  2145. userEvent.click(screen.getByLabelText(/releases/i));
  2146. expect(screen.getByText('High to low')).toBeEnabled();
  2147. expect(screen.getByText('crash_free_rate(session)')).toBeInTheDocument();
  2148. userEvent.click(screen.getByLabelText('Add a Column'));
  2149. await selectEvent.select(screen.getByText('(Required)'), 'session.status');
  2150. expect(screen.getByRole('textbox', {name: 'Sort direction'})).toBeDisabled();
  2151. expect(screen.getByRole('textbox', {name: 'Sort by'})).toBeDisabled();
  2152. });
  2153. it('does not allow sort on tags except release', async function () {
  2154. renderTestComponent({
  2155. orgFeatures: releaseHealthFeatureFlags,
  2156. });
  2157. expect(
  2158. await screen.findByText('Releases (sessions, crash rates)')
  2159. ).toBeInTheDocument();
  2160. userEvent.click(screen.getByLabelText(/releases/i));
  2161. expect(screen.getByText('High to low')).toBeEnabled();
  2162. expect(screen.getByText('crash_free_rate(session)')).toBeInTheDocument();
  2163. userEvent.click(screen.getByLabelText('Add a Column'));
  2164. await selectEvent.select(screen.getByText('(Required)'), 'release');
  2165. userEvent.click(screen.getByLabelText('Add a Column'));
  2166. await selectEvent.select(screen.getByText('(Required)'), 'environment');
  2167. expect(await screen.findByText('Sort by a column')).toBeInTheDocument();
  2168. // Selector "sortDirection"
  2169. expect(screen.getByText('High to low')).toBeInTheDocument();
  2170. // Selector "sortBy"
  2171. userEvent.click(screen.getAllByText('crash_free_rate(session)')[1]);
  2172. // release exists in sort by selector
  2173. expect(screen.getAllByText('release')).toHaveLength(3);
  2174. // environment does not exist in sort by selector
  2175. expect(screen.getAllByText('environment')).toHaveLength(2);
  2176. });
  2177. it('makes the appropriate sessions call', async function () {
  2178. renderTestComponent({
  2179. orgFeatures: releaseHealthFeatureFlags,
  2180. });
  2181. expect(
  2182. await screen.findByText('Releases (sessions, crash rates)')
  2183. ).toBeInTheDocument();
  2184. userEvent.click(screen.getByLabelText(/releases/i));
  2185. userEvent.click(screen.getByText('Table'));
  2186. userEvent.click(screen.getByText('Line Chart'));
  2187. await waitFor(() =>
  2188. expect(metricsDataMock).toHaveBeenLastCalledWith(
  2189. `/organizations/org-slug/metrics/data/`,
  2190. expect.objectContaining({
  2191. query: expect.objectContaining({
  2192. environment: [],
  2193. field: [`session.crash_free_rate`],
  2194. groupBy: [],
  2195. interval: '5m',
  2196. project: [],
  2197. statsPeriod: '24h',
  2198. }),
  2199. })
  2200. )
  2201. );
  2202. });
  2203. it('calls the session endpoint with the right limit', async function () {
  2204. renderTestComponent({
  2205. orgFeatures: releaseHealthFeatureFlags,
  2206. });
  2207. expect(
  2208. await screen.findByText('Releases (sessions, crash rates)')
  2209. ).toBeInTheDocument();
  2210. userEvent.click(screen.getByLabelText(/releases/i));
  2211. userEvent.click(screen.getByText('Table'));
  2212. userEvent.click(screen.getByText('Line Chart'));
  2213. await selectEvent.select(await screen.findByText('Select group'), 'project');
  2214. expect(screen.getByText('Limit to 5 results')).toBeInTheDocument();
  2215. await waitFor(() =>
  2216. expect(metricsDataMock).toHaveBeenLastCalledWith(
  2217. `/organizations/org-slug/metrics/data/`,
  2218. expect.objectContaining({
  2219. query: expect.objectContaining({
  2220. environment: [],
  2221. field: ['session.crash_free_rate'],
  2222. groupBy: ['project_id'],
  2223. interval: '5m',
  2224. orderBy: '-session.crash_free_rate',
  2225. per_page: 5,
  2226. project: [],
  2227. statsPeriod: '24h',
  2228. }),
  2229. })
  2230. )
  2231. );
  2232. });
  2233. it('calls sessions api when session.status is selected as a groupby', async function () {
  2234. renderTestComponent({
  2235. orgFeatures: releaseHealthFeatureFlags,
  2236. });
  2237. expect(
  2238. await screen.findByText('Releases (sessions, crash rates)')
  2239. ).toBeInTheDocument();
  2240. userEvent.click(screen.getByLabelText(/releases/i));
  2241. userEvent.click(screen.getByText('Table'));
  2242. userEvent.click(screen.getByText('Line Chart'));
  2243. await selectEvent.select(
  2244. await screen.findByText('Select group'),
  2245. 'session.status'
  2246. );
  2247. expect(screen.getByText('Limit to 5 results')).toBeInTheDocument();
  2248. await waitFor(() =>
  2249. expect(sessionsDataMock).toHaveBeenLastCalledWith(
  2250. `/organizations/org-slug/sessions/`,
  2251. expect.objectContaining({
  2252. query: expect.objectContaining({
  2253. environment: [],
  2254. field: ['crash_free_rate(session)'],
  2255. groupBy: ['session.status'],
  2256. interval: '5m',
  2257. project: [],
  2258. statsPeriod: '24h',
  2259. }),
  2260. })
  2261. )
  2262. );
  2263. });
  2264. it('displays the correct options for area chart', async function () {
  2265. renderTestComponent({
  2266. orgFeatures: releaseHealthFeatureFlags,
  2267. });
  2268. expect(
  2269. await screen.findByText('Releases (sessions, crash rates)')
  2270. ).toBeInTheDocument();
  2271. // change dataset to releases
  2272. userEvent.click(screen.getByLabelText(/releases/i));
  2273. userEvent.click(screen.getByText('Table'));
  2274. userEvent.click(screen.getByText('Line Chart'));
  2275. expect(screen.getByText('crash_free_rate(…)')).toBeInTheDocument();
  2276. expect(screen.getByText(`session`)).toBeInTheDocument();
  2277. userEvent.click(screen.getByText('crash_free_rate(…)'));
  2278. expect(screen.getByText('count_unique(…)')).toBeInTheDocument();
  2279. userEvent.click(screen.getByText('count_unique(…)'));
  2280. expect(screen.getByText('user')).toBeInTheDocument();
  2281. });
  2282. it('sets widgetType to release', async function () {
  2283. renderTestComponent({
  2284. orgFeatures: releaseHealthFeatureFlags,
  2285. });
  2286. userEvent.click(await screen.findByText('Releases (sessions, crash rates)'));
  2287. expect(metricsDataMock).toHaveBeenCalled();
  2288. expect(screen.getByLabelText(/Releases/i)).toBeChecked();
  2289. });
  2290. it('does not display "add an equation" button', async function () {
  2291. const widget: Widget = {
  2292. title: 'Release Widget',
  2293. displayType: DisplayType.TABLE,
  2294. widgetType: WidgetType.RELEASE,
  2295. queries: [
  2296. {
  2297. name: 'errors',
  2298. conditions: 'event.type:error',
  2299. fields: ['sdk.name', 'count()'],
  2300. columns: ['sdk.name'],
  2301. aggregates: ['count()'],
  2302. orderby: '-sdk.name',
  2303. },
  2304. ],
  2305. interval: '1d',
  2306. id: '1',
  2307. };
  2308. const dashboard = mockDashboard({widgets: [widget]});
  2309. renderTestComponent({
  2310. orgFeatures: releaseHealthFeatureFlags,
  2311. dashboard,
  2312. params: {
  2313. widgetIndex: '0',
  2314. },
  2315. });
  2316. // Select line chart display
  2317. userEvent.click(await screen.findByText('Table'));
  2318. userEvent.click(screen.getByText('Line Chart'));
  2319. await waitFor(() =>
  2320. expect(screen.queryByLabelText('Add an Equation')).not.toBeInTheDocument()
  2321. );
  2322. });
  2323. it('render release dataset disabled when the display type is world map', async function () {
  2324. renderTestComponent({
  2325. query: {
  2326. source: DashboardWidgetSource.DISCOVERV2,
  2327. },
  2328. orgFeatures: releaseHealthFeatureFlags,
  2329. });
  2330. userEvent.click(await screen.findByText('Table'));
  2331. userEvent.click(screen.getByText('World Map'));
  2332. await waitFor(() => expect(screen.getByLabelText(/Releases/)).toBeDisabled());
  2333. expect(
  2334. screen.getByRole('radio', {
  2335. name: 'Select Errors and Transactions',
  2336. })
  2337. ).toBeEnabled();
  2338. expect(
  2339. screen.getByRole('radio', {
  2340. name: 'Select Issues (States, Assignment, Time, etc.)',
  2341. })
  2342. ).toBeDisabled();
  2343. });
  2344. it('renders with a release search bar', async function () {
  2345. renderTestComponent({
  2346. orgFeatures: releaseHealthFeatureFlags,
  2347. });
  2348. userEvent.type(
  2349. await screen.findByPlaceholderText('Search for events, users, tags, and more'),
  2350. 'session.status:'
  2351. );
  2352. await waitFor(() => {
  2353. expect(screen.getByText("isn't supported here.")).toBeInTheDocument();
  2354. });
  2355. userEvent.click(screen.getByText('Releases (sessions, crash rates)'));
  2356. userEvent.click(
  2357. screen.getByPlaceholderText(
  2358. 'Search for release version, session status, and more'
  2359. )
  2360. );
  2361. expect(await screen.findByText('environment')).toBeInTheDocument();
  2362. expect(screen.getByText('project')).toBeInTheDocument();
  2363. expect(screen.getByText('release')).toBeInTheDocument();
  2364. });
  2365. it('adds a function when the only column chosen in a table is a tag', async function () {
  2366. renderTestComponent({
  2367. orgFeatures: releaseHealthFeatureFlags,
  2368. });
  2369. userEvent.click(await screen.findByText('Releases (sessions, crash rates)'));
  2370. await selectEvent.select(screen.getByText('crash_free_rate(…)'), 'environment');
  2371. // 1 in the table header, 1 in the column selector, and 1 in the sort by
  2372. expect(screen.getAllByText(/crash_free_rate/)).toHaveLength(3);
  2373. expect(screen.getAllByText('environment')).toHaveLength(2);
  2374. });
  2375. });
  2376. describe('Widget Library', function () {
  2377. it('renders', async function () {
  2378. renderTestComponent();
  2379. expect(await screen.findByText('Widget Library')).toBeInTheDocument();
  2380. });
  2381. it('only opens the modal when the query data is changed', async function () {
  2382. const mockModal = jest.spyOn(modals, 'openWidgetBuilderOverwriteModal');
  2383. renderTestComponent();
  2384. await screen.findByText('Widget Library');
  2385. userEvent.click(screen.getByText('Duration Distribution'));
  2386. // Widget Library, Builder title, and Chart title
  2387. expect(await screen.findAllByText('Duration Distribution')).toHaveLength(3);
  2388. // Confirm modal doesn't open because no changes were made
  2389. expect(mockModal).not.toHaveBeenCalled();
  2390. userEvent.click(screen.getAllByLabelText('Remove this Y-Axis')[0]);
  2391. userEvent.click(screen.getByText('High Throughput Transactions'));
  2392. // Should not have overwritten widget data, and confirm modal should open
  2393. expect(await screen.findAllByText('Duration Distribution')).toHaveLength(3);
  2394. expect(mockModal).toHaveBeenCalled();
  2395. });
  2396. });
  2397. describe('group by field', function () {
  2398. it('does not contain functions as options', async function () {
  2399. renderTestComponent({
  2400. query: {displayType: 'line'},
  2401. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  2402. });
  2403. await screen.findByText('Group your results');
  2404. expect(screen.getByText('Select group')).toBeInTheDocument();
  2405. userEvent.click(screen.getByText('Select group'));
  2406. // Only one f(x) field set in the y-axis selector
  2407. expect(screen.getByText('f(x)')).toBeInTheDocument();
  2408. });
  2409. it('adds more fields when Add Group is clicked', async function () {
  2410. renderTestComponent({
  2411. query: {displayType: 'line'},
  2412. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  2413. });
  2414. await screen.findByText('Group your results');
  2415. userEvent.click(screen.getByText('Add Group'));
  2416. expect(await screen.findAllByText('Select group')).toHaveLength(2);
  2417. });
  2418. it("doesn't reset group by when changing y-axis", async function () {
  2419. renderTestComponent({
  2420. query: {displayType: 'line'},
  2421. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  2422. });
  2423. await selectEvent.select(await screen.findByText('Select group'), 'project');
  2424. userEvent.click(screen.getAllByText('count()')[0], undefined, {skipHover: true});
  2425. userEvent.click(screen.getByText(/count_unique/), undefined, {skipHover: true});
  2426. expect(await screen.findByText('project')).toBeInTheDocument();
  2427. });
  2428. it("doesn't erase the selection when switching to another time series", async function () {
  2429. renderTestComponent({
  2430. query: {displayType: 'line'},
  2431. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  2432. });
  2433. await selectEvent.select(await screen.findByText('Select group'), 'project');
  2434. userEvent.click(screen.getByText('Line Chart'));
  2435. userEvent.click(screen.getByText('Area Chart'));
  2436. expect(await screen.findByText('project')).toBeInTheDocument();
  2437. });
  2438. it('sends a top N request when a grouping is selected', async function () {
  2439. renderTestComponent({
  2440. query: {displayType: 'line'},
  2441. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  2442. });
  2443. userEvent.click(await screen.findByText('Group your results'));
  2444. userEvent.type(screen.getByText('Select group'), 'project{enter}');
  2445. await waitFor(() =>
  2446. expect(eventsStatsMock).toHaveBeenNthCalledWith(
  2447. 2,
  2448. '/organizations/org-slug/events-stats/',
  2449. expect.objectContaining({
  2450. query: expect.objectContaining({
  2451. query: '',
  2452. yAxis: ['count()'],
  2453. field: ['project', 'count()'],
  2454. topEvents: TOP_N,
  2455. orderby: '-count()',
  2456. }),
  2457. })
  2458. )
  2459. );
  2460. });
  2461. it('allows deleting groups until there is one left', async function () {
  2462. renderTestComponent({
  2463. query: {displayType: 'line'},
  2464. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  2465. });
  2466. await screen.findByText('Group your results');
  2467. userEvent.click(screen.getByText('Add Group'));
  2468. expect(screen.getAllByLabelText('Remove group')).toHaveLength(2);
  2469. userEvent.click(screen.getAllByLabelText('Remove group')[1]);
  2470. await waitFor(() =>
  2471. expect(screen.queryByLabelText('Remove group')).not.toBeInTheDocument()
  2472. );
  2473. });
  2474. it("display 'remove' and 'drag to reorder' buttons", async function () {
  2475. renderTestComponent({
  2476. query: {displayType: 'line'},
  2477. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  2478. });
  2479. await screen.findByText('Select group');
  2480. expect(screen.queryByLabelText('Remove group')).not.toBeInTheDocument();
  2481. await selectEvent.select(screen.getByText('Select group'), 'project');
  2482. expect(screen.getByLabelText('Remove group')).toBeInTheDocument();
  2483. expect(screen.queryByLabelText('Drag to reorder')).not.toBeInTheDocument();
  2484. userEvent.click(screen.getByText('Add Group'));
  2485. expect(screen.getAllByLabelText('Remove group')).toHaveLength(2);
  2486. expect(screen.getAllByLabelText('Drag to reorder')).toHaveLength(2);
  2487. });
  2488. it.todo(
  2489. 'Since simulate drag and drop with RTL is not recommended because of browser layout, remember to create acceptance test for this'
  2490. );
  2491. });
  2492. describe('limit field', function () {
  2493. it('renders if groupBy value is present', async function () {
  2494. const handleSave = jest.fn();
  2495. renderTestComponent({
  2496. query: {displayType: 'line'},
  2497. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  2498. onSave: handleSave,
  2499. });
  2500. await selectEvent.select(await screen.findByText('Select group'), 'project');
  2501. expect(screen.getByText('Limit to 5 results')).toBeInTheDocument();
  2502. userEvent.click(screen.getByText('Add Widget'));
  2503. await waitFor(() =>
  2504. expect(handleSave).toHaveBeenCalledWith([
  2505. expect.objectContaining({
  2506. limit: 5,
  2507. }),
  2508. ])
  2509. );
  2510. });
  2511. it('update value', async function () {
  2512. renderTestComponent({
  2513. query: {displayType: 'line'},
  2514. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  2515. });
  2516. await selectEvent.select(await screen.findByText('Select group'), 'project');
  2517. userEvent.click(screen.getByText('Limit to 5 results'));
  2518. userEvent.click(screen.getByText('Limit to 2 results'));
  2519. await waitFor(() =>
  2520. expect(eventsStatsMock).toHaveBeenCalledWith(
  2521. '/organizations/org-slug/events-stats/',
  2522. expect.objectContaining({
  2523. query: expect.objectContaining({
  2524. query: '',
  2525. yAxis: ['count()'],
  2526. field: ['project', 'count()'],
  2527. topEvents: 2,
  2528. orderby: '-count()',
  2529. }),
  2530. })
  2531. )
  2532. );
  2533. });
  2534. it('gets removed if no groupBy value', async function () {
  2535. renderTestComponent({
  2536. query: {displayType: 'line'},
  2537. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  2538. });
  2539. await selectEvent.select(await screen.findByText('Select group'), 'project');
  2540. expect(screen.getByText('Limit to 5 results')).toBeInTheDocument();
  2541. userEvent.click(screen.getByLabelText('Remove group'));
  2542. await waitFor(() =>
  2543. expect(screen.queryByText('Limit to 5 results')).not.toBeInTheDocument()
  2544. );
  2545. });
  2546. it('applies a limit when switching from a table to timeseries chart with grouping', async function () {
  2547. const widget: Widget = {
  2548. displayType: DisplayType.TABLE,
  2549. interval: '1d',
  2550. queries: [
  2551. {
  2552. name: 'Test Widget',
  2553. fields: ['count()', 'count_unique(user)', 'epm()', 'project'],
  2554. columns: ['project'],
  2555. aggregates: ['count()', 'count_unique(user)', 'epm()'],
  2556. conditions: '',
  2557. orderby: '',
  2558. },
  2559. ],
  2560. title: 'Transactions',
  2561. id: '1',
  2562. };
  2563. const dashboard = mockDashboard({widgets: [widget]});
  2564. renderTestComponent({
  2565. dashboard,
  2566. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  2567. params: {
  2568. widgetIndex: '0',
  2569. },
  2570. });
  2571. userEvent.click(await screen.findByText('Table'));
  2572. userEvent.click(screen.getByText('Line Chart'));
  2573. expect(screen.getByText('Limit to 3 results')).toBeInTheDocument();
  2574. expect(eventsStatsMock).toHaveBeenCalledWith(
  2575. '/organizations/org-slug/events-stats/',
  2576. expect.objectContaining({
  2577. query: expect.objectContaining({
  2578. topEvents: 3,
  2579. }),
  2580. })
  2581. );
  2582. });
  2583. it('persists the limit when switching between timeseries charts', async function () {
  2584. const widget: Widget = {
  2585. displayType: DisplayType.AREA,
  2586. interval: '1d',
  2587. queries: [
  2588. {
  2589. name: 'Test Widget',
  2590. fields: ['count()', 'count_unique(user)', 'epm()', 'project'],
  2591. columns: ['project'],
  2592. aggregates: ['count()', 'count_unique(user)', 'epm()'],
  2593. conditions: '',
  2594. orderby: '',
  2595. },
  2596. ],
  2597. title: 'Transactions',
  2598. id: '1',
  2599. limit: 1,
  2600. };
  2601. const dashboard = mockDashboard({widgets: [widget]});
  2602. renderTestComponent({
  2603. dashboard,
  2604. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  2605. params: {
  2606. widgetIndex: '0',
  2607. },
  2608. });
  2609. userEvent.click(await screen.findByText('Area Chart'));
  2610. userEvent.click(screen.getByText('Line Chart'));
  2611. expect(screen.getByText('Limit to 1 result')).toBeInTheDocument();
  2612. expect(eventsStatsMock).toHaveBeenCalledWith(
  2613. '/organizations/org-slug/events-stats/',
  2614. expect.objectContaining({
  2615. query: expect.objectContaining({
  2616. topEvents: 1,
  2617. }),
  2618. })
  2619. );
  2620. });
  2621. it('unsets the limit when going from timeseries to table', async function () {
  2622. const widget: Widget = {
  2623. displayType: DisplayType.AREA,
  2624. interval: '1d',
  2625. queries: [
  2626. {
  2627. name: 'Test Widget',
  2628. fields: ['count()', 'count_unique(user)', 'epm()', 'project'],
  2629. columns: ['project'],
  2630. aggregates: ['count()', 'count_unique(user)', 'epm()'],
  2631. conditions: '',
  2632. orderby: '',
  2633. },
  2634. ],
  2635. title: 'Transactions',
  2636. id: '1',
  2637. limit: 1,
  2638. };
  2639. const dashboard = mockDashboard({widgets: [widget]});
  2640. renderTestComponent({
  2641. dashboard,
  2642. orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
  2643. params: {
  2644. widgetIndex: '0',
  2645. },
  2646. });
  2647. userEvent.click(await screen.findByText('Area Chart'));
  2648. userEvent.click(screen.getByText('Table'));
  2649. expect(screen.queryByText('Limit to 1 result')).not.toBeInTheDocument();
  2650. expect(eventsv2Mock).toHaveBeenCalledWith(
  2651. '/organizations/org-slug/eventsv2/',
  2652. expect.objectContaining({
  2653. query: expect.objectContaining({
  2654. topEvents: undefined,
  2655. }),
  2656. })
  2657. );
  2658. });
  2659. });
  2660. });
  2661. describe('with events', function () {
  2662. it('should properly query for table fields', async function () {
  2663. const defaultWidgetQuery = {
  2664. name: '',
  2665. fields: ['title', 'count()'],
  2666. columns: ['title'],
  2667. aggregates: ['count()'],
  2668. conditions: '',
  2669. orderby: '',
  2670. };
  2671. const defaultTableColumns = ['title', 'count()', 'count_unique(user)', 'epm()'];
  2672. renderTestComponent({
  2673. query: {
  2674. source: DashboardWidgetSource.DISCOVERV2,
  2675. defaultWidgetQuery: urlEncode(defaultWidgetQuery),
  2676. displayType: DisplayType.LINE,
  2677. defaultTableColumns,
  2678. },
  2679. orgFeatures: [...defaultOrgFeatures, 'discover-frontend-use-events-endpoint'],
  2680. });
  2681. expect(await screen.findByText('Line Chart')).toBeInTheDocument();
  2682. userEvent.click(screen.getByText('Line Chart'));
  2683. userEvent.click(screen.getByText('Table'));
  2684. await waitFor(() => {
  2685. expect(eventsMock).toHaveBeenLastCalledWith(
  2686. '/organizations/org-slug/events/',
  2687. expect.objectContaining({
  2688. query: expect.objectContaining({
  2689. field: defaultTableColumns,
  2690. }),
  2691. })
  2692. );
  2693. });
  2694. });
  2695. describe('Sort by selectors', function () {
  2696. it('ordering by column uses field form when selecting orderby', async function () {
  2697. const widget: Widget = {
  2698. id: '1',
  2699. title: 'Test Widget',
  2700. interval: '5m',
  2701. displayType: DisplayType.TABLE,
  2702. queries: [
  2703. {
  2704. name: 'errors',
  2705. conditions: 'event.type:error',
  2706. fields: ['count()'],
  2707. aggregates: ['count()'],
  2708. columns: ['project'],
  2709. orderby: '-project',
  2710. },
  2711. ],
  2712. };
  2713. const dashboard = mockDashboard({widgets: [widget]});
  2714. renderTestComponent({
  2715. orgFeatures: [
  2716. ...defaultOrgFeatures,
  2717. 'new-widget-builder-experience-design',
  2718. 'discover-frontend-use-events-endpoint',
  2719. ],
  2720. dashboard,
  2721. params: {
  2722. widgetIndex: '0',
  2723. },
  2724. });
  2725. await waitFor(async () => {
  2726. expect(await screen.findAllByText('project')).toHaveLength(3);
  2727. });
  2728. await selectEvent.select(screen.getAllByText('project')[2], 'count()');
  2729. await waitFor(() => {
  2730. expect(eventsMock).toHaveBeenCalledWith(
  2731. '/organizations/org-slug/events/',
  2732. expect.objectContaining({
  2733. query: expect.objectContaining({
  2734. sort: ['-count()'],
  2735. }),
  2736. })
  2737. );
  2738. });
  2739. });
  2740. it('hides Custom Equation input and resets orderby when switching to table', async function () {
  2741. renderTestComponent({
  2742. orgFeatures: [
  2743. ...defaultOrgFeatures,
  2744. 'new-widget-builder-experience-design',
  2745. 'discover-frontend-use-events-endpoint',
  2746. ],
  2747. query: {
  2748. source: DashboardWidgetSource.DASHBOARDS,
  2749. displayType: DisplayType.LINE,
  2750. },
  2751. });
  2752. await selectEvent.select(await screen.findByText('Select group'), 'project');
  2753. expect(screen.getAllByText('count()')).toHaveLength(2);
  2754. await selectEvent.select(screen.getAllByText('count()')[1], 'Custom Equation');
  2755. userEvent.paste(
  2756. screen.getByPlaceholderText('Enter Equation'),
  2757. 'count_unique(user) * 2'
  2758. );
  2759. userEvent.keyboard('{enter}');
  2760. // Switch the display type to Table
  2761. userEvent.click(screen.getByText('Line Chart'));
  2762. userEvent.click(screen.getByText('Table'));
  2763. expect(screen.getAllByText('count()')).toHaveLength(2);
  2764. expect(screen.queryByPlaceholderText('Enter Equation')).not.toBeInTheDocument();
  2765. await waitFor(() => {
  2766. expect(eventsMock).toHaveBeenCalledWith(
  2767. '/organizations/org-slug/events/',
  2768. expect.objectContaining({
  2769. query: expect.objectContaining({
  2770. sort: ['-count()'],
  2771. }),
  2772. })
  2773. );
  2774. });
  2775. });
  2776. });
  2777. describe('Widget creation coming from other verticals', function () {
  2778. it('shows the correct orderby when switching from a line chart to table', async function () {
  2779. const defaultWidgetQuery = {
  2780. name: '',
  2781. fields: ['count_unique(user)'],
  2782. columns: [],
  2783. aggregates: ['count_unique(user)'],
  2784. conditions: '',
  2785. orderby: 'count_unique(user)',
  2786. };
  2787. const defaultTableColumns = ['title', 'count_unique(user)'];
  2788. renderTestComponent({
  2789. orgFeatures: [
  2790. ...defaultOrgFeatures,
  2791. 'new-widget-builder-experience-design',
  2792. 'discover-frontend-use-events-endpoint',
  2793. ],
  2794. query: {
  2795. source: DashboardWidgetSource.DISCOVERV2,
  2796. defaultWidgetQuery: urlEncode(defaultWidgetQuery),
  2797. displayType: DisplayType.LINE,
  2798. defaultTableColumns,
  2799. },
  2800. });
  2801. userEvent.click(await screen.findByText('Line Chart'));
  2802. userEvent.click(screen.getByText('Table'));
  2803. expect(screen.getByText('count_unique(user)')).toBeInTheDocument();
  2804. await waitFor(() => {
  2805. expect(eventsMock).toHaveBeenLastCalledWith(
  2806. '/organizations/org-slug/events/',
  2807. expect.objectContaining({
  2808. query: expect.objectContaining({
  2809. field: defaultTableColumns,
  2810. sort: ['count_unique(user)'],
  2811. }),
  2812. })
  2813. );
  2814. });
  2815. });
  2816. });
  2817. describe('Custom Performance Metrics', function () {
  2818. it('can choose a custom measurement', async function () {
  2819. measurementsMetaMock = MockApiClient.addMockResponse({
  2820. url: '/organizations/org-slug/measurements-meta/',
  2821. method: 'GET',
  2822. body: {'measurements.custom.measurement': {functions: ['p99']}},
  2823. });
  2824. eventsMock = MockApiClient.addMockResponse({
  2825. url: '/organizations/org-slug/events/',
  2826. method: 'GET',
  2827. statusCode: 200,
  2828. body: {
  2829. meta: {
  2830. fields: {'p99(measurements.total.db.calls)': 'duration'},
  2831. isMetricsData: true,
  2832. },
  2833. data: [{'p99(measurements.total.db.calls)': 10}],
  2834. },
  2835. });
  2836. const {router} = renderTestComponent({
  2837. query: {source: DashboardWidgetSource.DISCOVERV2},
  2838. dashboard: testDashboard,
  2839. orgFeatures: [...defaultOrgFeatures, 'discover-frontend-use-events-endpoint'],
  2840. });
  2841. expect(await screen.findAllByText('Custom Widget')).toHaveLength(2);
  2842. // 1 in the table header, 1 in the column selector, 1 in the sort field
  2843. const countFields = screen.getAllByText('count()');
  2844. expect(countFields).toHaveLength(3);
  2845. await selectEvent.select(countFields[1], ['p99(…)']);
  2846. await selectEvent.select(screen.getByText('transaction.duration'), [
  2847. 'measurements.custom.measurement',
  2848. ]);
  2849. userEvent.click(screen.getByText('Add Widget'));
  2850. await waitFor(() => {
  2851. expect(router.push).toHaveBeenCalledWith(
  2852. expect.objectContaining({
  2853. pathname: '/organizations/org-slug/dashboard/2/',
  2854. query: {
  2855. displayType: 'table',
  2856. interval: '5m',
  2857. title: 'Custom Widget',
  2858. queryNames: [''],
  2859. queryConditions: [''],
  2860. queryFields: ['p99(measurements.custom.measurement)'],
  2861. queryOrderby: '-p99(measurements.custom.measurement)',
  2862. start: null,
  2863. end: null,
  2864. statsPeriod: '24h',
  2865. utc: false,
  2866. project: [],
  2867. environment: [],
  2868. },
  2869. })
  2870. );
  2871. });
  2872. });
  2873. it('raises an alert banner and disables saving widget if widget result is not metrics data and widget is using custom measurements', async function () {
  2874. eventsMock = MockApiClient.addMockResponse({
  2875. url: '/organizations/org-slug/events/',
  2876. method: 'GET',
  2877. statusCode: 200,
  2878. body: {
  2879. meta: {
  2880. fields: {'p99(measurements.custom.measurement)': 'duration'},
  2881. isMetricsData: false,
  2882. },
  2883. data: [{'p99(measurements.custom.measurement)': 10}],
  2884. },
  2885. });
  2886. const defaultWidgetQuery = {
  2887. name: '',
  2888. fields: ['p99(measurements.custom.measurement)'],
  2889. columns: [],
  2890. aggregates: ['p99(measurements.custom.measurement)'],
  2891. conditions: 'user:test.user@sentry.io',
  2892. orderby: '',
  2893. };
  2894. const defaultTableColumns = ['p99(measurements.custom.measurement)'];
  2895. renderTestComponent({
  2896. query: {
  2897. source: DashboardWidgetSource.DISCOVERV2,
  2898. defaultWidgetQuery: urlEncode(defaultWidgetQuery),
  2899. displayType: DisplayType.TABLE,
  2900. defaultTableColumns,
  2901. },
  2902. orgFeatures: [
  2903. ...defaultOrgFeatures,
  2904. 'discover-frontend-use-events-endpoint',
  2905. 'dashboards-mep',
  2906. ],
  2907. });
  2908. await waitFor(() => {
  2909. expect(measurementsMetaMock).toHaveBeenCalled();
  2910. });
  2911. await waitFor(() => {
  2912. expect(eventsMock).toHaveBeenCalled();
  2913. });
  2914. screen.getByText('You have inputs that are incompatible with');
  2915. expect(screen.getByText('Add Widget').closest('button')).toBeDisabled();
  2916. });
  2917. it('raises an alert banner if widget result is not metrics data', async function () {
  2918. eventsMock = MockApiClient.addMockResponse({
  2919. url: '/organizations/org-slug/events/',
  2920. method: 'GET',
  2921. statusCode: 200,
  2922. body: {
  2923. meta: {
  2924. fields: {'p99(measurements.lcp)': 'duration'},
  2925. isMetricsData: false,
  2926. },
  2927. data: [{'p99(measurements.lcp)': 10}],
  2928. },
  2929. });
  2930. const defaultWidgetQuery = {
  2931. name: '',
  2932. fields: ['p99(measurements.lcp)'],
  2933. columns: [],
  2934. aggregates: ['p99(measurements.lcp)'],
  2935. conditions: 'user:test.user@sentry.io',
  2936. orderby: '',
  2937. };
  2938. const defaultTableColumns = ['p99(measurements.lcp)'];
  2939. renderTestComponent({
  2940. query: {
  2941. source: DashboardWidgetSource.DISCOVERV2,
  2942. defaultWidgetQuery: urlEncode(defaultWidgetQuery),
  2943. displayType: DisplayType.TABLE,
  2944. defaultTableColumns,
  2945. },
  2946. orgFeatures: [
  2947. ...defaultOrgFeatures,
  2948. 'discover-frontend-use-events-endpoint',
  2949. 'dashboards-mep',
  2950. ],
  2951. });
  2952. await waitFor(() => {
  2953. expect(measurementsMetaMock).toHaveBeenCalled();
  2954. });
  2955. await waitFor(() => {
  2956. expect(eventsMock).toHaveBeenCalled();
  2957. });
  2958. screen.getByText('Your selection is only applicable to');
  2959. });
  2960. it('does not raise an alert banner if widget result is not metrics data but widget contains error fields', async function () {
  2961. eventsMock = MockApiClient.addMockResponse({
  2962. url: '/organizations/org-slug/events/',
  2963. method: 'GET',
  2964. statusCode: 200,
  2965. body: {
  2966. meta: {
  2967. fields: {'p99(measurements.lcp)': 'duration'},
  2968. isMetricsData: false,
  2969. },
  2970. data: [{'p99(measurements.lcp)': 10}],
  2971. },
  2972. });
  2973. const defaultWidgetQuery = {
  2974. name: '',
  2975. fields: ['p99(measurements.lcp)'],
  2976. columns: ['error.handled'],
  2977. aggregates: ['p99(measurements.lcp)'],
  2978. conditions: 'user:test.user@sentry.io',
  2979. orderby: '',
  2980. };
  2981. const defaultTableColumns = ['p99(measurements.lcp)'];
  2982. renderTestComponent({
  2983. query: {
  2984. source: DashboardWidgetSource.DISCOVERV2,
  2985. defaultWidgetQuery: urlEncode(defaultWidgetQuery),
  2986. displayType: DisplayType.TABLE,
  2987. defaultTableColumns,
  2988. },
  2989. orgFeatures: [
  2990. ...defaultOrgFeatures,
  2991. 'discover-frontend-use-events-endpoint',
  2992. 'dashboards-mep',
  2993. ],
  2994. });
  2995. await waitFor(() => {
  2996. expect(measurementsMetaMock).toHaveBeenCalled();
  2997. });
  2998. await waitFor(() => {
  2999. expect(eventsMock).toHaveBeenCalled();
  3000. });
  3001. expect(
  3002. screen.queryByText('Your selection is only applicable to')
  3003. ).not.toBeInTheDocument();
  3004. });
  3005. it('only displays custom measurements in supported functions', async function () {
  3006. measurementsMetaMock = MockApiClient.addMockResponse({
  3007. url: '/organizations/org-slug/measurements-meta/',
  3008. method: 'GET',
  3009. body: {
  3010. 'measurements.custom.measurement': {functions: ['p99']},
  3011. 'measurements.another.custom.measurement': {functions: ['p95']},
  3012. },
  3013. });
  3014. renderTestComponent({
  3015. query: {source: DashboardWidgetSource.DISCOVERV2},
  3016. dashboard: testDashboard,
  3017. orgFeatures: [...defaultOrgFeatures, 'discover-frontend-use-events-endpoint'],
  3018. });
  3019. expect(await screen.findAllByText('Custom Widget')).toHaveLength(2);
  3020. await selectEvent.select(screen.getAllByText('count()')[1], ['p99(…)']);
  3021. userEvent.click(screen.getByText('transaction.duration'));
  3022. screen.getByText('measurements.custom.measurement');
  3023. expect(
  3024. screen.queryByText('measurements.another.custom.measurement')
  3025. ).not.toBeInTheDocument();
  3026. await selectEvent.select(screen.getAllByText('p99(…)')[0], ['p95(…)']);
  3027. userEvent.click(screen.getByText('transaction.duration'));
  3028. screen.getByText('measurements.another.custom.measurement');
  3029. expect(
  3030. screen.queryByText('measurements.custom.measurement')
  3031. ).not.toBeInTheDocument();
  3032. });
  3033. });
  3034. });
  3035. });