actions_spec.js 17.7 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 6
import statusCodes from '~/lib/utils/http_status';
import { backOff } from '~/lib/utils/common_utils';
7
import createFlash from '~/flash';
8

9 10 11 12 13 14 15 16 17 18 19 20
import store from '~/monitoring/stores';
import * as types from '~/monitoring/stores/mutation_types';
import {
  fetchDashboard,
  receiveMetricsDashboardSuccess,
  receiveMetricsDashboardFailure,
  fetchDeploymentsData,
  fetchEnvironmentsData,
  fetchPrometheusMetrics,
  fetchPrometheusMetric,
  setEndpoints,
  setGettingStartedEmptyState,
21
  duplicateSystemDashboard,
22
} from '~/monitoring/stores/actions';
23
import { gqClient, parseEnvironmentsResponse } from '~/monitoring/stores/utils';
24 25 26 27 28
import storeState from '~/monitoring/stores/state';
import {
  deploymentData,
  environmentData,
  metricsDashboardResponse,
29
  metricsDashboardPayload,
30 31 32
  dashboardGitResponse,
} from '../mock_data';

33
jest.mock('~/lib/utils/common_utils');
34
jest.mock('~/flash');
35

36 37 38 39 40 41 42 43
const resetStore = str => {
  str.replaceState({
    showEmptyState: true,
    emptyState: 'loading',
    groups: [],
  });
};

44
describe('Monitoring store actions', () => {
45 46 47 48
  let mock;
  beforeEach(() => {
    mock = new MockAdapter(axios);

49 50
    // Mock `backOff` function to remove exponential algorithm delay.
    jest.useFakeTimers();
51

52 53 54 55 56 57 58
    backOff.mockImplementation(callback => {
      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);
59
        });
60 61 62 63
      });
      // Run all resolved promises in chain
      jest.runOnlyPendingTimers();
      return q;
64 65
    });
  });
