actions_spec.js 24.6 KB
Newer Older
1
import MockAdapter from 'axios-mock-adapter';
2
import testAction from 'helpers/vuex_action_helper';
3
import Tracking from '~/tracking';
4
import axios from '~/lib/utils/axios_utils';
5
import statusCodes from '~/lib/utils/http_status';
6
import * as commonUtils from '~/lib/utils/common_utils';
7
import createFlash from '~/flash';
8
import { defaultTimeRange } from '~/vue_shared/constants';
9
import { ENVIRONMENT_AVAILABLE_STATE } from '~/monitoring/constants';
10

11 12 13 14 15 16 17
import store from '~/monitoring/stores';
import * as types from '~/monitoring/stores/mutation_types';
import {
  fetchDashboard,
  receiveMetricsDashboardSuccess,
  fetchDeploymentsData,
  fetchEnvironmentsData,
18
  fetchDashboardData,
19
  fetchAnnotations,
20
  fetchPrometheusMetric,
21
  setInitialState,
22
  filterEnvironments,
23 24
  setExpandedPanel,
  clearExpandedPanel,
25
  setGettingStartedEmptyState,
26
  duplicateSystemDashboard,
27
} from '~/monitoring/stores/actions';
28 29 30 31 32
import {
  gqClient,
  parseEnvironmentsResponse,
  parseAnnotationsResponse,
} from '~/monitoring/stores/utils';
33
import getEnvironments from '~/monitoring/queries/getEnvironments.query.graphql';
34
import getAnnotations from '~/monitoring/queries/getAnnotations.query.graphql';
35 36 37 38
import storeState from '~/monitoring/stores/state';
import {
  deploymentData,
  environmentData,
39
  annotationsData,
40
  dashboardGitResponse,
41
  mockDashboardsErrorResponse,
42
} from '../mock_data';
43 44 45 46 47
import {
  metricsDashboardResponse,
  metricsDashboardViewModel,
  metricsDashboardPanelCount,
} from '../fixture_data';
48

49
jest.mock('~/flash');
50

51 52 53 54 55 56 57 58
const resetStore = str => {
  str.replaceState({
    showEmptyState: true,
    emptyState: 'loading',
    groups: [],
  });
};

