summaryrefslogtreecommitdiff
path: root/spec/frontend/monitoring/components/dashboard_spec.js
blob: 85408d57dde3f76ccd2631c2c2ebb6635156bda7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
import { shallowMount, createLocalVue, mount } from '@vue/test-utils';
import { GlDropdownItem, GlButton, GlToast } from '@gitlab/ui';
import VueDraggable from 'vuedraggable';
import MockAdapter from 'axios-mock-adapter';
import axios from '~/lib/utils/axios_utils';
import statusCodes from '~/lib/utils/http_status';
import { metricStates } from '~/monitoring/constants';
import Dashboard from '~/monitoring/components/dashboard.vue';

import DashboardsDropdown from '~/monitoring/components/dashboards_dropdown.vue';
import DateTimePicker from '~/monitoring/components/date_time_picker/date_time_picker.vue';
import GroupEmptyState from '~/monitoring/components/group_empty_state.vue';
import { createStore } from '~/monitoring/stores';
import * as types from '~/monitoring/stores/mutation_types';
import { setupComponentStore, propsData } from '../init_utils';
import {
  metricsGroupsAPIResponse,
  mockedQueryResultPayload,
  mockApiEndpoint,
  environmentData,
  dashboardGitResponse,
} from '../mock_data';

const localVue = createLocalVue();
const expectedPanelCount = 2;

