123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031 |
- import {urlEncode} from '@sentry/utils';
- import {MetricsFieldFixture} from 'sentry-fixture/metrics';
- import {ReleaseFixture} from 'sentry-fixture/release';
- import {SessionsFieldFixture} from 'sentry-fixture/sessions';
- import {TagsFixture} from 'sentry-fixture/tags';
- import {initializeOrg} from 'sentry-test/initializeOrg';
- import {
- act,
- fireEvent,
- render,
- renderGlobalModal,
- screen,
- userEvent,
- waitFor,
- } from 'sentry-test/reactTestingLibrary';
- import selectEvent from 'sentry-test/selectEvent';
- import * as modals from 'sentry/actionCreators/modal';
- import ProjectsStore from 'sentry/stores/projectsStore';
- import TagStore from 'sentry/stores/tagStore';
- import {TOP_N} from 'sentry/utils/discover/types';
- import type {DashboardDetails, Widget} from 'sentry/views/dashboards/types';
- import {
- DashboardWidgetSource,
- DisplayType,
- WidgetType,
- } from 'sentry/views/dashboards/types';
- import type {WidgetBuilderProps} from 'sentry/views/dashboards/widgetBuilder';
- import WidgetBuilder from 'sentry/views/dashboards/widgetBuilder';
- const defaultOrgFeatures = [
- 'performance-view',
- 'dashboards-edit',
- 'global-views',
- 'dashboards-mep',
- ];
- function mockDashboard(dashboard: Partial<DashboardDetails>): DashboardDetails {
- return {
- id: '1',
- title: 'Dashboard',
- createdBy: undefined,
- dateCreated: '2020-01-01T00:00:00.000Z',
- widgets: [],
- projects: [],
- filters: {},
- ...dashboard,
- };
- }
- function renderTestComponent({
- dashboard,
- query,
- orgFeatures,
- onSave,
- params,
- }: {
- dashboard?: WidgetBuilderProps['dashboard'];
- onSave?: WidgetBuilderProps['onSave'];
- orgFeatures?: string[];
- params?: Partial<WidgetBuilderProps['params']>;
- query?: Record<string, any>;
- } = {}) {
- const {organization, router, routerContext} = initializeOrg({
- organization: {
- features: orgFeatures ?? defaultOrgFeatures,
- },
- router: {
- location: {
- query: {
- source: DashboardWidgetSource.DASHBOARDS,
- ...query,
- },
- },
- },
- });
- ProjectsStore.loadInitialData(organization.projects);
- render(
- <WidgetBuilder
- route={{}}
- router={router}
- routes={router.routes}
- routeParams={router.params}
- location={router.location}
- dashboard={{
- id: 'new',
- title: 'Dashboard',
- createdBy: undefined,
- dateCreated: '2020-01-01T00:00:00.000Z',
- widgets: [],
- projects: [],
- filters: {},
- ...dashboard,
- }}
- onSave={onSave ?? jest.fn()}
- params={{
- orgId: organization.slug,
- dashboardId: dashboard?.id ?? 'new',
- ...params,
- }}
- />,
- {
- context: routerContext,
- organization,
- }
- );
- return {router};
- }
- /**
- * This test suite contains tests that test the generic interactions
- * between most components in the WidgetBuilder. Tests for the
- * SortBy step can be found in (and should be added to)
- * ./widgetBuilderSortBy.spec.tsx and tests for specific dataset
- * behaviour can be found (and should be added to) ./widgetBuilderDataset.spec.tsx.
- * The test files are broken up to allow better parallelization
- * in CI (we currently parallelize files).
- */
- describe('WidgetBuilder', function () {
- const untitledDashboard: DashboardDetails = {
- id: '1',
- title: 'Untitled Dashboard',
- createdBy: undefined,
- dateCreated: '2020-01-01T00:00:00.000Z',
- widgets: [],
- projects: [],
- filters: {},
- };
- const testDashboard: DashboardDetails = {
- id: '2',
- title: 'Test Dashboard',
- createdBy: undefined,
- dateCreated: '2020-01-01T00:00:00.000Z',
- widgets: [],
- projects: [],
- filters: {},
- };
- let eventsStatsMock: jest.Mock | undefined;
- let eventsMock: jest.Mock | undefined;
- let tagsMock: jest.Mock | undefined;
- beforeEach(function () {
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/dashboards/',
- body: [
- {...untitledDashboard, widgetDisplay: [DisplayType.TABLE]},
- {...testDashboard, widgetDisplay: [DisplayType.AREA]},
- ],
- });
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/dashboards/widgets/',
- method: 'POST',
- statusCode: 200,
- body: [],
- });
- eventsMock = MockApiClient.addMockResponse({
- url: '/organizations/org-slug/events/',
- method: 'GET',
- statusCode: 200,
- body: {
- meta: {fields: {}},
- data: [],
- },
- });
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/projects/',
- method: 'GET',
- body: [],
- });
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/recent-searches/',
- method: 'GET',
- body: [],
- });
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/recent-searches/',
- method: 'POST',
- body: [],
- });
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/issues/',
- method: 'GET',
- body: [],
- });
- eventsStatsMock = MockApiClient.addMockResponse({
- url: '/organizations/org-slug/events-stats/',
- body: [],
- });
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/tags/event.type/values/',
- body: [{count: 2, name: 'Nvidia 1080ti'}],
- });
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/users/',
- body: [],
- });
- MockApiClient.addMockResponse({
- method: 'GET',
- url: '/organizations/org-slug/sessions/',
- body: SessionsFieldFixture(`sum(session)`),
- });
- MockApiClient.addMockResponse({
- method: 'GET',
- url: '/organizations/org-slug/metrics/data/',
- body: MetricsFieldFixture('session.all'),
- });
- tagsMock = MockApiClient.addMockResponse({
- url: '/organizations/org-slug/tags/',
- method: 'GET',
- body: TagsFixture(),
- });
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/measurements-meta/',
- method: 'GET',
- body: {},
- });
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/tags/is/values/',
- method: 'GET',
- body: [],
- });
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/tags/transaction.duration/values/',
- method: 'GET',
- body: [],
- });
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/releases/',
- body: [],
- });
- TagStore.reset();
- });
- afterEach(function () {
- MockApiClient.clearMockResponses();
- jest.clearAllMocks();
- });
- it('no feature access', function () {
- renderTestComponent({orgFeatures: []});
- expect(screen.getByText("You don't have access to this feature")).toBeInTheDocument();
- });
- it('widget not found', async function () {
- const widget: Widget = {
- displayType: DisplayType.AREA,
- interval: '1d',
- queries: [
- {
- name: 'Known Users',
- fields: [],
- columns: [],
- aggregates: [],
- conditions: '',
- orderby: '-time',
- },
- {
- name: 'Anonymous Users',
- fields: [],
- columns: [],
- aggregates: [],
- conditions: '',
- orderby: '-time',
- },
- ],
- title: 'Transactions',
- id: '1',
- };
- const dashboard = mockDashboard({widgets: [widget]});
- renderTestComponent({
- dashboard,
- orgFeatures: ['dashboards-edit'],
- params: {
- widgetIndex: '2', // Out of bounds, only one widget
- },
- });
- expect(
- await screen.findByText('The widget you want to edit was not found.')
- ).toBeInTheDocument();
- });
- it('renders a widget not found message if the widget index url is not an integer', async function () {
- const widget: Widget = {
- displayType: DisplayType.AREA,
- interval: '1d',
- queries: [
- {
- name: 'Known Users',
- fields: [],
- columns: [],
- aggregates: [],
- conditions: '',
- orderby: '-time',
- },
- ],
- title: 'Transactions',
- id: '1',
- };
- const dashboard = mockDashboard({widgets: [widget]});
- renderTestComponent({
- dashboard,
- orgFeatures: ['dashboards-edit'],
- params: {
- widgetIndex: '0.5', // Invalid index
- },
- });
- expect(
- await screen.findByText('The widget you want to edit was not found.')
- ).toBeInTheDocument();
- });
- it('renders', async function () {
- renderTestComponent();
- // Header - Breadcrumbs
- expect(await screen.findByRole('link', {name: 'Dashboards'})).toHaveAttribute(
- 'href',
- '/organizations/org-slug/dashboards/'
- );
- expect(screen.getByRole('link', {name: 'Dashboard'})).toHaveAttribute(
- 'href',
- '/organizations/org-slug/dashboards/new/'
- );
- expect(screen.getByText('Widget Builder')).toBeInTheDocument();
- // Header - Widget Title
- expect(screen.getByText('Custom Widget')).toBeInTheDocument();
- // Footer - Actions
- expect(screen.getByLabelText('Cancel')).toBeInTheDocument();
- expect(screen.getByLabelText('Add Widget')).toBeInTheDocument();
- // Content - Step 1
- expect(
- screen.getByRole('heading', {name: 'Choose your dataset'})
- ).toBeInTheDocument();
- expect(screen.getByLabelText('Errors and Transactions')).toBeChecked();
- // Content - Step 2
- expect(
- screen.getByRole('heading', {name: 'Choose your visualization'})
- ).toBeInTheDocument();
- // Content - Step 3
- expect(
- screen.getByRole('heading', {name: 'Choose your columns'})
- ).toBeInTheDocument();
- // Content - Step 4
- expect(
- screen.getByRole('heading', {name: 'Filter your results'})
- ).toBeInTheDocument();
- // Content - Step 5
- expect(screen.getByRole('heading', {name: 'Sort by a column'})).toBeInTheDocument();
- });
- it('has links back to the new dashboard if creating', async function () {
- // Dashboard has undefined dashboardId when creating from a new dashboard
- // because of route setup
- renderTestComponent({params: {dashboardId: undefined}});
- expect(await screen.findByLabelText('Cancel')).toHaveAttribute(
- 'href',
- '/organizations/org-slug/dashboards/new/'
- );
- });
- it('renders new design', async function () {
- renderTestComponent({
- orgFeatures: [...defaultOrgFeatures],
- });
- // Switch to line chart for time series
- await userEvent.click(screen.getByText('Table'));
- await userEvent.click(screen.getByText('Line Chart'));
- // Header - Breadcrumbs
- expect(await screen.findByRole('link', {name: 'Dashboards'})).toHaveAttribute(
- 'href',
- '/organizations/org-slug/dashboards/'
- );
- expect(screen.getByRole('link', {name: 'Dashboard'})).toHaveAttribute(
- 'href',
- '/organizations/org-slug/dashboards/new/'
- );
- expect(screen.getByText('Widget Builder')).toBeInTheDocument();
- // Header - Widget Title
- expect(screen.getByText('Custom Widget')).toBeInTheDocument();
- // Footer - Actions
- expect(screen.getByLabelText('Cancel')).toBeInTheDocument();
- expect(screen.getByLabelText('Add Widget')).toBeInTheDocument();
- // Content - Step 1
- expect(
- screen.getByRole('heading', {name: 'Choose your dataset'})
- ).toBeInTheDocument();
- expect(screen.getByLabelText('Errors and Transactions')).toBeChecked();
- // Content - Step 2
- expect(
- screen.getByRole('heading', {name: 'Choose your visualization'})
- ).toBeInTheDocument();
- // Content - Step 3
- expect(
- screen.getByRole('heading', {name: 'Choose what to plot in the y-axis'})
- ).toBeInTheDocument();
- // Content - Step 4
- expect(
- screen.getByRole('heading', {name: 'Filter your results'})
- ).toBeInTheDocument();
- // Content - Step 5
- expect(screen.getByRole('heading', {name: 'Group your results'})).toBeInTheDocument();
- });
- it('can update the title', async function () {
- renderTestComponent({
- query: {source: DashboardWidgetSource.DISCOVERV2},
- });
- const customWidgetLabels = await screen.findByText('Custom Widget');
- // EditableText and chart title
- expect(customWidgetLabels).toBeInTheDocument();
- await userEvent.clear(screen.getByRole('textbox', {name: 'Widget title'}));
- await userEvent.click(screen.getByRole('textbox', {name: 'Widget title'}));
- await userEvent.paste('Unique Users');
- await userEvent.keyboard('{enter}');
- expect(screen.queryByText('Custom Widget')).not.toBeInTheDocument();
- expect(screen.getByText('Unique Users')).toBeInTheDocument();
- });
- it('can add query conditions', async function () {
- const {router} = renderTestComponent({
- query: {source: DashboardWidgetSource.DISCOVERV2},
- dashboard: testDashboard,
- });
- const search = await screen.findByTestId(/smart-search-input/);
- await userEvent.click(search);
- // Use fireEvent for performance reasons as this test suite is slow
- fireEvent.paste(search, {
- target: {value: 'color:blue'},
- clipboardData: {getData: () => 'color:blue'},
- });
- await userEvent.keyboard('{enter}');
- await userEvent.click(screen.getByText('Add Widget'));
- await waitFor(() => {
- expect(router.push).toHaveBeenCalledWith(
- expect.objectContaining({
- pathname: '/organizations/org-slug/dashboard/2/',
- query: {
- displayType: 'table',
- interval: '5m',
- title: 'Custom Widget',
- queryNames: [''],
- queryConditions: ['color:blue'],
- queryFields: ['count()'],
- queryOrderby: '-count()',
- start: null,
- end: null,
- statsPeriod: '24h',
- utc: null,
- project: [],
- environment: [],
- },
- })
- );
- });
- });
- it('can choose a field', async function () {
- const {router} = renderTestComponent({
- query: {source: DashboardWidgetSource.DISCOVERV2},
- dashboard: testDashboard,
- });
- expect(await screen.findByText('Custom Widget')).toBeInTheDocument();
- // No delete button as there is only one query.
- expect(screen.queryByLabelText('Remove query')).not.toBeInTheDocument();
- // 1 in the table header, 1 in the column selector, 1 in the sort field
- const countFields = screen.getAllByText('count()');
- expect(countFields).toHaveLength(3);
- await selectEvent.select(countFields[1], ['last_seen()']);
- await userEvent.click(screen.getByText('Add Widget'));
- await waitFor(() => {
- expect(router.push).toHaveBeenCalledWith(
- expect.objectContaining({
- pathname: '/organizations/org-slug/dashboard/2/',
- query: {
- displayType: 'table',
- interval: '5m',
- title: 'Custom Widget',
- queryNames: [''],
- queryConditions: [''],
- queryFields: ['last_seen()'],
- queryOrderby: '-last_seen()',
- start: null,
- end: null,
- statsPeriod: '24h',
- utc: null,
- project: [],
- environment: [],
- },
- })
- );
- });
- });
- it('can add additional fields', async function () {
- const handleSave = jest.fn();
- renderTestComponent({onSave: handleSave});
- await userEvent.click(await screen.findByText('Table'));
- // Select line chart display
- await userEvent.click(screen.getByText('Line Chart'));
- // Click the add overlay button
- await userEvent.click(screen.getByLabelText('Add Overlay'));
- await selectEvent.select(screen.getByText('(Required)'), ['count_unique(…)']);
- await userEvent.click(screen.getByLabelText('Add Widget'));
- await waitFor(() => {
- expect(handleSave).toHaveBeenCalledWith([
- expect.objectContaining({
- title: 'Custom Widget',
- displayType: DisplayType.LINE,
- interval: '5m',
- widgetType: WidgetType.DISCOVER,
- queries: [
- {
- conditions: '',
- fields: ['count()', 'count_unique(user)'],
- aggregates: ['count()', 'count_unique(user)'],
- fieldAliases: [],
- columns: [],
- orderby: '',
- name: '',
- },
- ],
- }),
- ]);
- });
- expect(handleSave).toHaveBeenCalledTimes(1);
- });
- it('can add equation fields', async function () {
- const handleSave = jest.fn();
- renderTestComponent({onSave: handleSave});
- await userEvent.click(await screen.findByText('Table'));
- // Select line chart display
- await userEvent.click(screen.getByText('Line Chart'));
- // Click the add an equation button
- await userEvent.click(screen.getByLabelText('Add an Equation'));
- expect(screen.getByPlaceholderText('Equation')).toBeInTheDocument();
- await userEvent.click(screen.getByPlaceholderText('Equation'));
- await userEvent.paste('count() + 100');
- await userEvent.click(screen.getByLabelText('Add Widget'));
- await waitFor(() => {
- expect(handleSave).toHaveBeenCalledWith([
- expect.objectContaining({
- title: 'Custom Widget',
- displayType: DisplayType.LINE,
- interval: '5m',
- widgetType: WidgetType.DISCOVER,
- queries: [
- {
- name: '',
- fields: ['count()', 'equation|count() + 100'],
- aggregates: ['count()', 'equation|count() + 100'],
- columns: [],
- fieldAliases: [],
- conditions: '',
- orderby: '',
- },
- ],
- }),
- ]);
- });
- expect(handleSave).toHaveBeenCalledTimes(1);
- });
- it('can respond to validation feedback', async function () {
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/dashboards/widgets/',
- method: 'POST',
- statusCode: 400,
- body: {
- title: ['This field may not be blank.'],
- },
- });
- renderTestComponent();
- await userEvent.click(await screen.findByText('Table'));
- const customWidgetLabels = await screen.findByText('Custom Widget');
- // EditableText and chart title
- expect(customWidgetLabels).toBeInTheDocument();
- await userEvent.clear(screen.getByRole('textbox', {name: 'Widget title'}));
- await userEvent.click(screen.getByText('Add Widget'));
- await screen.findByText('This field may not be blank.');
- });
- it('sets up widget data in edit correctly', async function () {
- const widget: Widget = {
- id: '1',
- title: 'Errors over time',
- interval: '5m',
- displayType: DisplayType.LINE,
- queries: [
- {
- name: 'errors',
- conditions: 'event.type:error',
- fields: ['count()', 'count_unique(id)'],
- aggregates: ['count()', 'count_unique(id)'],
- columns: [],
- orderby: '',
- },
- {
- name: 'csp',
- conditions: 'event.type:csp',
- fields: ['count()', 'count_unique(id)'],
- aggregates: ['count()', 'count_unique(id)'],
- columns: [],
- orderby: '',
- },
- ],
- };
- const dashboard = mockDashboard({widgets: [widget]});
- renderTestComponent({dashboard, params: {widgetIndex: '0'}});
- await screen.findByText('Line Chart');
- // Should be in edit 'mode'
- expect(await screen.findByText('Update Widget')).toBeInTheDocument();
- // Should set widget data up.
- expect(screen.getByText('Update Widget')).toBeInTheDocument();
- // Filters
- expect(
- screen.getAllByPlaceholderText('Search for events, users, tags, and more')
- ).toHaveLength(2);
- expect(screen.getByText('event.type:csp')).toBeInTheDocument();
- expect(screen.getByText('event.type:error')).toBeInTheDocument();
- // Y-axis
- expect(screen.getAllByRole('button', {name: 'Remove query'})).toHaveLength(2);
- expect(screen.getByText('count()')).toBeInTheDocument();
- expect(screen.getByText('count_unique(…)')).toBeInTheDocument();
- expect(screen.getByText('id')).toBeInTheDocument();
- // Expect events-stats endpoint to be called for each search conditions with
- // the same y-axis parameters
- expect(eventsStatsMock).toHaveBeenNthCalledWith(
- 1,
- '/organizations/org-slug/events-stats/',
- expect.objectContaining({
- query: expect.objectContaining({
- query: 'event.type:error',
- yAxis: ['count()', 'count_unique(id)'],
- }),
- })
- );
- expect(eventsStatsMock).toHaveBeenNthCalledWith(
- 2,
- '/organizations/org-slug/events-stats/',
- expect.objectContaining({
- query: expect.objectContaining({
- query: 'event.type:csp',
- yAxis: ['count()', 'count_unique(id)'],
- }),
- })
- );
- });
- it('can edit a widget', async function () {
- const widget: Widget = {
- id: '1',
- title: 'Errors over time',
- interval: '5m',
- displayType: DisplayType.LINE,
- queries: [
- {
- name: 'errors',
- conditions: 'event.type:error',
- fields: ['count()', 'count_unique(id)'],
- aggregates: ['count()', 'count_unique(id)'],
- columns: [],
- orderby: '',
- },
- {
- name: 'csp',
- conditions: 'event.type:csp',
- fields: ['count()', 'count_unique(id)'],
- aggregates: ['count()', 'count_unique(id)'],
- columns: [],
- orderby: '',
- },
- ],
- };
- const dashboard = mockDashboard({widgets: [widget]});
- const handleSave = jest.fn();
- renderTestComponent({onSave: handleSave, dashboard, params: {widgetIndex: '0'}});
- await screen.findByText('Line Chart');
- // Should be in edit 'mode'
- expect(screen.getByText('Update Widget')).toBeInTheDocument();
- const customWidgetLabels = screen.getByText(widget.title);
- // EditableText and chart title
- expect(customWidgetLabels).toBeInTheDocument();
- await userEvent.clear(screen.getByRole('textbox', {name: 'Widget title'}));
- await userEvent.click(screen.getByRole('textbox', {name: 'Widget title'}));
- await userEvent.paste('New Title');
- await userEvent.click(screen.getByRole('button', {name: 'Update Widget'}));
- await waitFor(() => {
- expect(handleSave).toHaveBeenCalledWith([
- expect.objectContaining({
- ...widget,
- title: 'New Title',
- }),
- ]);
- });
- expect(handleSave).toHaveBeenCalledTimes(1);
- });
- it('renders column inputs for table widgets', async function () {
- const widget: Widget = {
- id: '0',
- title: 'sdk usage',
- interval: '5m',
- displayType: DisplayType.TABLE,
- queries: [
- {
- name: 'errors',
- conditions: 'event.type:error',
- fields: ['sdk.name', 'count()'],
- columns: ['sdk.name'],
- aggregates: ['count()'],
- orderby: '',
- },
- ],
- };
- const dashboard = mockDashboard({widgets: [widget]});
- renderTestComponent({dashboard, params: {widgetIndex: '0'}});
- // Should be in edit 'mode'
- expect(await screen.findByText('Update Widget')).toBeInTheDocument();
- // Should set widget data up.
- expect(screen.getByText(widget.title)).toBeInTheDocument();
- expect(screen.getByText('Table')).toBeInTheDocument();
- expect(screen.getByLabelText('Search events')).toBeInTheDocument();
- // Should have an orderby select
- expect(screen.getByText('Sort by a column')).toBeInTheDocument();
- // Add a column, and choose a value,
- expect(screen.getByLabelText('Add a Column')).toBeInTheDocument();
- });
- it('can save table widgets', async function () {
- const widget: Widget = {
- id: '0',
- title: 'sdk usage',
- interval: '5m',
- displayType: DisplayType.TABLE,
- queries: [
- {
- name: 'errors',
- conditions: 'event.type:error',
- fields: ['sdk.name', 'count()'],
- columns: ['sdk.name'],
- aggregates: ['count()'],
- orderby: '-count()',
- },
- ],
- };
- const dashboard = mockDashboard({widgets: [widget]});
- const handleSave = jest.fn();
- renderTestComponent({dashboard, onSave: handleSave, params: {widgetIndex: '0'}});
- // Should be in edit 'mode'
- expect(await screen.findByText('Update Widget')).toBeInTheDocument();
- // Add a column, and choose a value,
- await userEvent.click(screen.getByLabelText('Add a Column'));
- await selectEvent.select(screen.getByText('(Required)'), 'trace');
- // Save widget
- await userEvent.click(screen.getByLabelText('Update Widget'));
- await waitFor(() => {
- expect(handleSave).toHaveBeenCalledWith([
- expect.objectContaining({
- id: '0',
- title: 'sdk usage',
- displayType: DisplayType.TABLE,
- interval: '5m',
- queries: [
- {
- name: 'errors',
- conditions: 'event.type:error',
- fields: ['sdk.name', 'count()', 'trace'],
- aggregates: ['count()'],
- columns: ['sdk.name', 'trace'],
- orderby: '-count()',
- fieldAliases: ['', '', ''],
- },
- ],
- widgetType: WidgetType.DISCOVER,
- }),
- ]);
- });
- expect(handleSave).toHaveBeenCalledTimes(1);
- });
- it('should properly query for table fields', async function () {
- const defaultWidgetQuery = {
- name: '',
- fields: ['title', 'count()'],
- columns: ['title'],
- aggregates: ['count()'],
- conditions: '',
- orderby: '',
- };
- const defaultTableColumns = ['title', 'count()', 'count_unique(user)', 'epm()'];
- renderTestComponent({
- query: {
- source: DashboardWidgetSource.DISCOVERV2,
- defaultWidgetQuery: urlEncode(defaultWidgetQuery),
- displayType: DisplayType.LINE,
- defaultTableColumns,
- },
- });
- expect(await screen.findByText('Line Chart')).toBeInTheDocument();
- await userEvent.click(screen.getByText('Line Chart'));
- await userEvent.click(screen.getByText('Table'));
- await waitFor(() => {
- expect(eventsMock).toHaveBeenLastCalledWith(
- '/organizations/org-slug/events/',
- expect.objectContaining({
- query: expect.objectContaining({
- field: defaultTableColumns,
- }),
- })
- );
- });
- });
- it('should use defaultWidgetQuery Y-Axis and Conditions if given a defaultWidgetQuery', async function () {
- const defaultWidgetQuery = {
- name: '',
- fields: ['count()', 'failure_count()', 'count_unique(user)'],
- columns: [],
- aggregates: ['count()', 'failure_count()', 'count_unique(user)'],
- conditions: 'tag:value',
- orderby: '',
- };
- renderTestComponent({
- query: {
- source: DashboardWidgetSource.DISCOVERV2,
- defaultWidgetQuery: urlEncode(defaultWidgetQuery),
- },
- });
- expect(await screen.findByText('tag:value')).toBeInTheDocument();
- // Table display, column, and sort field
- expect(screen.getAllByText('count()')).toHaveLength(3);
- // Table display and column
- expect(screen.getAllByText('failure_count()')).toHaveLength(2);
- // Table display
- expect(screen.getByText('count_unique(user)')).toBeInTheDocument();
- // Column
- expect(screen.getByText('count_unique(…)')).toBeInTheDocument();
- // Column
- expect(screen.getByText('user')).toBeInTheDocument();
- });
- it('uses displayType if given a displayType', async function () {
- renderTestComponent({
- query: {
- displayType: DisplayType.BAR,
- },
- });
- expect(await screen.findByText('Bar Chart')).toBeInTheDocument();
- });
- it('deletes the widget when the modal is confirmed', async () => {
- const handleSave = jest.fn();
- const widget: Widget = {
- id: '1',
- title: 'Errors over time',
- interval: '5m',
- displayType: DisplayType.LINE,
- queries: [
- {
- name: 'errors',
- conditions: 'event.type:error',
- fields: ['count()', 'count_unique(id)'],
- aggregates: ['count()', 'count_unique(id)'],
- columns: [],
- orderby: '',
- },
- {
- name: 'csp',
- conditions: 'event.type:csp',
- fields: ['count()', 'count_unique(id)'],
- aggregates: ['count()', 'count_unique(id)'],
- columns: [],
- orderby: '',
- },
- ],
- };
- const dashboard = mockDashboard({widgets: [widget]});
- renderTestComponent({onSave: handleSave, dashboard, params: {widgetIndex: '0'}});
- await userEvent.click(await screen.findByText('Delete'));
- renderGlobalModal();
- await userEvent.click(await screen.findByText('Confirm'));
- await waitFor(() => {
- // The only widget was deleted
- expect(handleSave).toHaveBeenCalledWith([]);
- });
- expect(handleSave).toHaveBeenCalledTimes(1);
- });
- it('persists the page filter period when updating a widget', async () => {
- const widget: Widget = {
- id: '1',
- title: 'Errors over time',
- interval: '5m',
- displayType: DisplayType.LINE,
- queries: [
- {
- name: 'errors',
- conditions: 'event.type:error',
- fields: ['count()', 'count_unique(id)'],
- aggregates: ['count()', 'count_unique(id)'],
- columns: [],
- orderby: '',
- },
- ],
- };
- const dashboard = mockDashboard({widgets: [widget]});
- const {router} = renderTestComponent({
- dashboard,
- params: {orgId: 'org-slug', widgetIndex: '0'},
- query: {statsPeriod: '90d'},
- });
- await userEvent.click(screen.getByText('Update Widget'));
- await waitFor(() => {
- expect(router.push).toHaveBeenLastCalledWith(
- expect.objectContaining({
- pathname: '/organizations/org-slug/dashboard/1/',
- query: expect.objectContaining({
- statsPeriod: '90d',
- }),
- })
- );
- });
- });
- it('renders page filters in the filter step', async () => {
- const mockReleases = MockApiClient.addMockResponse({
- url: '/organizations/org-slug/releases/',
- body: [ReleaseFixture()],
- });
- renderTestComponent({
- params: {orgId: 'org-slug'},
- query: {statsPeriod: '90d'},
- orgFeatures: defaultOrgFeatures,
- });
- expect(await screen.findByTestId('page-filter-timerange-selector')).toBeDisabled();
- expect(screen.getByTestId('page-filter-environment-selector')).toBeDisabled();
- expect(screen.getByTestId('page-filter-project-selector')).toBeDisabled();
- expect(mockReleases).toHaveBeenCalled();
- expect(screen.getByRole('button', {name: /all releases/i})).toBeDisabled();
- });
- it('appends dashboard filters to widget builder fetch data request', async () => {
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/releases/',
- body: [ReleaseFixture()],
- });
- const mock = MockApiClient.addMockResponse({
- url: '/organizations/org-slug/events/',
- body: [],
- });
- renderTestComponent({
- dashboard: {
- id: 'new',
- title: 'Dashboard',
- createdBy: undefined,
- dateCreated: '2020-01-01T00:00:00.000Z',
- widgets: [],
- projects: [],
- filters: {release: ['abc@1.2.0']},
- },
- params: {orgId: 'org-slug'},
- query: {statsPeriod: '90d'},
- orgFeatures: defaultOrgFeatures,
- });
- await waitFor(() => {
- expect(mock).toHaveBeenCalledWith(
- '/organizations/org-slug/events/',
- expect.objectContaining({
- query: expect.objectContaining({
- query: ' release:"abc@1.2.0" ',
- }),
- })
- );
- });
- });
- it('does not error when query conditions field is blurred', async function () {
- const widget: Widget = {
- id: '0',
- title: 'sdk usage',
- interval: '5m',
- displayType: DisplayType.BAR,
- queries: [
- {
- name: 'filled in',
- conditions: 'event.type:error',
- fields: ['count()', 'count_unique(id)'],
- aggregates: ['count()', 'count_unique(id)'],
- columns: [],
- orderby: '-count()',
- },
- ],
- };
- const dashboard = mockDashboard({widgets: [widget]});
- const handleSave = jest.fn();
- renderTestComponent({dashboard, onSave: handleSave, params: {widgetIndex: '0'}});
- await userEvent.click(await screen.findByLabelText('Add Query'), {delay: null});
- // Triggering the onBlur of the new field should not error
- await userEvent.click(
- screen.getAllByPlaceholderText('Search for events, users, tags, and more')[1],
- {delay: null}
- );
- await userEvent.keyboard('{Escape}', {delay: null});
- // Run all timers because the handleBlur contains a setTimeout
- await act(tick);
- });
- it('does not wipe column changes when filters are modified', async function () {
- // widgetIndex: undefined means creating a new widget
- renderTestComponent({params: {widgetIndex: undefined}});
- await userEvent.click(await screen.findByLabelText('Add a Column'), {delay: null});
- await selectEvent.select(screen.getByText('(Required)'), /project/);
- // Triggering the onBlur of the filter should not error
- await userEvent.click(
- screen.getByPlaceholderText('Search for events, users, tags, and more'),
- {delay: null}
- );
- await userEvent.keyboard('{enter}', {delay: null});
- expect(await screen.findAllByText('project')).toHaveLength(2);
- });
- it('renders fields with commas properly', async () => {
- const defaultWidgetQuery = {
- conditions: '',
- fields: ['equation|count_if(transaction.duration,equals,300)*2'],
- aggregates: ['equation|count_if(transaction.duration,equals,300)*2'],
- columns: [],
- orderby: '',
- name: '',
- };
- const defaultTableColumns = [
- 'count_if(transaction.duration,equals,300)',
- 'equation|count_if(transaction.duration,equals,300)*2',
- ];
- renderTestComponent({
- query: {
- source: DashboardWidgetSource.DISCOVERV2,
- defaultWidgetQuery: urlEncode(defaultWidgetQuery),
- defaultTableColumns,
- yAxis: ['equation|count_if(transaction.duration,equals,300)*2'],
- },
- });
- expect(
- await screen.findByText('count_if(transaction.duration,equals,300)*2')
- ).toBeInTheDocument();
- });
- it('sets the correct fields for a top n widget', async () => {
- renderTestComponent({
- orgFeatures: [...defaultOrgFeatures, 'performance-view'],
- query: {
- displayType: DisplayType.TOP_N,
- },
- });
- // Top N now opens as Area Chart
- expect(await screen.findByText('Area Chart')).toBeInTheDocument();
- // Add a group by
- await userEvent.click(screen.getByText('Add Overlay'));
- await selectEvent.select(screen.getByText('Select group'), /project/);
- // Change the y-axis
- await selectEvent.select(screen.getAllByText('count()')[0], 'eps()');
- await waitFor(() => {
- expect(eventsStatsMock).toHaveBeenLastCalledWith(
- '/organizations/org-slug/events-stats/',
- expect.objectContaining({
- query: expect.objectContaining({
- query: '',
- yAxis: ['eps()'],
- field: ['project', 'eps()'],
- topEvents: TOP_N,
- orderby: '-eps()',
- }),
- })
- );
- });
- });
- it('fetches tags when tag store is empty', async function () {
- renderTestComponent();
- await waitFor(() => {
- expect(tagsMock).toHaveBeenCalled();
- });
- });
- it('does not fetch tags when tag store is not empty', async function () {
- await act(async () => {
- TagStore.loadTagsSuccess(TagsFixture());
- renderTestComponent();
- await tick();
- });
- expect(tagsMock).not.toHaveBeenCalled();
- });
- it('excludes the Other series when grouping and using multiple y-axes', async function () {
- renderTestComponent({
- orgFeatures: [...defaultOrgFeatures],
- query: {
- displayType: DisplayType.LINE,
- },
- });
- await selectEvent.select(await screen.findByText('Select group'), 'project');
- await userEvent.click(screen.getByText('Add Overlay'));
- await selectEvent.select(screen.getByText('(Required)'), /count_unique/);
- await waitFor(() => {
- expect(eventsStatsMock).toHaveBeenCalledWith(
- '/organizations/org-slug/events-stats/',
- expect.objectContaining({
- query: expect.objectContaining({excludeOther: '1'}),
- })
- );
- });
- });
- it('excludes the Other series when grouping and using multiple queries', async function () {
- renderTestComponent({
- orgFeatures: [...defaultOrgFeatures],
- query: {
- displayType: DisplayType.LINE,
- },
- });
- await selectEvent.select(await screen.findByText('Select group'), 'project');
- await userEvent.click(screen.getByText('Add Query'));
- await waitFor(() => {
- expect(eventsStatsMock).toHaveBeenCalledWith(
- '/organizations/org-slug/events-stats/',
- expect.objectContaining({
- query: expect.objectContaining({excludeOther: '1'}),
- })
- );
- });
- });
- it('includes Other series when there is only one query and one y-axis', async function () {
- renderTestComponent({
- orgFeatures: [...defaultOrgFeatures],
- query: {
- displayType: DisplayType.LINE,
- },
- });
- await selectEvent.select(await screen.findByText('Select group'), 'project');
- await waitFor(() => {
- expect(eventsStatsMock).toHaveBeenCalledWith(
- '/organizations/org-slug/events-stats/',
- expect.objectContaining({
- query: expect.not.objectContaining({excludeOther: '1'}),
- })
- );
- });
- });
- it('decreases the limit when more y-axes and queries are added', async function () {
- renderTestComponent({
- orgFeatures: [...defaultOrgFeatures],
- query: {
- displayType: DisplayType.LINE,
- },
- });
- await selectEvent.select(await screen.findByText('Select group'), 'project');
- screen.getByText('Limit to 5 results');
- await userEvent.click(screen.getByText('Add Query'));
- await userEvent.click(screen.getByText('Add Overlay'));
- expect(screen.getByText('Limit to 2 results')).toBeInTheDocument();
- });
- it('alerts the user if there are unsaved title changes', async function () {
- const {router} = renderTestComponent();
- const alertMock = jest.fn();
- const setRouteLeaveHookMock = jest.spyOn(router, 'setRouteLeaveHook');
- setRouteLeaveHookMock.mockImplementationOnce((_route, _callback) => {
- alertMock();
- });
- const customWidgetLabels = await screen.findByText('Custom Widget');
- // EditableText and chart title
- expect(customWidgetLabels).toBeInTheDocument();
- // Change title text
- await userEvent.clear(screen.getByRole('textbox', {name: 'Widget title'}));
- await userEvent.click(screen.getByRole('textbox', {name: 'Widget title'}));
- await userEvent.paste('Unique Users');
- await userEvent.keyboard('{Enter}');
- // Click Cancel
- await userEvent.click(screen.getByText('Cancel'));
- // Assert an alert was triggered
- expect(alertMock).toHaveBeenCalled();
- });
- it('alerts the user if there are unsaved description changes', async function () {
- const {router} = renderTestComponent();
- const alertMock = jest.fn();
- const setRouteLeaveHookMock = jest.spyOn(router, 'setRouteLeaveHook');
- setRouteLeaveHookMock.mockImplementationOnce((_route, _callback) => {
- alertMock();
- });
- const descriptionTextArea = await screen.findByRole('textbox', {
- name: 'Widget Description',
- });
- expect(descriptionTextArea).toBeInTheDocument();
- expect(descriptionTextArea).toHaveAttribute(
- 'placeholder',
- 'Enter description (Optional)'
- );
- // Change description text
- await userEvent.clear(descriptionTextArea);
- await userEvent.click(descriptionTextArea);
- await userEvent.paste('This is a description');
- await userEvent.keyboard('{Enter}');
- // Click Cancel
- await userEvent.click(screen.getByText('Cancel'));
- // Assert an alert was triggered
- expect(alertMock).toHaveBeenCalled();
- });
- it('does not trigger alert dialog if no changes', async function () {
- const {router} = renderTestComponent();
- const alertMock = jest.fn();
- const setRouteLeaveHookMock = jest.spyOn(router, 'setRouteLeaveHook');
- setRouteLeaveHookMock.mockImplementationOnce((_route, _callback) => {
- alertMock();
- });
- // Click Cancel
- await userEvent.click(await screen.findByText('Cancel'));
- // Assert an alert was triggered
- expect(alertMock).not.toHaveBeenCalled();
- });
- describe('Widget creation coming from other verticals', function () {
- it('redirects correctly when creating a new dashboard', async function () {
- const {router} = renderTestComponent({
- query: {source: DashboardWidgetSource.DISCOVERV2},
- });
- await userEvent.click(await screen.findByText('Add Widget'));
- await waitFor(() => {
- expect(router.push).toHaveBeenCalledWith(
- expect.objectContaining({
- pathname: '/organizations/org-slug/dashboards/new/',
- query: {
- displayType: 'table',
- interval: '5m',
- title: 'Custom Widget',
- queryNames: [''],
- queryConditions: [''],
- queryFields: ['count()'],
- queryOrderby: '-count()',
- start: null,
- end: null,
- statsPeriod: '24h',
- utc: null,
- project: [],
- environment: [],
- },
- })
- );
- });
- });
- it('redirects correctly when choosing an existing dashboard', async function () {
- const {router} = renderTestComponent({
- query: {source: DashboardWidgetSource.DISCOVERV2},
- dashboard: testDashboard,
- });
- await userEvent.click(await screen.findByText('Add Widget'));
- await waitFor(() => {
- expect(router.push).toHaveBeenCalledWith(
- expect.objectContaining({
- pathname: '/organizations/org-slug/dashboard/2/',
- query: {
- displayType: 'table',
- interval: '5m',
- title: 'Custom Widget',
- queryNames: [''],
- queryConditions: [''],
- queryFields: ['count()'],
- queryOrderby: '-count()',
- start: null,
- end: null,
- statsPeriod: '24h',
- utc: null,
- project: [],
- environment: [],
- },
- })
- );
- });
- });
- it('shows the correct orderby when switching from a line chart to table', async function () {
- const defaultWidgetQuery = {
- name: '',
- fields: ['count_unique(user)'],
- columns: [],
- aggregates: ['count_unique(user)'],
- conditions: '',
- orderby: 'count_unique(user)',
- };
- const defaultTableColumns = ['title', 'count_unique(user)'];
- renderTestComponent({
- orgFeatures: [...defaultOrgFeatures],
- query: {
- source: DashboardWidgetSource.DISCOVERV2,
- defaultWidgetQuery: urlEncode(defaultWidgetQuery),
- displayType: DisplayType.LINE,
- defaultTableColumns,
- },
- });
- await userEvent.click(await screen.findByText('Line Chart'));
- await userEvent.click(screen.getByText('Table'));
- expect(screen.getAllByText('count_unique(user)')[0]).toBeInTheDocument();
- await waitFor(() => {
- expect(eventsMock).toHaveBeenLastCalledWith(
- '/organizations/org-slug/events/',
- expect.objectContaining({
- query: expect.objectContaining({
- field: defaultTableColumns,
- sort: ['count_unique(user)'],
- }),
- })
- );
- });
- });
- it('does not send request with orderby if a timeseries chart without grouping', async function () {
- const defaultWidgetQuery = {
- name: '',
- fields: ['count_unique(user)'],
- columns: [],
- aggregates: ['count_unique(user)'],
- conditions: '',
- orderby: 'count_unique(user)',
- };
- const defaultTableColumns = ['title', 'count_unique(user)'];
- renderTestComponent({
- orgFeatures: [...defaultOrgFeatures],
- query: {
- source: DashboardWidgetSource.DISCOVERV2,
- defaultWidgetQuery: urlEncode(defaultWidgetQuery),
- displayType: DisplayType.LINE,
- defaultTableColumns,
- },
- });
- await waitFor(() => {
- expect(eventsStatsMock).toHaveBeenLastCalledWith(
- '/organizations/org-slug/events-stats/',
- expect.objectContaining({
- query: expect.objectContaining({
- orderby: '',
- }),
- })
- );
- });
- });
- });
- it('opens top-N widgets as area display', async function () {
- const widget: Widget = {
- id: '1',
- title: 'Errors over time',
- interval: '5m',
- displayType: DisplayType.TOP_N,
- queries: [
- {
- name: '',
- conditions: '',
- fields: ['count()', 'count_unique(id)'],
- aggregates: ['count()', 'count_unique(id)'],
- columns: [],
- orderby: '-count()',
- },
- ],
- };
- const dashboard = mockDashboard({widgets: [widget]});
- renderTestComponent({
- orgFeatures: [...defaultOrgFeatures],
- dashboard,
- params: {
- widgetIndex: '0',
- },
- });
- expect(await screen.findByText('Area Chart')).toBeInTheDocument();
- });
- it('Update table header values (field alias)', async function () {
- const handleSave = jest.fn();
- renderTestComponent({
- onSave: handleSave,
- orgFeatures: [...defaultOrgFeatures],
- });
- await userEvent.click(screen.getByPlaceholderText('Alias'));
- await userEvent.paste('First Alias');
- await userEvent.click(screen.getByLabelText('Add a Column'));
- await userEvent.click(screen.getAllByPlaceholderText('Alias')[1]);
- await userEvent.paste('Second Alias');
- await userEvent.click(screen.getByText('Add Widget'));
- await waitFor(() => {
- expect(handleSave).toHaveBeenCalledWith([
- expect.objectContaining({
- queries: [
- expect.objectContaining({fieldAliases: ['First Alias', 'Second Alias']}),
- ],
- }),
- ]);
- });
- });
- it('does not wipe equation aliases when a column alias is updated', async function () {
- renderTestComponent({
- orgFeatures: [...defaultOrgFeatures],
- });
- await userEvent.click(screen.getByText('Add an Equation'));
- await userEvent.click(screen.getAllByPlaceholderText('Alias')[1]);
- await userEvent.paste('This should persist');
- await userEvent.type(screen.getAllByPlaceholderText('Alias')[0], 'A');
- expect(await screen.findByText('This should persist')).toBeInTheDocument();
- });
- it('does not wipe equation aliases when a column selection is made', async function () {
- renderTestComponent({
- orgFeatures: [...defaultOrgFeatures],
- });
- await userEvent.click(screen.getByText('Add an Equation'));
- await userEvent.click(screen.getAllByPlaceholderText('Alias')[1]);
- await userEvent.paste('This should persist');
- // 1 for the table, 1 for the the column selector, 1 for the sort
- await waitFor(() => expect(screen.getAllByText('count()')).toHaveLength(3));
- await selectEvent.select(screen.getAllByText('count()')[1], /count_unique/);
- expect(screen.getByText('This should persist')).toBeInTheDocument();
- });
- it('copies over the orderby from the previous query if adding another', async function () {
- renderTestComponent({
- orgFeatures: [...defaultOrgFeatures],
- });
- await userEvent.click(await screen.findByText('Table'));
- await userEvent.click(screen.getByText('Line Chart'));
- await selectEvent.select(screen.getByText('Select group'), 'project');
- await selectEvent.select(screen.getAllByText('count()')[1], 'count_unique(…)');
- MockApiClient.clearMockResponses();
- eventsStatsMock = MockApiClient.addMockResponse({
- url: '/organizations/org-slug/events-stats/',
- body: [],
- });
- await userEvent.click(screen.getByText('Add Query'));
- // Assert on two calls, one for each query
- const expectedArgs = expect.objectContaining({
- query: expect.objectContaining({
- orderby: '-count_unique(user)',
- }),
- });
- expect(eventsStatsMock).toHaveBeenNthCalledWith(
- 1,
- '/organizations/org-slug/events-stats/',
- expectedArgs
- );
- expect(eventsStatsMock).toHaveBeenNthCalledWith(
- 2,
- '/organizations/org-slug/events-stats/',
- expectedArgs
- );
- });
- it('disables add widget button and prevents widget previewing from firing widget query if widget query condition is invalid', async function () {
- renderTestComponent({
- orgFeatures: [...defaultOrgFeatures],
- });
- await userEvent.click(await screen.findByText('Table'));
- await userEvent.click(screen.getByText('Line Chart'));
- expect(eventsStatsMock).toHaveBeenCalledTimes(1);
- await userEvent.type(
- screen.getByTestId('smart-search-input'),
- 'transaction.duration:123a'
- );
- // Unfocus input
- await userEvent.click(screen.getByText('Filter your results'));
- expect(screen.getByText('Add Widget').closest('button')).toBeDisabled();
- expect(screen.getByText('Widget query condition is invalid.')).toBeInTheDocument();
- expect(eventsStatsMock).toHaveBeenCalledTimes(1);
- });
- describe('Widget Library', function () {
- it('only opens the modal when the query data is changed', async function () {
- const mockModal = jest.spyOn(modals, 'openWidgetBuilderOverwriteModal');
- renderTestComponent();
- await screen.findByText('Widget Library');
- await userEvent.click(screen.getByText('Duration Distribution'));
- // Widget Library, Builder title, and Chart title
- expect(screen.getAllByText('Duration Distribution')).toHaveLength(2);
- // Confirm modal doesn't open because no changes were made
- expect(mockModal).not.toHaveBeenCalled();
- await userEvent.click(screen.getAllByLabelText('Remove this Y-Axis')[0]);
- await userEvent.click(screen.getByText('High Throughput Transactions'));
- // Should not have overwritten widget data, and confirm modal should open
- expect(screen.getAllByText('Duration Distribution')).toHaveLength(2);
- expect(mockModal).toHaveBeenCalled();
- });
- });
- describe('group by field', function () {
- it('does not contain functions as options', async function () {
- renderTestComponent({
- query: {displayType: 'line'},
- orgFeatures: [...defaultOrgFeatures],
- });
- expect(await screen.findByText('Select group')).toBeInTheDocument();
- await userEvent.click(screen.getByText('Select group'));
- // Only one f(x) field set in the y-axis selector
- expect(screen.getByText('f(x)')).toBeInTheDocument();
- });
- it('adds more fields when Add Group is clicked', async function () {
- renderTestComponent({
- query: {displayType: 'line'},
- orgFeatures: [...defaultOrgFeatures],
- });
- await userEvent.click(await screen.findByText('Add Group'));
- expect(await screen.findAllByText('Select group')).toHaveLength(2);
- });
- it("doesn't reset group by when changing y-axis", async function () {
- renderTestComponent({
- query: {displayType: 'line'},
- orgFeatures: [...defaultOrgFeatures],
- });
- await selectEvent.select(await screen.findByText('Select group'), 'project');
- await userEvent.click(screen.getAllByText('count()')[0], {
- skipHover: true,
- });
- await userEvent.click(screen.getByText(/count_unique/), {
- skipHover: true,
- });
- expect(await screen.findByText('project')).toBeInTheDocument();
- });
- it("doesn't erase the selection when switching to another time series", async function () {
- renderTestComponent({
- query: {displayType: 'line'},
- orgFeatures: [...defaultOrgFeatures],
- });
- await selectEvent.select(await screen.findByText('Select group'), 'project');
- await userEvent.click(screen.getByText('Line Chart'));
- await userEvent.click(screen.getByText('Area Chart'));
- expect(await screen.findByText('project')).toBeInTheDocument();
- });
- it('sends a top N request when a grouping is selected', async function () {
- renderTestComponent({
- query: {displayType: 'line'},
- orgFeatures: [...defaultOrgFeatures],
- });
- await userEvent.click(await screen.findByText('Group your results'));
- await userEvent.type(screen.getByText('Select group'), 'project{enter}');
- await waitFor(() =>
- expect(eventsStatsMock).toHaveBeenNthCalledWith(
- 2,
- '/organizations/org-slug/events-stats/',
- expect.objectContaining({
- query: expect.objectContaining({
- query: '',
- yAxis: ['count()'],
- field: ['project', 'count()'],
- topEvents: TOP_N,
- orderby: '-count()',
- }),
- })
- )
- );
- });
- it('allows deleting groups until there is one left', async function () {
- renderTestComponent({
- query: {displayType: 'line'},
- orgFeatures: [...defaultOrgFeatures],
- });
- await userEvent.click(await screen.findByText('Add Group'));
- expect(screen.getAllByLabelText('Remove group')).toHaveLength(2);
- await userEvent.click(screen.getAllByLabelText('Remove group')[1]);
- await waitFor(() =>
- expect(screen.queryByLabelText('Remove group')).not.toBeInTheDocument()
- );
- });
- it("display 'remove' and 'drag to reorder' buttons", async function () {
- renderTestComponent({
- query: {displayType: 'line'},
- orgFeatures: [...defaultOrgFeatures],
- });
- expect(screen.queryByLabelText('Remove group')).not.toBeInTheDocument();
- await selectEvent.select(screen.getByText('Select group'), 'project');
- expect(screen.getByLabelText('Remove group')).toBeInTheDocument();
- expect(screen.queryByLabelText('Drag to reorder')).not.toBeInTheDocument();
- await userEvent.click(screen.getByText('Add Group'));
- expect(screen.getAllByLabelText('Remove group')).toHaveLength(2);
- expect(screen.getAllByLabelText('Drag to reorder')).toHaveLength(2);
- });
- it.todo(
- 'Since simulate drag and drop with RTL is not recommended because of browser layout, remember to create acceptance test for this'
- );
- });
- describe('limit field', function () {
- it('renders if groupBy value is present', async function () {
- const handleSave = jest.fn();
- renderTestComponent({
- query: {displayType: 'line'},
- orgFeatures: [...defaultOrgFeatures],
- onSave: handleSave,
- });
- await selectEvent.select(await screen.findByText('Select group'), 'project');
- expect(screen.getByText('Limit to 5 results')).toBeInTheDocument();
- await userEvent.click(screen.getByText('Add Widget'));
- await waitFor(() =>
- expect(handleSave).toHaveBeenCalledWith([
- expect.objectContaining({
- limit: 5,
- }),
- ])
- );
- });
- it('update value', async function () {
- renderTestComponent({
- query: {displayType: 'line'},
- orgFeatures: [...defaultOrgFeatures],
- });
- await selectEvent.select(await screen.findByText('Select group'), 'project');
- await userEvent.click(screen.getByText('Limit to 5 results'));
- await userEvent.click(screen.getByText('Limit to 2 results'));
- await waitFor(() =>
- expect(eventsStatsMock).toHaveBeenCalledWith(
- '/organizations/org-slug/events-stats/',
- expect.objectContaining({
- query: expect.objectContaining({
- query: '',
- yAxis: ['count()'],
- field: ['project', 'count()'],
- topEvents: 2,
- orderby: '-count()',
- }),
- })
- )
- );
- });
- it('gets removed if no groupBy value', async function () {
- renderTestComponent({
- query: {displayType: 'line'},
- orgFeatures: [...defaultOrgFeatures],
- });
- await selectEvent.select(await screen.findByText('Select group'), 'project');
- expect(screen.getByText('Limit to 5 results')).toBeInTheDocument();
- await userEvent.click(screen.getByLabelText('Remove group'));
- await waitFor(() =>
- expect(screen.queryByText('Limit to 5 results')).not.toBeInTheDocument()
- );
- });
- it('applies a limit when switching from a table to timeseries chart with grouping', async function () {
- const widget: Widget = {
- displayType: DisplayType.TABLE,
- interval: '1d',
- queries: [
- {
- name: 'Test Widget',
- fields: ['count()', 'count_unique(user)', 'epm()', 'project'],
- columns: ['project'],
- aggregates: ['count()', 'count_unique(user)', 'epm()'],
- conditions: '',
- orderby: '',
- },
- ],
- title: 'Transactions',
- id: '1',
- };
- const dashboard = mockDashboard({widgets: [widget]});
- renderTestComponent({
- dashboard,
- orgFeatures: [...defaultOrgFeatures],
- params: {
- widgetIndex: '0',
- },
- });
- await userEvent.click(await screen.findByText('Table'));
- await userEvent.click(screen.getByText('Line Chart'));
- expect(screen.getByText('Limit to 3 results')).toBeInTheDocument();
- expect(eventsStatsMock).toHaveBeenCalledWith(
- '/organizations/org-slug/events-stats/',
- expect.objectContaining({
- query: expect.objectContaining({
- topEvents: 3,
- }),
- })
- );
- });
- it('persists the limit when switching between timeseries charts', async function () {
- const widget: Widget = {
- displayType: DisplayType.AREA,
- interval: '1d',
- queries: [
- {
- name: 'Test Widget',
- fields: ['count()', 'count_unique(user)', 'epm()', 'project'],
- columns: ['project'],
- aggregates: ['count()', 'count_unique(user)', 'epm()'],
- conditions: '',
- orderby: '',
- },
- ],
- title: 'Transactions',
- id: '1',
- limit: 1,
- };
- const dashboard = mockDashboard({widgets: [widget]});
- renderTestComponent({
- dashboard,
- orgFeatures: [...defaultOrgFeatures],
- params: {
- widgetIndex: '0',
- },
- });
- await userEvent.click(await screen.findByText('Area Chart'));
- await userEvent.click(screen.getByText('Line Chart'));
- expect(screen.getByText('Limit to 1 result')).toBeInTheDocument();
- expect(eventsStatsMock).toHaveBeenCalledWith(
- '/organizations/org-slug/events-stats/',
- expect.objectContaining({
- query: expect.objectContaining({
- topEvents: 1,
- }),
- })
- );
- });
- it('unsets the limit when going from timeseries to table', async function () {
- const widget: Widget = {
- displayType: DisplayType.AREA,
- interval: '1d',
- queries: [
- {
- name: 'Test Widget',
- fields: ['count()', 'count_unique(user)', 'epm()', 'project'],
- columns: ['project'],
- aggregates: ['count()', 'count_unique(user)', 'epm()'],
- conditions: '',
- orderby: '',
- },
- ],
- title: 'Transactions',
- id: '1',
- limit: 1,
- };
- const dashboard = mockDashboard({widgets: [widget]});
- renderTestComponent({
- dashboard,
- orgFeatures: [...defaultOrgFeatures],
- params: {
- widgetIndex: '0',
- },
- });
- await userEvent.click(await screen.findByText('Area Chart'));
- await userEvent.click(screen.getByText('Table'));
- expect(screen.queryByText('Limit to 1 result')).not.toBeInTheDocument();
- expect(eventsMock).toHaveBeenCalledWith(
- '/organizations/org-slug/events/',
- expect.objectContaining({
- query: expect.objectContaining({
- topEvents: undefined,
- }),
- })
- );
- });
- });
- });
|