59
describe('Monitoring store actions', () => {
60 61
  const { convertObjectPropsToCamelCase } = commonUtils;

62
  let mock;
63

64 65 66
  beforeEach(() => {
    mock = new MockAdapter(axios);

67
    jest.spyOn(commonUtils, 'backOff').mockImplementation(callback => {
68 69 70 71 72 73
      const q = new Promise((resolve, reject) => {
        const stop = arg => (arg instanceof Error ? reject(arg) : resolve(arg));
        const next = () => callback(next, stop);
        // Define a timeout based on a mock timer
        setTimeout(() => {
          callback(next, stop);
74
        });
75 76 77 78
      });
      // Run all resolved promises in chain
      jest.runOnlyPendingTimers();
      return q;
79 80
    });
  });
81 82
  afterEach(() => {
    resetStore(store);
83 84
    mock.reset();

85
    commonUtils.backOff.mockReset();
86
    createFlash.mockReset();
87
  });
88

89
  describe('fetchDeploymentsData', () => {
90
    it('dispatches receiveDeploymentsDataSuccess on success', () => {
91 92 93 94 95
      const { state } = store;
      state.deploymentsEndpoint = '/success';
      mock.onGet(state.deploymentsEndpoint).reply(200, {
        deployments: deploymentData,
      });
96 97 98 99

      return testAction(
        fetchDeploymentsData,
        null,
100
        state,
101 102 103
        [],
        [{ type: 'receiveDeploymentsDataSuccess', payload: deploymentData }],
      );
104
    });
105
    it('dispatches receiveDeploymentsDataFailure on error', () => {
106 107 108
      const { state } = store;
      state.deploymentsEndpoint = '/error';
      mock.onGet(state.deploymentsEndpoint).reply(500);
109 110 111 112

      return testAction(
        fetchDeploymentsData,
        null,
113
        state,
114 115 116 117 118 119
        [],
        [{ type: 'receiveDeploymentsDataFailure' }],
        () => {
          expect(createFlash).toHaveBeenCalled();
        },
      );
120 121
    });
  });
122

123
  describe('fetchEnvironmentsData', () => {
124 125 126 127 128 129 130 131
    const { state } = store;
    state.projectPath = 'gitlab-org/gitlab-test';

    afterEach(() => {
      resetStore(store);
    });

    it('setting SET_ENVIRONMENTS_FILTER should dispatch fetchEnvironmentsData', () => {
132 133 134 135 136
      jest.spyOn(gqClient, 'mutate').mockReturnValue({
        data: {
          project: {
            data: {
              environments: [],
137 138
            },
          },
139 140
        },
      });
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158

      return testAction(
        filterEnvironments,
        {},
        state,
        [
          {
            type: 'SET_ENVIRONMENTS_FILTER',
            payload: {},
          },
        ],
        [
          {
            type: 'fetchEnvironmentsData',
          },
        ],
      );
    });
159

160 161 162 163 164 165 166 167
    it('fetch environments data call takes in search param', () => {
      const mockMutate = jest.spyOn(gqClient, 'mutate');
      const searchTerm = 'Something';
      const mutationVariables = {
        mutation: getEnvironments,
        variables: {
          projectPath: state.projectPath,
          search: searchTerm,
168
          states: [ENVIRONMENT_AVAILABLE_STATE],
169 170 171
        },
      };
      state.environmentsSearchTerm = searchTerm;
172
      mockMutate.mockResolvedValue({});
173

174 175 176
      return testAction(
        fetchEnvironmentsData,
        null,
177
        state,
178
        [],
179 180 181 182
        [
          { type: 'requestEnvironmentsData' },
          { type: 'receiveEnvironmentsDataSuccess', payload: [] },
        ],
183 184 185 186
        () => {
          expect(mockMutate).toHaveBeenCalledWith(mutationVariables);
        },
      );
187 188
    });

189
    it('dispatches receiveEnvironmentsDataSuccess on success', () => {
190 191 192 193 194
      jest.spyOn(gqClient, 'mutate').mockResolvedValue({
        data: {
          project: {
            data: {
              environments: environmentData,
195 196
            },
          },
197 198
        },
      });
199

200 201 202
      return testAction(
        fetchEnvironmentsData,
        null,
203
        state,
204 205 206 207 208 209 210 211 212
        [],
        [
          { type: 'requestEnvironmentsData' },
          {
            type: 'receiveEnvironmentsDataSuccess',
            payload: parseEnvironmentsResponse(environmentData, state.projectPath),
          },
        ],
      );
213
    });
214

215
    it('dispatches receiveEnvironmentsDataFailure on error', () => {
216
      jest.spyOn(gqClient, 'mutate').mockRejectedValue({});
217

218 219 220
      return testAction(
        fetchEnvironmentsData,
        null,
221
        state,
222 223 224
        [],
        [{ type: 'requestEnvironmentsData' }, { type: 'receiveEnvironmentsDataFailure' }],
      );
225 226
    });
  });
227

228 229
  describe('fetchAnnotations', () => {
    const { state } = store;
230 231 232 233
    state.timeRange = {
      start: '2020-04-15T12:54:32.137Z',
      end: '2020-08-15T12:54:32.137Z',
    };
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
    state.projectPath = 'gitlab-org/gitlab-test';
    state.currentEnvironmentName = 'production';
    state.currentDashboard = '.gitlab/dashboards/custom_dashboard.yml';

    afterEach(() => {
      resetStore(store);
    });

    it('fetches annotations data and dispatches receiveAnnotationsSuccess', () => {
      const mockMutate = jest.spyOn(gqClient, 'mutate');
      const mutationVariables = {
        mutation: getAnnotations,
        variables: {
          projectPath: state.projectPath,
          environmentName: state.currentEnvironmentName,
249 250
          dashboardPath: state.currentDashboard,
          startingFrom: state.timeRange.start,
251 252
        },
      };
253
      const parsedResponse = parseAnnotationsResponse(annotationsData);
254 255 256 257

      mockMutate.mockResolvedValue({
        data: {
          project: {
258 259 260 261 262 263 264 265 266 267
            environments: {
              nodes: [
                {
                  metricsDashboard: {
                    annotations: {
                      nodes: parsedResponse,
                    },
                  },
                },
              ],
268 269 270 271 272 273 274 275 276 277
            },
          },
        },
      });

      return testAction(
        fetchAnnotations,
        null,
        state,
        [],
278
        [{ type: 'receiveAnnotationsSuccess', payload: parsedResponse }],
279 280 281 282 283 284 285 286 287 288 289 290 291
        () => {
          expect(mockMutate).toHaveBeenCalledWith(mutationVariables);
        },
      );
    });

    it('dispatches receiveAnnotationsFailure if the annotations API call fails', () => {
      const mockMutate = jest.spyOn(gqClient, 'mutate');
      const mutationVariables = {
        mutation: getAnnotations,
        variables: {
          projectPath: state.projectPath,
          environmentName: state.currentEnvironmentName,
292 293
          dashboardPath: state.currentDashboard,
          startingFrom: state.timeRange.start,
294 295 296 297 298 299 300 301 302 303
        },
      };

      mockMutate.mockRejectedValue({});

      return testAction(
        fetchAnnotations,
        null,
        state,
        [],
304
        [{ type: 'receiveAnnotationsFailure' }],
305 306 307 308 309 310 311
        () => {
          expect(mockMutate).toHaveBeenCalledWith(mutationVariables);
        },
      );
    });
  });

312
  describe('Set initial state', () => {
313 314 315 316
    let mockedState;
    beforeEach(() => {
      mockedState = storeState();
    });
317
    it('should commit SET_INITIAL_STATE mutation', done => {
318
      testAction(
319
        setInitialState,
320 321 322 323 324 325 326
        {
          metricsEndpoint: 'additional_metrics.json',
          deploymentsEndpoint: 'deployments.json',
        },
        mockedState,
        [
          {
327
            type: types.SET_INITIAL_STATE,
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
            payload: {
              metricsEndpoint: 'additional_metrics.json',
              deploymentsEndpoint: 'deployments.json',
            },
          },
        ],
        [],
        done,
      );
    });
  });
  describe('Set empty states', () => {
    let mockedState;
    beforeEach(() => {
      mockedState = storeState();
    });
    it('should commit SET_METRICS_ENDPOINT mutation', done => {
      testAction(
        setGettingStartedEmptyState,
        null,
        mockedState,
        [
          {
            type: types.SET_GETTING_STARTED_EMPTY_STATE,
          },
        ],
        [],
        done,
      );
    });
  });
  describe('fetchDashboard', () => {
    let dispatch;
    let state;
362
    let commit;
363 364 365
    const response = metricsDashboardResponse;
    beforeEach(() => {
      dispatch = jest.fn();
366
      commit = jest.fn();
367 368 369
      state = storeState();
      state.dashboardEndpoint = '/dashboard';
    });
370 371

    it('on success, dispatches receive and success actions', () => {
372
      document.body.dataset.page = 'projects:environments:metrics';
373
      mock.onGet(state.dashboardEndpoint).reply(200, response);
374 375 376 377 378 379 380 381 382 383 384 385 386 387

      return testAction(
        fetchDashboard,
        null,
        state,
        [],
        [
          { type: 'requestMetricsDashboard' },
          {
            type: 'receiveMetricsDashboardSuccess',
            payload: { response },
          },
        ],
      );
388
    });
389 390 391 392 393 394

    describe('on failure', () => {
      let result;
      beforeEach(() => {
        const params = {};
        result = () => {
395 396
          mock.onGet(state.dashboardEndpoint).replyOnce(500, mockDashboardsErrorResponse);
          return fetchDashboard({ state, commit, dispatch }, params);
397 398 399
        };
      });

400
      it('dispatches a failure', done => {
401 402
        result()
          .then(() => {
403 404 405 406
            expect(commit).toHaveBeenCalledWith(
              types.SET_ALL_DASHBOARDS,
              mockDashboardsErrorResponse.all_dashboards,
            );
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
            expect(dispatch).toHaveBeenCalledWith(
              'receiveMetricsDashboardFailure',
              new Error('Request failed with status code 500'),
            );
            expect(createFlash).toHaveBeenCalled();
            done();
          })
          .catch(done.fail);
      });

      it('dispatches a failure action when a message is returned', done => {
        result()
          .then(() => {
            expect(dispatch).toHaveBeenCalledWith(
              'receiveMetricsDashboardFailure',
              new Error('Request failed with status code 500'),
            );
424 425 426
            expect(createFlash).toHaveBeenCalledWith(
              expect.stringContaining(mockDashboardsErrorResponse.message),
            );
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
            done();
          })
          .catch(done.fail);
      });

      it('does not show a flash error when showErrorBanner is disabled', done => {
        state.showErrorBanner = false;

        result()
          .then(() => {
            expect(dispatch).toHaveBeenCalledWith(
              'receiveMetricsDashboardFailure',
              new Error('Request failed with status code 500'),
            );
            expect(createFlash).not.toHaveBeenCalled();
            done();
          })
          .catch(done.fail);
      });
446 447 448 449 450 451
    });
  });
  describe('receiveMetricsDashboardSuccess', () => {
    let commit;
    let dispatch;
    let state;
452

453 454 455 456 457
    beforeEach(() => {
      commit = jest.fn();
      dispatch = jest.fn();
      state = storeState();
    });
458 459

    it('stores groups', () => {
460
      const response = metricsDashboardResponse;
461
      receiveMetricsDashboardSuccess({ state, commit, dispatch }, { response });
462
      expect(commit).toHaveBeenCalledWith(
463
        types.RECEIVE_METRICS_DASHBOARD_SUCCESS,
464

465
        metricsDashboardResponse.dashboard,
466
      );
467
      expect(dispatch).toHaveBeenCalledWith('fetchDashboardData');
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
    });
    it('sets the dashboards loaded from the repository', () => {
      const params = {};
      const response = metricsDashboardResponse;
      response.all_dashboards = dashboardGitResponse;
      receiveMetricsDashboardSuccess(
        {
          state,
          commit,
          dispatch,
        },
        {
          response,
          params,
        },
      );
      expect(commit).toHaveBeenCalledWith(types.SET_ALL_DASHBOARDS, dashboardGitResponse);
    });
  });
487
  describe('fetchDashboardData', () => {
488 489
    let commit;
    let dispatch;
490 491
    let state;

492
    beforeEach(() => {
493
      jest.spyOn(Tracking, 'event');
494 495
      commit = jest.fn();
      dispatch = jest.fn();
496
      state = storeState();
497 498

      state.timeRange = defaultTimeRange;
499
    });
500

501
    it('commits empty state when state.groups is empty', done => {
502 503 504
      const getters = {
        metricsWithData: () => [],
      };
505
      fetchDashboardData({ state, commit, dispatch, getters })
506
        .then(() => {
507 508 509 510 511 512 513 514 515
          expect(Tracking.event).toHaveBeenCalledWith(
            document.body.dataset.page,
            'dashboard_fetch',
            {
              label: 'custom_metrics_dashboard',
              property: 'count',
              value: 0,
            },
          );
516 517 518
          expect(dispatch).toHaveBeenCalledTimes(1);
          expect(dispatch).toHaveBeenCalledWith('fetchDeploymentsData');

519
          expect(createFlash).not.toHaveBeenCalled();
520 521 522 523 524
          done();
        })
        .catch(done.fail);
    });
    it('dispatches fetchPrometheusMetric for each panel query', done => {
525 526 527 528 529
      state.dashboard.panelGroups = convertObjectPropsToCamelCase(
        metricsDashboardResponse.dashboard.panel_groups,
      );

      const [metric] = state.dashboard.panelGroups[0].panels[0].metrics;
530 531 532 533
      const getters = {
        metricsWithData: () => [metric.id],
      };

534
      fetchDashboardData({ state, commit, dispatch, getters })
535 536 537
        .then(() => {
          expect(dispatch).toHaveBeenCalledWith('fetchPrometheusMetric', {
            metric,
538 539 540 541 542
            defaultQueryParams: {
              start_time: expect.any(String),
              end_time: expect.any(String),
              step: expect.any(Number),
            },
543 544
          });

545 546 547 548 549 550 551 552 553
          expect(Tracking.event).toHaveBeenCalledWith(
            document.body.dataset.page,
            'dashboard_fetch',
            {
              label: 'custom_metrics_dashboard',
              property: 'count',
              value: 1,
            },
          );
554 555 556 557 558 559 560 561

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

    it('dispatches fetchPrometheusMetric for each panel query, handles an error', done => {
562 563
      state.dashboard.panelGroups = metricsDashboardViewModel.panelGroups;
      const metric = state.dashboard.panelGroups[0].panels[0].metrics[0];
564

565
      dispatch.mockResolvedValueOnce(); // fetchDeploymentsData
566
      // Mock having one out of four metrics failing
567 568 569
      dispatch.mockRejectedValueOnce(new Error('Error fetching this metric'));
      dispatch.mockResolvedValue();

570
      fetchDashboardData({ state, commit, dispatch })
571
        .then(() => {
572
          expect(dispatch).toHaveBeenCalledTimes(metricsDashboardPanelCount + 1); // plus 1 for deployments
573
          expect(dispatch).toHaveBeenCalledWith('fetchDeploymentsData');
574 575
          expect(dispatch).toHaveBeenCalledWith('fetchPrometheusMetric', {
            metric,
576 577 578 579 580
            defaultQueryParams: {
              start_time: expect.any(String),
              end_time: expect.any(String),
              step: expect.any(Number),
            },
581
          });
582 583 584

          expect(createFlash).toHaveBeenCalledTimes(1);

585 586 587 588 589 590 591
          done();
        })
        .catch(done.fail);
      done();
    });
  });
  describe('fetchPrometheusMetric', () => {
592
    const defaultQueryParams = {
593 594
      start_time: '2019-08-06T12:40:02.184Z',
      end_time: '2019-08-06T20:40:02.184Z',
595
      step: 60,
596 597 598 599
    };
    let metric;
    let state;
    let data;
600
    let prometheusEndpointPath;
601 602 603

    beforeEach(() => {
      state = storeState();
604 605 606
      [metric] = metricsDashboardViewModel.panelGroups[0].panels[0].metrics;

      prometheusEndpointPath = metric.prometheusEndpointPath;
607 608 609 610 611

      data = {
        metricId: metric.metricId,
        result: [1582065167.353, 5, 1582065599.353],
      };
612 613 614
    });

    it('commits result', done => {
615
      mock.onGet(prometheusEndpointPath).reply(200, { data }); // One attempt
616

617 618
      testAction(
        fetchPrometheusMetric,
619
        { metric, defaultQueryParams },
620 621 622 623 624
        state,
        [
          {
            type: types.REQUEST_METRIC_RESULT,
            payload: {
625
              metricId: metric.metricId,
626 627 628 629 630
            },
          },
          {
            type: types.RECEIVE_METRIC_RESULT_SUCCESS,
            payload: {
631
              metricId: metric.metricId,
632 633 634 635 636 637
              result: data.result,
            },
          },
        ],
        [],
        () => {
638
          expect(mock.history.get).toHaveLength(1);
639
          done();
640 641
        },
      ).catch(done.fail);
642
    });
643

644 645 646 647 648 649 650 651
    describe('without metric defined step', () => {
      const expectedParams = {
        start_time: '2019-08-06T12:40:02.184Z',
        end_time: '2019-08-06T20:40:02.184Z',
        step: 60,
      };

      it('uses calculated step', done => {
652
        mock.onGet(prometheusEndpointPath).reply(200, { data }); // One attempt
653 654 655

        testAction(
          fetchPrometheusMetric,
656
          { metric, defaultQueryParams },
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
          state,
          [
            {
              type: types.REQUEST_METRIC_RESULT,
              payload: {
                metricId: metric.metricId,
              },
            },
            {
              type: types.RECEIVE_METRIC_RESULT_SUCCESS,
              payload: {
                metricId: metric.metricId,
                result: data.result,
              },
            },
          ],
          [],
          () => {
            expect(mock.history.get[0].params).toEqual(expectedParams);
            done();
          },
        ).catch(done.fail);
      });
    });

    describe('with metric defined step', () => {
      beforeEach(() => {
        metric.step = 7;
      });

      const expectedParams = {
        start_time: '2019-08-06T12:40:02.184Z',
        end_time: '2019-08-06T20:40:02.184Z',
        step: 7,
      };

      it('uses metric step', done => {
694
        mock.onGet(prometheusEndpointPath).reply(200, { data }); // One attempt
695 696 697

        testAction(
          fetchPrometheusMetric,
698
          { metric, defaultQueryParams },
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
          state,
          [
            {
              type: types.REQUEST_METRIC_RESULT,
              payload: {
                metricId: metric.metricId,
              },
            },
            {
              type: types.RECEIVE_METRIC_RESULT_SUCCESS,
              payload: {
                metricId: metric.metricId,
                result: data.result,
              },
            },
          ],
          [],
          () => {
            expect(mock.history.get[0].params).toEqual(expectedParams);
            done();
          },
        ).catch(done.fail);
      });
    });

724 725
    it('commits result, when waiting for results', done => {
      // Mock multiple attempts while the cache is filling up
726 727 728 729
      mock.onGet(prometheusEndpointPath).replyOnce(statusCodes.NO_CONTENT);
      mock.onGet(prometheusEndpointPath).replyOnce(statusCodes.NO_CONTENT);
      mock.onGet(prometheusEndpointPath).replyOnce(statusCodes.NO_CONTENT);
      mock.onGet(prometheusEndpointPath).reply(200, { data }); // 4th attempt
730

731 732
      testAction(
        fetchPrometheusMetric,
733
        { metric, defaultQueryParams },
734 735 736 737 738
        state,
        [
          {
            type: types.REQUEST_METRIC_RESULT,
            payload: {
739
              metricId: metric.metricId,
740 741 742 743 744
            },
          },
          {
            type: types.RECEIVE_METRIC_RESULT_SUCCESS,
            payload: {
745
              metricId: metric.metricId,
746 747 748 749 750 751
              result: data.result,
            },
          },
        ],
        [],
        () => {
752 753
          expect(mock.history.get).toHaveLength(4);
          done();
754 755
        },
      ).catch(done.fail);
756 757 758 759
    });

    it('commits failure, when waiting for results and getting a server error', done => {
      // Mock multiple attempts while the cache is filling up and fails
760 761 762 763
      mock.onGet(prometheusEndpointPath).replyOnce(statusCodes.NO_CONTENT);
      mock.onGet(prometheusEndpointPath).replyOnce(statusCodes.NO_CONTENT);
      mock.onGet(prometheusEndpointPath).replyOnce(statusCodes.NO_CONTENT);
      mock.onGet(prometheusEndpointPath).reply(500); // 4th attempt
764

765 766 767 768
      const error = new Error('Request failed with status code 500');

      testAction(
        fetchPrometheusMetric,
769
        { metric, defaultQueryParams },
770 771 772 773 774
        state,
        [
          {
            type: types.REQUEST_METRIC_RESULT,
            payload: {
775
              metricId: metric.metricId,
776 777 778
            },
          },
          {
779
            type: types.RECEIVE_METRIC_RESULT_FAILURE,
780
            payload: {
781
              metricId: metric.metricId,
782 783 784 785 786 787 788 789 790 791
              error,
            },
          },
        ],
        [],
      ).catch(e => {
        expect(mock.history.get).toHaveLength(4);
        expect(e).toEqual(error);
        done();
      });
792
    });
793
  });
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874

  describe('duplicateSystemDashboard', () => {
    let state;

    beforeEach(() => {
      state = storeState();
      state.dashboardsEndpoint = '/dashboards.json';
    });

    it('Succesful POST request resolves', done => {
      mock.onPost(state.dashboardsEndpoint).reply(statusCodes.CREATED, {
        dashboard: dashboardGitResponse[1],
      });

      testAction(duplicateSystemDashboard, {}, state, [], [])
        .then(() => {
          expect(mock.history.post).toHaveLength(1);
          done();
        })
        .catch(done.fail);
    });

    it('Succesful POST request resolves to a dashboard', done => {
      const mockCreatedDashboard = dashboardGitResponse[1];

      const params = {
        dashboard: 'my-dashboard',
        fileName: 'file-name.yml',
        branch: 'my-new-branch',
        commitMessage: 'A new commit message',
      };

      const expectedPayload = JSON.stringify({
        dashboard: 'my-dashboard',
        file_name: 'file-name.yml',
        branch: 'my-new-branch',
        commit_message: 'A new commit message',
      });

      mock.onPost(state.dashboardsEndpoint).reply(statusCodes.CREATED, {
        dashboard: mockCreatedDashboard,
      });

      testAction(duplicateSystemDashboard, params, state, [], [])
        .then(result => {
          expect(mock.history.post).toHaveLength(1);
          expect(mock.history.post[0].data).toEqual(expectedPayload);
          expect(result).toEqual(mockCreatedDashboard);

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

    it('Failed POST request throws an error', done => {
      mock.onPost(state.dashboardsEndpoint).reply(statusCodes.BAD_REQUEST);

      testAction(duplicateSystemDashboard, {}, state, [], []).catch(err => {
        expect(mock.history.post).toHaveLength(1);
        expect(err).toEqual(expect.any(String));

        done();
      });
    });

    it('Failed POST request throws an error with a description', done => {
      const backendErrorMsg = 'This file already exists!';

      mock.onPost(state.dashboardsEndpoint).reply(statusCodes.BAD_REQUEST, {
        error: backendErrorMsg,
      });

      testAction(duplicateSystemDashboard, {}, state, [], []).catch(err => {
        expect(mock.history.post).toHaveLength(1);
        expect(err).toEqual(expect.any(String));
        expect(err).toEqual(expect.stringContaining(backendErrorMsg));

        done();
      });
    });
  });
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913

  describe('setExpandedPanel', () => {
    let state;

    beforeEach(() => {
      state = storeState();
    });

    it('Sets a panel as expanded', () => {
      const group = 'group_1';
      const panel = { title: 'A Panel' };

      return testAction(
        setExpandedPanel,
        { group, panel },
        state,
        [{ type: types.SET_EXPANDED_PANEL, payload: { group, panel } }],
        [],
      );
    });
  });

  describe('clearExpandedPanel', () => {
    let state;

    beforeEach(() => {
      state = storeState();
    });

    it('Clears a panel as expanded', () => {
      return testAction(
        clearExpandedPanel,
        undefined,
        state,
        [{ type: types.SET_EXPANDED_PANEL, payload: { group: null, panel: null } }],
        [],
      );
    });
  });
914
});