describe('Dashboard', () => {
  let store;
  let wrapper;
  let mock;

  const createShallowWrapper = (props = {}, options = {}) => {
    wrapper = shallowMount(Dashboard, {
      localVue,
      propsData: { ...propsData, ...props },
      store,
      ...options,
    });
  };

  const createMountedWrapper = (props = {}, options = {}) => {
    wrapper = mount(Dashboard, {
      localVue,
      propsData: { ...propsData, ...props },
      store,
      ...options,
    });
  };

  beforeEach(() => {
    store = createStore();
    mock = new MockAdapter(axios);
  });

  afterEach(() => {
    if (wrapper) {
      wrapper.destroy();
    }
    mock.restore();
  });

  describe('no metrics are available yet', () => {
    beforeEach(() => {
      mock.onGet(mockApiEndpoint).reply(statusCodes.OK, metricsGroupsAPIResponse);

      createShallowWrapper();
    });

    afterEach(() => {
      wrapper.destroy();
    });

    it('shows the environment selector', () => {
      expect(wrapper.vm.$el.querySelector('.js-environments-dropdown')).toBeTruthy();
    });
  });

  describe('no data found', () => {
    beforeEach(done => {
      mock.onGet(mockApiEndpoint).reply(statusCodes.OK, metricsGroupsAPIResponse);

      createShallowWrapper();

      wrapper.vm.$nextTick(done);
    });

    afterEach(() => {
      wrapper.destroy();
    });

    it('shows the environment selector dropdown', () => {
      expect(wrapper.vm.$el.querySelector('.js-environments-dropdown')).toBeTruthy();
    });
  });

  describe('request information to the server', () => {
    beforeEach(() => {
      mock.onGet(mockApiEndpoint).reply(200, metricsGroupsAPIResponse);
    });

    it('shows up a loading state', done => {
      createShallowWrapper({ hasMetrics: true });

      wrapper.vm
        .$nextTick()
        .then(() => {
          expect(wrapper.vm.emptyState).toEqual('loading');

          done();
        })
        .catch(done.fail);
    });

    it('hides the group panels when showPanels is false', done => {
      createMountedWrapper(
        { hasMetrics: true, showPanels: false },
        { stubs: ['graph-group', 'panel-type'] },
      );

      setupComponentStore(wrapper);

      wrapper.vm
        .$nextTick()
        .then(() => {
          expect(wrapper.vm.showEmptyState).toEqual(false);
          expect(wrapper.vm.$el.querySelector('.prometheus-panel')).toEqual(null);
          // TODO: The last expectation doesn't belong here, it belongs in a `group_group_spec.js` file
          // Issue: https://gitlab.com/gitlab-org/gitlab/issues/118780
          // expect(wrapper.vm.$el.querySelector('.prometheus-graph-group')).toBeTruthy();

          done();
        })
        .catch(done.fail);
    });

    it('fetches the metrics data with proper time window', done => {
      jest.spyOn(store, 'dispatch');

      createMountedWrapper({ hasMetrics: true }, { stubs: ['graph-group', 'panel-type'] });

      wrapper.vm.$store.commit(
        `monitoringDashboard/${types.RECEIVE_ENVIRONMENTS_DATA_SUCCESS}`,
        environmentData,
      );

      wrapper.vm
        .$nextTick()
        .then(() => {
          expect(store.dispatch).toHaveBeenCalled();

          done();
        })
        .catch(done.fail);
    });
  });

  describe('when all requests have been commited by the store', () => {
    beforeEach(() => {
      mock.onGet(mockApiEndpoint).reply(statusCodes.OK, metricsGroupsAPIResponse);

      createMountedWrapper({ hasMetrics: true }, { stubs: ['graph-group', 'panel-type'] });

      setupComponentStore(wrapper);
    });

    afterEach(() => {
      wrapper.destroy();
    });

    it('renders the environments dropdown with a number of environments', done => {
      wrapper.vm
        .$nextTick()
        .then(() => {
          const environmentDropdownItems = wrapper
            .find('.js-environments-dropdown')
            .findAll(GlDropdownItem);

          expect(wrapper.vm.environments.length).toEqual(environmentData.length);
          expect(environmentDropdownItems.length).toEqual(wrapper.vm.environments.length);

          environmentDropdownItems.wrappers.forEach((itemWrapper, index) => {
            const anchorEl = itemWrapper.find('a');
            if (anchorEl.exists() && environmentData[index].metrics_path) {
              const href = anchorEl.attributes('href');
              expect(href).toBe(environmentData[index].metrics_path);
            }
          });

          done();
        })
        .catch(done.fail);
    });

    it('renders the environments dropdown with a single active element', done => {
      wrapper.vm
        .$nextTick()
        .then(() => {
          const environmentDropdownItems = wrapper
            .find('.js-environments-dropdown')
            .findAll(GlDropdownItem);
          const activeItem = environmentDropdownItems.wrappers.filter(itemWrapper =>
            itemWrapper.find('.active').exists(),
          );

          expect(activeItem.length).toBe(1);
          done();
        })
        .catch(done.fail);
    });
  });

  it('hides the environments dropdown list when there is no environments', done => {
    createMountedWrapper({ hasMetrics: true }, { stubs: ['graph-group', 'panel-type'] });

    wrapper.vm.$store.commit(
      `monitoringDashboard/${types.RECEIVE_METRICS_DATA_SUCCESS}`,
      metricsGroupsAPIResponse,
    );
    wrapper.vm.$store.commit(
      `monitoringDashboard/${types.RECEIVE_METRIC_RESULT_SUCCESS}`,
      mockedQueryResultPayload,
    );

    wrapper.vm
      .$nextTick()
      .then(() => {
        const environmentDropdownItems = wrapper
          .find('.js-environments-dropdown')
          .findAll(GlDropdownItem);

        expect(environmentDropdownItems.length).toEqual(0);
        done();
      })
      .catch(done.fail);
  });

  it('renders the datetimepicker dropdown', done => {
    createMountedWrapper({ hasMetrics: true }, { stubs: ['graph-group', 'panel-type'] });

    setupComponentStore(wrapper);

    wrapper.vm
      .$nextTick()
      .then(() => {
        expect(wrapper.find(DateTimePicker).exists()).toBe(true);
        done();
      })
      .catch(done.fail);
  });

  describe('when one of the metrics is missing', () => {
    beforeEach(done => {
      mock.onGet(mockApiEndpoint).reply(200, metricsGroupsAPIResponse);

      createShallowWrapper({ hasMetrics: true });
      setupComponentStore(wrapper);

      wrapper.vm.$nextTick(done);
    });

    it('shows a group empty area', () => {
      const emptyGroup = wrapper.findAll({ ref: 'empty-group' });

      expect(emptyGroup).toHaveLength(1);
      expect(emptyGroup.is(GroupEmptyState)).toBe(true);
    });

    it('group empty area displays a NO_DATA state', () => {
      expect(
        wrapper
          .findAll({ ref: 'empty-group' })
          .at(0)
          .props('selectedState'),
      ).toEqual(metricStates.NO_DATA);
    });
  });

  describe('drag and drop function', () => {
    const findDraggables = () => wrapper.findAll(VueDraggable);
    const findEnabledDraggables = () => findDraggables().filter(f => !f.attributes('disabled'));
    const findDraggablePanels = () => wrapper.findAll('.js-draggable-panel');
    const findRearrangeButton = () => wrapper.find('.js-rearrange-button');

    beforeEach(() => {
      mock.onGet(mockApiEndpoint).reply(statusCodes.OK, metricsGroupsAPIResponse);
    });

    beforeEach(done => {
      createShallowWrapper({ hasMetrics: true });

      setupComponentStore(wrapper);

      wrapper.vm.$nextTick(done);
    });

    afterEach(() => {
      wrapper.destroy();
    });

    it('wraps vuedraggable', () => {
      expect(findDraggablePanels().exists()).toBe(true);
      expect(findDraggablePanels().length).toEqual(expectedPanelCount);
    });

    it('is disabled by default', () => {
      expect(findRearrangeButton().exists()).toBe(false);
      expect(findEnabledDraggables().length).toBe(0);
    });

    describe('when rearrange is enabled', () => {
      beforeEach(done => {
        wrapper.setProps({ rearrangePanelsAvailable: true });
        wrapper.vm.$nextTick(done);
      });

      it('displays rearrange button', () => {
        expect(findRearrangeButton().exists()).toBe(true);
      });

      describe('when rearrange button is clicked', () => {
        const findFirstDraggableRemoveButton = () =>
          findDraggablePanels()
            .at(0)
            .find('.js-draggable-remove');

        beforeEach(done => {
          findRearrangeButton().vm.$emit('click');
          wrapper.vm.$nextTick(done);
        });

        it('it enables draggables', () => {
          expect(findRearrangeButton().attributes('pressed')).toBeTruthy();
          expect(findEnabledDraggables()).toEqual(findDraggables());
        });

        it('metrics can be swapped', done => {
          const firstDraggable = findDraggables().at(0);
          const mockMetrics = [...metricsGroupsAPIResponse.panel_groups[1].panels];

          const firstTitle = mockMetrics[0].title;
          const secondTitle = mockMetrics[1].title;

          // swap two elements and `input` them
          [mockMetrics[0], mockMetrics[1]] = [mockMetrics[1], mockMetrics[0]];
          firstDraggable.vm.$emit('input', mockMetrics);

          wrapper.vm.$nextTick(() => {
            const { panels } = wrapper.vm.dashboard.panel_groups[1];

            expect(panels[1].title).toEqual(firstTitle);
            expect(panels[0].title).toEqual(secondTitle);
            done();
          });
        });

        it('shows a remove button, which removes a panel', done => {
          expect(findFirstDraggableRemoveButton().isEmpty()).toBe(false);

          expect(findDraggablePanels().length).toEqual(expectedPanelCount);
          findFirstDraggableRemoveButton().trigger('click');

          wrapper.vm.$nextTick(() => {
            expect(findDraggablePanels().length).toEqual(expectedPanelCount - 1);
            done();
          });
        });

        it('it disables draggables when clicked again', done => {
          findRearrangeButton().vm.$emit('click');
          wrapper.vm.$nextTick(() => {
            expect(findRearrangeButton().attributes('pressed')).toBeFalsy();
            expect(findEnabledDraggables().length).toBe(0);
            done();
          });
        });
      });
    });
  });

  describe('cluster health', () => {
    beforeEach(done => {
      mock.onGet(propsData.metricsEndpoint).reply(statusCodes.OK, JSON.stringify({}));
      createShallowWrapper({ hasMetrics: true });

      // all_dashboards is not defined in health dashboards
      wrapper.vm.$store.commit(`monitoringDashboard/${types.SET_ALL_DASHBOARDS}`, undefined);
      wrapper.vm.$nextTick(done);
    });

    afterEach(() => {
      wrapper.destroy();
    });

    it('renders correctly', () => {
      expect(wrapper.isVueInstance()).toBe(true);
      expect(wrapper.exists()).toBe(true);
    });
  });

  describe('dashboard edit link', () => {
    const findEditLink = () => wrapper.find('.js-edit-link');

    beforeEach(done => {
      mock.onGet(mockApiEndpoint).reply(statusCodes.OK, metricsGroupsAPIResponse);

      createShallowWrapper({ hasMetrics: true });

      wrapper.vm.$store.commit(
        `monitoringDashboard/${types.SET_ALL_DASHBOARDS}`,
        dashboardGitResponse,
      );
      wrapper.vm.$nextTick(done);
    });

    afterEach(() => {
      wrapper.destroy();
    });

    it('is not present for the default dashboard', () => {
      expect(findEditLink().exists()).toBe(false);
    });

    it('is present for a custom dashboard, and links to its edit_path', done => {
      const dashboard = dashboardGitResponse[1]; // non-default dashboard
      const currentDashboard = dashboard.path;

      wrapper.setProps({ currentDashboard });
      wrapper.vm
        .$nextTick()
        .then(() => {
          expect(findEditLink().exists()).toBe(true);
          expect(findEditLink().attributes('href')).toBe(dashboard.project_blob_path);
          done();
        })
        .catch(done.fail);
    });
  });

  describe('Dashboard dropdown', () => {
    beforeEach(() => {
      mock.onGet(mockApiEndpoint).reply(200, metricsGroupsAPIResponse);

      createMountedWrapper({ hasMetrics: true }, { stubs: ['graph-group', 'panel-type'] });

      wrapper.vm.$store.commit(
        `monitoringDashboard/${types.SET_ALL_DASHBOARDS}`,
        dashboardGitResponse,
      );
    });

    it('shows the dashboard dropdown', done => {
      wrapper.vm
        .$nextTick()
        .then(() => {
          const dashboardDropdown = wrapper.find(DashboardsDropdown);

          expect(dashboardDropdown.exists()).toBe(true);
          done();
        })
        .catch(done.fail);
    });
  });

  describe('external dashboard link', () => {
    beforeEach(() => {
      mock.onGet(mockApiEndpoint).reply(200, metricsGroupsAPIResponse);

      createMountedWrapper(
        {
          hasMetrics: true,
          showPanels: false,
          showTimeWindowDropdown: false,
          externalDashboardUrl: '/mockUrl',
        },
        { stubs: ['graph-group', 'panel-type'] },
      );
    });

    it('shows the link', done => {
      wrapper.vm
        .$nextTick()
        .then(() => {
          const externalDashboardButton = wrapper.find('.js-external-dashboard-link');

          expect(externalDashboardButton.exists()).toBe(true);
          expect(externalDashboardButton.is(GlButton)).toBe(true);
          expect(externalDashboardButton.text()).toContain('View full dashboard');
          done();
        })
        .catch(done.fail);
    });
  });

  // https://gitlab.com/gitlab-org/gitlab-ce/issues/66922
  // eslint-disable-next-line jest/no-disabled-tests
  describe.skip('link to chart', () => {
    const currentDashboard = 'TEST_DASHBOARD';
    localVue.use(GlToast);
    const link = () => wrapper.find('.js-chart-link');
    const clipboardText = () => link().element.dataset.clipboardText;

    beforeEach(done => {
      mock.onGet(mockApiEndpoint).reply(200, metricsGroupsAPIResponse);

      createShallowWrapper({ hasMetrics: true, currentDashboard });

      setTimeout(done);
    });

    afterEach(() => {
      wrapper.destroy();
    });

    it('adds a copy button to the dropdown', () => {
      expect(link().text()).toContain('Generate link to chart');
    });

    it('contains a link to the dashboard', () => {
      expect(clipboardText()).toContain(`dashboard=${currentDashboard}`);
      expect(clipboardText()).toContain(`group=`);
      expect(clipboardText()).toContain(`title=`);
      expect(clipboardText()).toContain(`y_label=`);
    });

    it('undefined parameter is stripped', done => {
      wrapper.setProps({ currentDashboard: undefined });

      wrapper.vm.$nextTick(() => {
        expect(clipboardText()).not.toContain(`dashboard=`);
        expect(clipboardText()).toContain(`y_label=`);
        done();
      });
    });

    it('null parameter is stripped', done => {
      wrapper.setProps({ currentDashboard: null });

      wrapper.vm.$nextTick(() => {
        expect(clipboardText()).not.toContain(`dashboard=`);
        expect(clipboardText()).toContain(`y_label=`);
        done();
      });
    });

    it('creates a toast when clicked', () => {
      jest.spyOn(wrapper.vm.$toast, 'show').and.stub();

      link().vm.$emit('click');

      expect(wrapper.vm.$toast.show).toHaveBeenCalled();
    });
  });
});