66 67
  afterEach(() => {
    resetStore(store);
68 69 70 71
    mock.reset();

    backOff.mockReset();
    createFlash.mockReset();
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
  describe('fetchDeploymentsData', () => {
    it('commits RECEIVE_DEPLOYMENTS_DATA_SUCCESS on error', done => {
      const dispatch = jest.fn();
      const { state } = store;
      state.deploymentsEndpoint = '/success';
      mock.onGet(state.deploymentsEndpoint).reply(200, {
        deployments: deploymentData,
      });
      fetchDeploymentsData({
        state,
        dispatch,
      })
        .then(() => {
          expect(dispatch).toHaveBeenCalledWith('receiveDeploymentsDataSuccess', deploymentData);
          done();
        })
        .catch(done.fail);
    });
    it('commits RECEIVE_DEPLOYMENTS_DATA_FAILURE on error', done => {
      const dispatch = jest.fn();
      const { state } = store;
      state.deploymentsEndpoint = '/error';
      mock.onGet(state.deploymentsEndpoint).reply(500);
      fetchDeploymentsData({
        state,
        dispatch,
      })
        .then(() => {
          expect(dispatch).toHaveBeenCalledWith('receiveDeploymentsDataFailure');
          done();
        })
        .catch(done.fail);
    });
  });
  describe('fetchEnvironmentsData', () => {
109
    it('commits RECEIVE_ENVIRONMENTS_DATA_SUCCESS on error', () => {
110 111
      const dispatch = jest.fn();
      const { state } = store;
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
      state.projectPath = '/gitlab-org/gitlab-test';

      jest.spyOn(gqClient, 'mutate').mockReturnValue(
        Promise.resolve({
          data: {
            project: {
              data: {
                environments: environmentData,
              },
            },
          },
        }),
      );

      return fetchEnvironmentsData({
127 128
        state,
        dispatch,
129 130 131 132 133 134
      }).then(() => {
        expect(dispatch).toHaveBeenCalledWith(
          'receiveEnvironmentsDataSuccess',
          parseEnvironmentsResponse(environmentData, state.projectPath),
        );
      });
135
    });
136 137

    it('commits RECEIVE_ENVIRONMENTS_DATA_FAILURE on error', () => {
138 139
      const dispatch = jest.fn();
      const { state } = store;
140 141 142 143
      state.projectPath = '/gitlab-org/gitlab-test';
      jest.spyOn(gqClient, 'mutate').mockReturnValue(Promise.reject());

      return fetchEnvironmentsData({
144 145
        state,
        dispatch,
146 147 148
      }).then(() => {
        expect(dispatch).toHaveBeenCalledWith('receiveEnvironmentsDataFailure');
      });
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
    });
  });
  describe('Set endpoints', () => {
    let mockedState;
    beforeEach(() => {
      mockedState = storeState();
    });
    it('should commit SET_ENDPOINTS mutation', done => {
      testAction(
        setEndpoints,
        {
          metricsEndpoint: 'additional_metrics.json',
          deploymentsEndpoint: 'deployments.json',
        },
        mockedState,
        [
          {
            type: types.SET_ENDPOINTS,
            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;
    const response = metricsDashboardResponse;
    beforeEach(() => {
      dispatch = jest.fn();
      state = storeState();
      state.dashboardEndpoint = '/dashboard';
    });
207
    it('on success, dispatches receive and success actions', done => {
208
      const params = {};
209
      document.body.dataset.page = 'projects:environments:metrics';
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
      mock.onGet(state.dashboardEndpoint).reply(200, response);
      fetchDashboard(
        {
          state,
          dispatch,
        },
        params,
      )
        .then(() => {
          expect(dispatch).toHaveBeenCalledWith('requestMetricsDashboard');
          expect(dispatch).toHaveBeenCalledWith('receiveMetricsDashboardSuccess', {
            response,
            params,
          });
          done();
        })
        .catch(done.fail);
    });
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

    describe('on failure', () => {
      let result;
      let errorResponse;
      beforeEach(() => {
        const params = {};
        result = () => {
          mock.onGet(state.dashboardEndpoint).replyOnce(500, errorResponse);
          return fetchDashboard({ state, dispatch }, params);
        };
      });

      it('dispatches a failure action', done => {
        errorResponse = {};
        result()
          .then(() => {
            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 => {
        const message = 'Something went wrong with Prometheus!';
        errorResponse = { message };
        result()
          .then(() => {
            expect(dispatch).toHaveBeenCalledWith(
              'receiveMetricsDashboardFailure',
              new Error('Request failed with status code 500'),
            );
            expect(createFlash).toHaveBeenCalledWith(expect.stringContaining(message));
            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);
      });
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
    });
  });
  describe('receiveMetricsDashboardSuccess', () => {
    let commit;
    let dispatch;
    let state;
    beforeEach(() => {
      commit = jest.fn();
      dispatch = jest.fn();
      state = storeState();
    });
    it('stores groups ', () => {
      const params = {};
      const response = metricsDashboardResponse;
      receiveMetricsDashboardSuccess(
        {
          state,
          commit,
          dispatch,
        },
        {
          response,
          params,
        },
      );
      expect(commit).toHaveBeenCalledWith(
        types.RECEIVE_METRICS_DATA_SUCCESS,
310
        metricsDashboardResponse.dashboard,
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
      );
      expect(dispatch).toHaveBeenCalledWith('fetchPrometheusMetrics', params);
    });
    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);
    });
  });
  describe('receiveMetricsDashboardFailure', () => {
    let commit;
    beforeEach(() => {
      commit = jest.fn();
    });
    it('commits failure action', () => {
      receiveMetricsDashboardFailure({
        commit,
      });
      expect(commit).toHaveBeenCalledWith(types.RECEIVE_METRICS_DATA_FAILURE, undefined);
    });
    it('commits failure action with error', () => {
      receiveMetricsDashboardFailure(
        {
          commit,
        },
        'uh-oh',
      );
      expect(commit).toHaveBeenCalledWith(types.RECEIVE_METRICS_DATA_FAILURE, 'uh-oh');
    });
  });
  describe('fetchPrometheusMetrics', () => {
354
    const params = {};
355 356
    let commit;
    let dispatch;
357 358
    let state;

359
    beforeEach(() => {
360
      jest.spyOn(Tracking, 'event');
361 362
      commit = jest.fn();
      dispatch = jest.fn();
363
      state = storeState();
364
    });
365

366
    it('commits empty state when state.groups is empty', done => {
367 368 369 370
      const getters = {
        metricsWithData: () => [],
      };
      fetchPrometheusMetrics({ state, commit, dispatch, getters }, params)
371
        .then(() => {
372 373 374 375 376 377 378 379 380
          expect(Tracking.event).toHaveBeenCalledWith(
            document.body.dataset.page,
            'dashboard_fetch',
            {
              label: 'custom_metrics_dashboard',
              property: 'count',
              value: 0,
            },
          );
381
          expect(dispatch).not.toHaveBeenCalled();
382
          expect(createFlash).not.toHaveBeenCalled();
383 384 385 386 387 388
          done();
        })
        .catch(done.fail);
    });
    it('dispatches fetchPrometheusMetric for each panel query', done => {
      state.dashboard.panel_groups = metricsDashboardResponse.dashboard.panel_groups;
389 390 391 392 393 394
      const [metric] = state.dashboard.panel_groups[0].panels[0].metrics;
      const getters = {
        metricsWithData: () => [metric.id],
      };

      fetchPrometheusMetrics({ state, commit, dispatch, getters }, params)
395 396 397 398 399 400
        .then(() => {
          expect(dispatch).toHaveBeenCalledWith('fetchPrometheusMetric', {
            metric,
            params,
          });

401 402 403 404 405 406 407 408 409
          expect(Tracking.event).toHaveBeenCalledWith(
            document.body.dataset.page,
            'dashboard_fetch',
            {
              label: 'custom_metrics_dashboard',
              property: 'count',
              value: 1,
            },
          );
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425

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

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

      // Mock having one out of three metrics failing
      dispatch.mockRejectedValueOnce(new Error('Error fetching this metric'));
      dispatch.mockResolvedValue();

      fetchPrometheusMetrics({ state, commit, dispatch }, params)
426 427 428 429 430 431
        .then(() => {
          expect(dispatch).toHaveBeenCalledTimes(3);
          expect(dispatch).toHaveBeenCalledWith('fetchPrometheusMetric', {
            metric,
            params,
          });
432 433 434

          expect(createFlash).toHaveBeenCalledTimes(1);

435 436 437 438 439 440 441
          done();
        })
        .catch(done.fail);
      done();
    });
  });
  describe('fetchPrometheusMetric', () => {
442 443 444 445 446 447 448 449 450 451 452
    const params = {
      start: '2019-08-06T12:40:02.184Z',
      end: '2019-08-06T20:40:02.184Z',
    };
    let metric;
    let state;
    let data;

    beforeEach(() => {
      state = storeState();
      [metric] = metricsDashboardResponse.dashboard.panel_groups[0].panels[0].metrics;
453
      [data] = metricsDashboardPayload.panel_groups[0].panels[0].metrics;
454 455 456 457 458
    });

    it('commits result', done => {
      mock.onGet('http://test').reply(200, { data }); // One attempt

459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
      testAction(
        fetchPrometheusMetric,
        { metric, params },
        state,
        [
          {
            type: types.REQUEST_METRIC_RESULT,
            payload: {
              metricId: metric.metric_id,
            },
          },
          {
            type: types.RECEIVE_METRIC_RESULT_SUCCESS,
            payload: {
              metricId: metric.metric_id,
              result: data.result,
            },
          },
        ],
        [],
        () => {
480
          expect(mock.history.get).toHaveLength(1);
481
          done();
482 483
        },
      ).catch(done.fail);
484
    });
485 486 487 488 489 490 491 492

    it('commits result, when waiting for results', done => {
      // Mock multiple attempts while the cache is filling up
      mock.onGet('http://test').replyOnce(statusCodes.NO_CONTENT);
      mock.onGet('http://test').replyOnce(statusCodes.NO_CONTENT);
      mock.onGet('http://test').replyOnce(statusCodes.NO_CONTENT);
      mock.onGet('http://test').reply(200, { data }); // 4th attempt

493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
      testAction(
        fetchPrometheusMetric,
        { metric, params },
        state,
        [
          {
            type: types.REQUEST_METRIC_RESULT,
            payload: {
              metricId: metric.metric_id,
            },
          },
          {
            type: types.RECEIVE_METRIC_RESULT_SUCCESS,
            payload: {
              metricId: metric.metric_id,
              result: data.result,
            },
          },
        ],
        [],
        () => {
514 515
          expect(mock.history.get).toHaveLength(4);
          done();
516 517
        },
      ).catch(done.fail);
518 519 520 521 522 523 524 525 526
    });

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

527 528 529 530 531 532 533 534 535 536 537 538 539 540
      const error = new Error('Request failed with status code 500');

      testAction(
        fetchPrometheusMetric,
        { metric, params },
        state,
        [
          {
            type: types.REQUEST_METRIC_RESULT,
            payload: {
              metricId: metric.metric_id,
            },
          },
          {
541
            type: types.RECEIVE_METRIC_RESULT_FAILURE,
542 543 544 545 546 547 548 549 550 551 552 553
            payload: {
              metricId: metric.metric_id,
              error,
            },
          },
        ],
        [],
      ).catch(e => {
        expect(mock.history.get).toHaveLength(4);
        expect(e).toEqual(error);
        done();
      });
554
    });
555
  });
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636

  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();
      });
    });
  });
637
});