common_utils_spec.js 12.3 KB
Newer Older
1
require('~/lib/utils/common_utils');
2 3 4 5 6 7 8 9 10 11 12

(() => {
  describe('common_utils', () => {
    describe('gl.utils.parseUrl', () => {
      it('returns an anchor tag with url', () => {
        expect(gl.utils.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.
13 14
        // The JavaScript test suite is executed at '/' which will lead to an absolute url
        // starting with '/'.
15
        expect(gl.utils.parseUrl('" test="asf"').pathname).toContain('/%22%20test=%22asf%22');
16 17
      });
    });
18

19 20 21 22 23 24 25 26 27 28 29 30 31
    describe('gl.utils.parseUrlPathname', () => {
      beforeEach(() => {
        spyOn(gl.utils, 'parseUrl').and.callFake(url => ({
          pathname: url,
        }));
      });
      it('returns an absolute url when given an absolute url', () => {
        expect(gl.utils.parseUrlPathname('/some/absolute/url')).toEqual('/some/absolute/url');
      });
      it('returns an absolute url when given a relative url', () => {
        expect(gl.utils.parseUrlPathname('some/relative/url')).toEqual('/some/relative/url');
      });
    });
32 33 34 35 36 37 38 39 40 41 42 43

    describe('gl.utils.getUrlParamsArray', () => {
      it('should return params array', () => {
        expect(gl.utils.getUrlParamsArray() instanceof Array).toBe(true);
      });

      it('should remove the question mark from the search params', () => {
        const paramsArray = gl.utils.getUrlParamsArray();
        expect(paramsArray[0][0] !== '?').toBe(true);
      });
    });

44 45
    describe('gl.utils.handleLocationHash', () => {
      beforeEach(() => {
46
        spyOn(window.document, 'getElementById').and.callThrough();
47 48
      });

49 50 51 52
      afterEach(() => {
        window.history.pushState({}, null, '');
      });

53 54 55 56
      function expectGetElementIdToHaveBeenCalledWith(elementId) {
        expect(window.document.getElementById).toHaveBeenCalledWith(elementId);
      }

57
      it('decodes hash parameter', () => {
58 59 60 61 62 63 64 65 66
        window.history.pushState({}, null, '#random-hash');
        gl.utils.handleLocationHash();

        expectGetElementIdToHaveBeenCalledWith('random-hash');
        expectGetElementIdToHaveBeenCalledWith('user-content-random-hash');
      });

      it('decodes cyrillic hash parameter', () => {
        window.history.pushState({}, null, '#definição');
67
        gl.utils.handleLocationHash();
68 69 70 71 72 73 74 75 76 77 78

        expectGetElementIdToHaveBeenCalledWith('definição');
        expectGetElementIdToHaveBeenCalledWith('user-content-definição');
      });

      it('decodes encoded cyrillic hash parameter', () => {
        window.history.pushState({}, null, '#defini%C3%A7%C3%A3o');
        gl.utils.handleLocationHash();

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

Filipa Lacerda's avatar
Filipa Lacerda committed
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
    describe('gl.utils.setParamInURL', () => {
      afterEach(() => {
        window.history.pushState({}, null, '');
      });

      it('should return the parameter', () => {
        window.history.replaceState({}, null, '');

        expect(gl.utils.setParamInURL('page', 156)).toBe('?page=156');
        expect(gl.utils.setParamInURL('page', '156')).toBe('?page=156');
      });

      it('should update the existing parameter when its a number', () => {
        window.history.pushState({}, null, '?page=15');

        expect(gl.utils.setParamInURL('page', 16)).toBe('?page=16');
        expect(gl.utils.setParamInURL('page', '16')).toBe('?page=16');
        expect(gl.utils.setParamInURL('page', true)).toBe('?page=true');
      });

      it('should update the existing parameter when its a string', () => {
        window.history.pushState({}, null, '?scope=all');

        expect(gl.utils.setParamInURL('scope', 'finished')).toBe('?scope=finished');
      });

      it('should update the existing parameter when more than one parameter exists', () => {
        window.history.pushState({}, null, '?scope=all&page=15');

        expect(gl.utils.setParamInURL('scope', 'finished')).toBe('?scope=finished&page=15');
      });

      it('should add a new parameter to the end of the existing ones', () => {
        window.history.pushState({}, null, '?scope=all');

        expect(gl.utils.setParamInURL('page', 16)).toBe('?scope=all&page=16');
        expect(gl.utils.setParamInURL('page', '16')).toBe('?scope=all&page=16');
        expect(gl.utils.setParamInURL('page', true)).toBe('?scope=all&page=true');
      });
    });

123
    describe('gl.utils.getParameterByName', () => {
124 125 126 127
      beforeEach(() => {
        window.history.pushState({}, null, '?scope=all&p=2');
      });

128
      afterEach(() => {
Filipa Lacerda's avatar
Filipa Lacerda committed
129
        window.history.replaceState({}, null, null);
130 131
      });

132
      it('should return valid parameter', () => {
133 134
        const value = gl.utils.getParameterByName('scope');
        expect(value).toBe('all');
135 136 137 138 139 140 141
      });

      it('should return invalid parameter', () => {
        const value = gl.utils.getParameterByName('fakeParameter');
        expect(value).toBe(null);
      });
    });
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158

    describe('gl.utils.normalizedHeaders', () => {
      it('should upperCase all the header keys to keep them consistent', () => {
        const apiHeaders = {
          'X-Something-Workhorse': { workhorse: 'ok' },
          'x-something-nginx': { nginx: 'ok' },
        };

        const normalized = gl.utils.normalizeHeaders(apiHeaders);

        const WORKHORSE = 'X-SOMETHING-WORKHORSE';
        const NGINX = 'X-SOMETHING-NGINX';

        expect(normalized[WORKHORSE].workhorse).toBe('ok');
        expect(normalized[NGINX].nginx).toBe('ok');
      });
    });
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
    describe('gl.utils.normalizeCRLFHeaders', () => {
      beforeEach(function () {
        this.CLRFHeaders = 'a-header: a-value\nAnother-Header: ANOTHER-VALUE\nLaSt-HeAdEr: last-VALUE';

        spyOn(String.prototype, 'split').and.callThrough();
        spyOn(gl.utils, 'normalizeHeaders').and.callThrough();

        this.normalizeCRLFHeaders = gl.utils.normalizeCRLFHeaders(this.CLRFHeaders);
      });

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

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

      it('should call gl.utils.normalizeHeaders with a parsed headers object', function () {
        expect(gl.utils.normalizeHeaders).toHaveBeenCalledWith(jasmine.any(Object));
      });

      it('should return a normalized headers object', function () {
        expect(this.normalizeCRLFHeaders).toEqual({
          'A-HEADER': 'a-value',
          'ANOTHER-HEADER': 'ANOTHER-VALUE',
          'LAST-HEADER': 'last-VALUE',
        });
      });
    });

191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
    describe('gl.utils.parseIntPagination', () => {
      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,
        };

        expect(gl.utils.parseIntPagination(pagination)).toEqual(expectedPagination);
      });
    });

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
    describe('gl.utils.isMetaClick', () => {
      it('should identify meta click on Windows/Linux', () => {
        const e = {
          metaKey: false,
          ctrlKey: true,
          which: 1,
        };

        expect(gl.utils.isMetaClick(e)).toBe(true);
      });

      it('should identify meta click on macOS', () => {
        const e = {
          metaKey: true,
          ctrlKey: false,
          which: 1,
        };

        expect(gl.utils.isMetaClick(e)).toBe(true);
      });

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

        expect(gl.utils.isMetaClick(e)).toBe(true);
      });
    });
246 247 248 249

    describe('gl.utils.backOff', () => {
      it('solves the promise from the callback', (done) => {
        const expectedResponseValue = 'Success!';
250 251
        gl.utils.backOff((next, stop) => (
          new Promise((resolve) => {
252 253 254
            resolve(expectedResponseValue);
          }).then((resp) => {
            stop(resp);
255 256
          })
        )).then((respBackoff) => {
257 258 259 260 261 262 263 264
          expect(respBackoff).toBe(expectedResponseValue);
          done();
        });
      });

      it('catches the rejected promise from the callback ', (done) => {
        const errorMessage = 'Mistakes were made!';
        gl.utils.backOff((next, stop) => {
265
          new Promise((resolve, reject) => {
266 267 268 269 270 271 272 273 274 275 276 277 278 279
            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();
        });
      });

      it('solves the promise correctly after retrying a third time', (done) => {
        let numberOfCalls = 1;
        const expectedResponseValue = 'Success!';
280 281
        gl.utils.backOff((next, stop) => (
          new Promise((resolve) => {
282 283 284 285 286 287 288 289
            resolve(expectedResponseValue);
          }).then((resp) => {
            if (numberOfCalls < 3) {
              numberOfCalls += 1;
              next();
            } else {
              stop(resp);
            }
290 291
          })
        )).then((respBackoff) => {
292 293 294 295 296 297 298 299
          expect(respBackoff).toBe(expectedResponseValue);
          expect(numberOfCalls).toBe(3);
          done();
        });
      }, 10000);

      it('rejects the backOff promise after timing out', (done) => {
        const expectedResponseValue = 'Success!';
300 301
        gl.utils.backOff(next => (
          new Promise((resolve) => {
302
            resolve(expectedResponseValue);
303 304
          }).then(() => {
            setTimeout(next(), 5000); // it will time out
305 306
          })
        ), 3000).catch((errBackoffResp) => {
307 308 309 310 311 312
          expect(errBackoffResp instanceof Error).toBe(true);
          expect(errBackoffResp.message).toBe('BACKOFF_TIMEOUT');
          done();
        });
      }, 10000);
    });
313 314 315

    describe('gl.utils.setFavicon', () => {
      it('should set page favicon to provided favicon', () => {
Luke "Jared" Bennett's avatar
Luke "Jared" Bennett committed
316
        const faviconPath = '//custom_favicon';
317 318 319 320 321 322 323
        const fakeLink = {
          setAttribute() {},
        };

        spyOn(window.document, 'getElementById').and.callFake(() => fakeLink);
        spyOn(fakeLink, 'setAttribute').and.callFake((attr, val) => {
          expect(attr).toEqual('href');
Luke "Jared" Bennett's avatar
Luke "Jared" Bennett committed
324
          expect(val.indexOf(faviconPath) > -1).toBe(true);
325
        });
Luke "Jared" Bennett's avatar
Luke "Jared" Bennett committed
326
        gl.utils.setFavicon(faviconPath);
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
      });
    });

    describe('gl.utils.resetFavicon', () => {
      it('should reset page favicon to tanuki', () => {
        const fakeLink = {
          setAttribute() {},
        };

        spyOn(window.document, 'getElementById').and.callFake(() => fakeLink);
        spyOn(fakeLink, 'setAttribute').and.callFake((attr, val) => {
          expect(attr).toEqual('href');
          expect(val).toMatch(/favicon/);
        });
        gl.utils.resetFavicon();
      });
    });

    describe('gl.utils.setCiStatusFavicon', () => {
      it('should set page favicon to CI status favicon based on provided status', () => {
        const BUILD_URL = `${gl.TEST_HOST}/frontend-fixtures/builds-project/builds/1/status.json`;
Luke "Jared" Bennett's avatar
Luke "Jared" Bennett committed
348
        const FAVICON_PATH = '//icon_status_success';
349 350 351
        const spySetFavicon = spyOn(gl.utils, 'setFavicon').and.stub();
        const spyResetFavicon = spyOn(gl.utils, 'resetFavicon').and.stub();
        spyOn($, 'ajax').and.callFake(function (options) {
Luke "Jared" Bennett's avatar
Luke "Jared" Bennett committed
352 353
          options.success({ favicon: FAVICON_PATH });
          expect(spySetFavicon).toHaveBeenCalledWith(FAVICON_PATH);
354 355 356 357 358 359 360 361 362
          options.success();
          expect(spyResetFavicon).toHaveBeenCalled();
          options.error();
          expect(spyResetFavicon).toHaveBeenCalled();
        });

        gl.utils.setCiStatusFavicon(BUILD_URL);
      });
    });
363 364
  });
})();