common_utils_spec.js 20.1 KB
Newer Older
1
/* eslint-disable promise/catch-or-return */
2
import axios from '~/lib/utils/axios_utils';
3
import * as commonUtils from '~/lib/utils/common_utils';
4
import MockAdapter from 'axios-mock-adapter';
5
import { faviconDataUrl, overlayDataUrl, faviconWithOverlayDataUrl } from './mock_data';
6

7 8 9 10 11 12 13 14 15 16 17 18
describe('common_utils', () => {
  describe('parseUrl', () => {
    it('returns an anchor tag with url', () => {
      expect(commonUtils.parseUrl('/some/absolute/url').pathname).toContain('some/absolute/url');
    });
    it('url is escaped', () => {
      // IE11 will return a relative pathname while other browsers will return a full pathname.
      // parseUrl uses an anchor element for parsing an url. With relative urls, the anchor
      // element will create an absolute url relative to the current execution context.
      // The JavaScript test suite is executed at '/' which will lead to an absolute url
      // starting with '/'.
      expect(commonUtils.parseUrl('" test="asf"').pathname).toContain('/%22%20test=%22asf%22');
19
    });
20
  });
21

22 23 24 25
  describe('parseUrlPathname', () => {
    it('returns an absolute url when given an absolute url', () => {
      expect(commonUtils.parseUrlPathname('/some/absolute/url')).toEqual('/some/absolute/url');
    });
26

27 28
    it('returns an absolute url when given a relative url', () => {
      expect(commonUtils.parseUrlPathname('some/relative/url')).toEqual('/some/relative/url');
29
    });
30
  });
31

32
  describe('getUrlParamsArray', () => {
33
    it('should return params array', () => {
34
      expect(commonUtils.getUrlParamsArray() instanceof Array).toBe(true);
35
    });
36

37
    it('should remove the question mark from the search params', () => {
38
      const paramsArray = commonUtils.getUrlParamsArray();
39 40
      expect(paramsArray[0][0] !== '?').toBe(true);
    });
41

42
    it('should decode params', () => {
43
      window.history.pushState('', '', '?label_name%5B%5D=test');
44

45
      expect(
46
        commonUtils.getUrlParamsArray()[0],
47
      ).toBe('label_name[]=test');
48

49
      window.history.pushState('', '', '?');
50
    });
51
  });
52

53 54 55 56
  describe('handleLocationHash', () => {
    beforeEach(() => {
      spyOn(window.document, 'getElementById').and.callThrough();
    });
57

58 59 60
    afterEach(() => {
      window.history.pushState({}, null, '');
    });
61

62 63 64
    function expectGetElementIdToHaveBeenCalledWith(elementId) {
      expect(window.document.getElementById).toHaveBeenCalledWith(elementId);
    }
65

66 67 68
    it('decodes hash parameter', () => {
      window.history.pushState({}, null, '#random-hash');
      commonUtils.handleLocationHash();
69

70 71 72
      expectGetElementIdToHaveBeenCalledWith('random-hash');
      expectGetElementIdToHaveBeenCalledWith('user-content-random-hash');
    });
73

74 75 76
    it('decodes cyrillic hash parameter', () => {
      window.history.pushState({}, null, '#definição');
      commonUtils.handleLocationHash();
77

78 79 80
      expectGetElementIdToHaveBeenCalledWith('definição');
      expectGetElementIdToHaveBeenCalledWith('user-content-definição');
    });
81

82 83 84
    it('decodes encoded cyrillic hash parameter', () => {
      window.history.pushState({}, null, '#defini%C3%A7%C3%A3o');
      commonUtils.handleLocationHash();
85

86 87
      expectGetElementIdToHaveBeenCalledWith('definição');
      expectGetElementIdToHaveBeenCalledWith('user-content-definição');
88
    });
89 90 91 92 93 94 95 96 97 98 99 100 101

    it('scrolls element into view', () => {
      document.body.innerHTML += `
        <div id="parent">
          <div style="height: 2000px;"></div>
          <div id="test" style="height: 2000px;"></div>
        </div>
      `;

      window.history.pushState({}, null, '#test');
      commonUtils.handleLocationHash();

      expectGetElementIdToHaveBeenCalledWith('test');
Phil Hughes's avatar
Phil Hughes committed
102
      expect(window.scrollY).toBe(document.getElementById('test').offsetTop);
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119

      document.getElementById('parent').remove();
    });

    it('scrolls user content element into view', () => {
      document.body.innerHTML += `
        <div id="parent">
          <div style="height: 2000px;"></div>
          <div id="user-content-test" style="height: 2000px;"></div>
        </div>
      `;

      window.history.pushState({}, null, '#test');
      commonUtils.handleLocationHash();

      expectGetElementIdToHaveBeenCalledWith('test');
      expectGetElementIdToHaveBeenCalledWith('user-content-test');
Phil Hughes's avatar
Phil Hughes committed
120
      expect(window.scrollY).toBe(document.getElementById('user-content-test').offsetTop);
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139

      document.getElementById('parent').remove();
    });

    it('scrolls to element with offset from navbar', () => {
      spyOn(window, 'scrollBy').and.callThrough();
      document.body.innerHTML += `
        <div id="parent">
          <div class="navbar-gitlab" style="position: fixed; top: 0; height: 50px;"></div>
          <div style="height: 2000px; margin-top: 50px;"></div>
          <div id="user-content-test" style="height: 2000px;"></div>
        </div>
      `;

      window.history.pushState({}, null, '#test');
      commonUtils.handleLocationHash();

      expectGetElementIdToHaveBeenCalledWith('test');
      expectGetElementIdToHaveBeenCalledWith('user-content-test');
Phil Hughes's avatar
Phil Hughes committed
140
      expect(window.scrollY).toBe(document.getElementById('user-content-test').offsetTop - 50);
141 142 143 144
      expect(window.scrollBy).toHaveBeenCalledWith(0, -50);

      document.getElementById('parent').remove();
    });
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
  describe('historyPushState', () => {
    afterEach(() => {
      window.history.replaceState({}, null, null);
    });

    it('should call pushState with the correct path', () => {
      spyOn(window.history, 'pushState');

      commonUtils.historyPushState('newpath?page=2');

      expect(window.history.pushState).toHaveBeenCalled();
      expect(window.history.pushState.calls.allArgs()[0][2]).toContain('newpath?page=2');
    });
  });

  describe('parseQueryStringIntoObject', () => {
    it('should return object with query parameters', () => {
      expect(commonUtils.parseQueryStringIntoObject('scope=all&page=2')).toEqual({ scope: 'all', page: '2' });
      expect(commonUtils.parseQueryStringIntoObject('scope=all')).toEqual({ scope: 'all' });
      expect(commonUtils.parseQueryStringIntoObject()).toEqual({});
    });
  });

170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
  describe('objectToQueryString', () => {
    it('returns empty string when `param` is undefined, null or empty string', () => {
      expect(commonUtils.objectToQueryString()).toBe('');
      expect(commonUtils.objectToQueryString('')).toBe('');
    });

    it('returns query string with values of `params`', () => {
      const singleQueryParams = { foo: true };
      const multipleQueryParams = { foo: true, bar: true };

      expect(commonUtils.objectToQueryString(singleQueryParams)).toBe('foo=true');
      expect(commonUtils.objectToQueryString(multipleQueryParams)).toBe('foo=true&bar=true');
    });
  });

185 186 187 188 189 190 191
  describe('buildUrlWithCurrentLocation', () => {
    it('should build an url with current location and given parameters', () => {
      expect(commonUtils.buildUrlWithCurrentLocation()).toEqual(window.location.pathname);
      expect(commonUtils.buildUrlWithCurrentLocation('?page=2')).toEqual(`${window.location.pathname}?page=2`);
    });
  });

192
  describe('getParameterByName', () => {
193 194 195
    beforeEach(() => {
      window.history.pushState({}, null, '?scope=all&p=2');
    });
196

197 198 199
    afterEach(() => {
      window.history.replaceState({}, null, null);
    });
200

201
    it('should return valid parameter', () => {
202 203
      const value = commonUtils.getParameterByName('scope');
      expect(commonUtils.getParameterByName('p')).toEqual('2');
204 205
      expect(value).toBe('all');
    });
206

207
    it('should return invalid parameter', () => {
208
      const value = commonUtils.getParameterByName('fakeParameter');
209 210
      expect(value).toBe(null);
    });
Alfredo Sumaran's avatar
Alfredo Sumaran committed
211

212
    it('should return valid paramentes if URL is provided', () => {
213
      let value = commonUtils.getParameterByName('foo', 'http://cocteau.twins/?foo=bar');
214
      expect(value).toBe('bar');
Alfredo Sumaran's avatar
Alfredo Sumaran committed
215

216
      value = commonUtils.getParameterByName('manan', 'http://cocteau.twins/?foo=bar&manan=canchu');
217
      expect(value).toBe('canchu');
218
    });
219
  });
220

221
  describe('normalizedHeaders', () => {
222 223 224 225 226
    it('should upperCase all the header keys to keep them consistent', () => {
      const apiHeaders = {
        'X-Something-Workhorse': { workhorse: 'ok' },
        'x-something-nginx': { nginx: 'ok' },
      };
227

228
      const normalized = commonUtils.normalizeHeaders(apiHeaders);
229

230 231
      const WORKHORSE = 'X-SOMETHING-WORKHORSE';
      const NGINX = 'X-SOMETHING-NGINX';
232

233 234
      expect(normalized[WORKHORSE].workhorse).toBe('ok');
      expect(normalized[NGINX].nginx).toBe('ok');
235
    });
236
  });
237

238
  describe('normalizeCRLFHeaders', () => {
239 240 241
    beforeEach(function () {
      this.CLRFHeaders = 'a-header: a-value\nAnother-Header: ANOTHER-VALUE\nLaSt-HeAdEr: last-VALUE';
      spyOn(String.prototype, 'split').and.callThrough();
242
      this.normalizeCRLFHeaders = commonUtils.normalizeCRLFHeaders(this.CLRFHeaders);
243
    });
244

245 246 247
    it('should split by newline', function () {
      expect(String.prototype.split).toHaveBeenCalledWith('\n');
    });
248

249 250 251
    it('should split by colon+space for each header', function () {
      expect(String.prototype.split.calls.allArgs().filter(args => args[0] === ': ').length).toBe(3);
    });
252

253 254 255 256 257
    it('should return a normalized headers object', function () {
      expect(this.normalizeCRLFHeaders).toEqual({
        'A-HEADER': 'a-value',
        'ANOTHER-HEADER': 'ANOTHER-VALUE',
        'LAST-HEADER': 'last-VALUE',
258 259
      });
    });
260
  });
261

262
  describe('parseIntPagination', () => {
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
    it('should parse to integers all string values and return pagination object', () => {
      const pagination = {
        'X-PER-PAGE': 10,
        'X-PAGE': 2,
        'X-TOTAL': 30,
        'X-TOTAL-PAGES': 3,
        'X-NEXT-PAGE': 3,
        'X-PREV-PAGE': 1,
      };

      const expectedPagination = {
        perPage: 10,
        page: 2,
        total: 30,
        totalPages: 3,
        nextPage: 3,
        previousPage: 1,
      };

282
      expect(commonUtils.parseIntPagination(pagination)).toEqual(expectedPagination);
283
    });
284
  });
285

286
  describe('isMetaClick', () => {
287 288 289 290 291 292
    it('should identify meta click on Windows/Linux', () => {
      const e = {
        metaKey: false,
        ctrlKey: true,
        which: 1,
      };
293

294
      expect(commonUtils.isMetaClick(e)).toBe(true);
295
    });
296

297 298 299 300 301 302
    it('should identify meta click on macOS', () => {
      const e = {
        metaKey: true,
        ctrlKey: false,
        which: 1,
      };
303

304
      expect(commonUtils.isMetaClick(e)).toBe(true);
305
    });
306

307 308 309 310 311 312
    it('should identify as meta click on middle-click or Mouse-wheel click', () => {
      const e = {
        metaKey: false,
        ctrlKey: false,
        which: 2,
      };
313

314 315 316 317 318 319 320 321
      expect(commonUtils.isMetaClick(e)).toBe(true);
    });
  });

  describe('convertPermissionToBoolean', () => {
    it('should convert a boolean in a string to a boolean', () => {
      expect(commonUtils.convertPermissionToBoolean('true')).toEqual(true);
      expect(commonUtils.convertPermissionToBoolean('false')).toEqual(false);
322 323 324 325 326 327 328 329
    });
  });

  describe('backOff', () => {
    beforeEach(() => {
      // shortcut our timeouts otherwise these tests will take a long time to finish
      const origSetTimeout = window.setTimeout;
      spyOn(window, 'setTimeout').and.callFake(cb => origSetTimeout(cb, 0));
330
    });
331

332 333 334 335 336 337 338 339 340 341 342
    it('solves the promise from the callback', (done) => {
      const expectedResponseValue = 'Success!';
      commonUtils.backOff((next, stop) => (
        new Promise((resolve) => {
          resolve(expectedResponseValue);
        }).then((resp) => {
          stop(resp);
        })
      )).then((respBackoff) => {
        expect(respBackoff).toBe(expectedResponseValue);
        done();
343
      });
344
    });
345

346 347 348 349 350 351 352 353 354 355 356 357
    it('catches the rejected promise from the callback ', (done) => {
      const errorMessage = 'Mistakes were made!';
      commonUtils.backOff((next, stop) => {
        new Promise((resolve, reject) => {
          reject(new Error(errorMessage));
        }).then((resp) => {
          stop(resp);
        }).catch(err => stop(err));
      }).catch((errBackoffResp) => {
        expect(errBackoffResp instanceof Error).toBe(true);
        expect(errBackoffResp.message).toBe(errorMessage);
        done();
358
      });
359
    });
360

361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
    it('solves the promise correctly after retrying a third time', (done) => {
      let numberOfCalls = 1;
      const expectedResponseValue = 'Success!';
      commonUtils.backOff((next, stop) => (
        Promise.resolve(expectedResponseValue)
          .then((resp) => {
            if (numberOfCalls < 3) {
              numberOfCalls += 1;
              next();
            } else {
              stop(resp);
            }
          })
      )).then((respBackoff) => {
        const timeouts = window.setTimeout.calls.allArgs().map(([, timeout]) => timeout);
        expect(timeouts).toEqual([2000, 4000]);
        expect(respBackoff).toBe(expectedResponseValue);
        done();
379
      });
380
    });
381

382 383 384
    it('rejects the backOff promise after timing out', (done) => {
      commonUtils.backOff(next => next(), 64000)
        .catch((errBackoffResp) => {
385
          const timeouts = window.setTimeout.calls.allArgs().map(([, timeout]) => timeout);
386 387 388
          expect(timeouts).toEqual([2000, 4000, 8000, 16000, 32000, 32000]);
          expect(errBackoffResp instanceof Error).toBe(true);
          expect(errBackoffResp.message).toBe('BACKOFF_TIMEOUT');
389 390 391
          done();
        });
    });
392
  });
393

394 395 396 397 398
  describe('setFavicon', () => {
    beforeEach(() => {
      const favicon = document.createElement('link');
      favicon.setAttribute('id', 'favicon');
      favicon.setAttribute('href', 'default/favicon');
399
      favicon.setAttribute('data-default-href', 'default/favicon');
400 401 402 403 404 405
      document.body.appendChild(favicon);
    });

    afterEach(() => {
      document.body.removeChild(document.getElementById('favicon'));
    });
406 407
    it('should set page favicon to provided favicon', () => {
      const faviconPath = '//custom_favicon';
408
      commonUtils.setFavicon(faviconPath);
409

410
      expect(document.getElementById('favicon').getAttribute('href')).toEqual(faviconPath);
411
    });
412
  });
413

414 415 416 417
  describe('resetFavicon', () => {
    beforeEach(() => {
      const favicon = document.createElement('link');
      favicon.setAttribute('id', 'favicon');
418
      favicon.setAttribute('data-original-href', 'default/favicon');
419 420 421 422 423 424 425
      document.body.appendChild(favicon);
    });

    afterEach(() => {
      document.body.removeChild(document.getElementById('favicon'));
    });

426 427 428
    it('should reset page favicon to the default icon', () => {
      const favicon = document.getElementById('favicon');
      favicon.setAttribute('href', 'new/favicon');
429 430 431 432 433
      commonUtils.resetFavicon();
      expect(document.getElementById('favicon').getAttribute('href')).toEqual('default/favicon');
    });
  });

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
  describe('createOverlayIcon', () => {
    it('should return the favicon with the overlay', (done) => {
      commonUtils.createOverlayIcon(faviconDataUrl, overlayDataUrl).then((url) => {
        expect(url).toEqual(faviconWithOverlayDataUrl);
        done();
      });
    });
  });

  describe('setFaviconOverlay', () => {
    beforeEach(() => {
      const favicon = document.createElement('link');
      favicon.setAttribute('id', 'favicon');
      favicon.setAttribute('data-original-href', faviconDataUrl);
      document.body.appendChild(favicon);
    });

    afterEach(() => {
      document.body.removeChild(document.getElementById('favicon'));
    });

    it('should set page favicon to provided favicon overlay', (done) => {
      commonUtils.setFaviconOverlay(overlayDataUrl).then(() => {
        expect(document.getElementById('favicon').getAttribute('href')).toEqual(faviconWithOverlayDataUrl);
        done();
      });
    });
  });

463 464
  describe('setCiStatusFavicon', () => {
    const BUILD_URL = `${gl.TEST_HOST}/frontend-fixtures/builds-project/-/jobs/1/status.json`;
465
    let mock;
466 467 468 469

    beforeEach(() => {
      const favicon = document.createElement('link');
      favicon.setAttribute('id', 'favicon');
470 471
      favicon.setAttribute('href', 'null');
      favicon.setAttribute('data-original-href', faviconDataUrl);
472
      document.body.appendChild(favicon);
473
      mock = new MockAdapter(axios);
474
    });
475

476
    afterEach(() => {
477
      mock.restore();
478 479 480
      document.body.removeChild(document.getElementById('favicon'));
    });

481 482
    it('should reset favicon in case of error', (done) => {
      mock.onGet(BUILD_URL).networkError();
483

484 485 486
      commonUtils.setCiStatusFavicon(BUILD_URL)
        .then(() => {
          const favicon = document.getElementById('favicon');
487
          expect(favicon.getAttribute('href')).toEqual(faviconDataUrl);
488 489 490 491 492
          done();
        })
        // Error is already caught in catch() block of setCiStatusFavicon,
        // It won't throw another error for us to catch
        .catch(done.fail);
493 494
    });

495 496
    it('should set page favicon to CI status favicon based on provided status', (done) => {
      mock.onGet(BUILD_URL).reply(200, {
497
        favicon: overlayDataUrl,
498 499
      });

500 501 502
      commonUtils.setCiStatusFavicon(BUILD_URL)
        .then(() => {
          const favicon = document.getElementById('favicon');
503
          expect(favicon.getAttribute('href')).toEqual(faviconWithOverlayDataUrl);
504 505 506
          done();
        })
        .catch(done.fail);
507
    });
508
  });
509

Clement Ho's avatar
Clement Ho committed
510 511
  describe('spriteIcon', () => {
    let beforeGon;
512

Clement Ho's avatar
Clement Ho committed
513 514 515 516 517
    beforeEach(() => {
      window.gon = window.gon || {};
      beforeGon = Object.assign({}, window.gon);
      window.gon.sprite_icons = 'icons.svg';
    });
518

Clement Ho's avatar
Clement Ho committed
519 520 521 522 523 524 525 526 527 528
    afterEach(() => {
      window.gon = beforeGon;
    });

    it('should return the svg for a linked icon', () => {
      expect(commonUtils.spriteIcon('test')).toEqual('<svg ><use xlink:href="icons.svg#test" /></svg>');
    });

    it('should set svg className when passed', () => {
      expect(commonUtils.spriteIcon('test', 'fa fa-test')).toEqual('<svg class="fa fa-test"><use xlink:href="icons.svg#test" /></svg>');
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 554 555 556 557 558

  describe('convertObjectPropsToCamelCase', () => {
    it('returns new object with camelCase property names by converting object with snake_case names', () => {
      const snakeRegEx = /(_\w)/g;
      const mockObj = {
        id: 1,
        group_name: 'GitLab.org',
        absolute_web_url: 'https://gitlab.com/gitlab-org/',
      };
      const mappings = {
        id: 'id',
        groupName: 'group_name',
        absoluteWebUrl: 'absolute_web_url',
      };

      const convertedObj = commonUtils.convertObjectPropsToCamelCase(mockObj);

      Object.keys(convertedObj).forEach((prop) => {
        expect(snakeRegEx.test(prop)).toBeFalsy();
        expect(convertedObj[prop]).toBe(mockObj[mappings[prop]]);
      });
    });

    it('return empty object if method is called with null or undefined', () => {
      expect(Object.keys(commonUtils.convertObjectPropsToCamelCase(null)).length).toBe(0);
      expect(Object.keys(commonUtils.convertObjectPropsToCamelCase()).length).toBe(0);
      expect(Object.keys(commonUtils.convertObjectPropsToCamelCase({})).length).toBe(0);
    });
Felipe Artur's avatar
Felipe Artur committed
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

    it('does not deep-convert by default', () => {
      const obj = {
        snake_key: {
          child_snake_key: 'value',
        },
      };

      expect(
        commonUtils.convertObjectPropsToCamelCase(obj),
      ).toEqual({
        snakeKey: {
          child_snake_key: 'value',
        },
      });
    });

    describe('deep: true', () => {
      it('converts object with child objects', () => {
        const obj = {
          snake_key: {
            child_snake_key: 'value',
          },
        };

        expect(
          commonUtils.convertObjectPropsToCamelCase(obj, { deep: true }),
        ).toEqual({
          snakeKey: {
            childSnakeKey: 'value',
          },
        });
      });

      it('converts array with child objects', () => {
        const arr = [
          {
            child_snake_key: 'value',
          },
        ];

        expect(
          commonUtils.convertObjectPropsToCamelCase(arr, { deep: true }),
        ).toEqual([
          {
            childSnakeKey: 'value',
          },
        ]);
      });

      it('converts array with child arrays', () => {
        const arr = [
          [
            {
              child_snake_key: 'value',
            },
          ],
        ];

        expect(
          commonUtils.convertObjectPropsToCamelCase(arr, { deep: true }),
        ).toEqual([
          [
            {
              childSnakeKey: 'value',
            },
          ],
        ]);
      });
    });
629
  });
630
});