debian-mirror-gitlab/spec/javascripts/lib/utils/common_utils_spec.js

908 lines
28 KiB
JavaScript
Raw Normal View History

2018-03-17 18:26:18 +05:30
import axios from '~/lib/utils/axios_utils';
import * as commonUtils from '~/lib/utils/common_utils';
import MockAdapter from 'axios-mock-adapter';
2018-11-08 19:23:39 +05:30
import { faviconDataUrl, overlayDataUrl, faviconWithOverlayDataUrl } from './mock_data';
2019-07-07 11:18:12 +05:30
import breakpointInstance from '~/breakpoints';
2018-03-17 18:26:18 +05:30
2019-03-02 22:35:43 +05:30
const PIXEL_TOLERANCE = 0.2;
/**
* Loads a data URL as the src of an
* {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image|Image}
* and resolves to that Image once loaded.
*
* @param url
* @returns {Promise}
*/
const urlToImage = url =>
new Promise(resolve => {
const img = new Image();
img.onload = function() {
resolve(img);
};
img.src = url;
});
2018-03-17 18:26:18 +05:30
describe('common_utils', () => {
describe('parseUrl', () => {
it('returns an anchor tag with url', () => {
expect(commonUtils.parseUrl('/some/absolute/url').pathname).toContain('some/absolute/url');
});
2018-12-13 13:39:08 +05:30
2018-03-17 18:26:18 +05:30
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');
});
});
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
describe('parseUrlPathname', () => {
it('returns an absolute url when given an absolute url', () => {
expect(commonUtils.parseUrlPathname('/some/absolute/url')).toEqual('/some/absolute/url');
2017-08-17 22:00:37 +05:30
});
2018-03-17 18:26:18 +05:30
it('returns an absolute url when given a relative url', () => {
expect(commonUtils.parseUrlPathname('some/relative/url')).toEqual('/some/relative/url');
2017-08-17 22:00:37 +05:30
});
2018-03-17 18:26:18 +05:30
});
2017-08-17 22:00:37 +05:30
2018-11-20 20:47:30 +05:30
describe('urlParamsToArray', () => {
it('returns empty array for empty querystring', () => {
expect(commonUtils.urlParamsToArray('')).toEqual([]);
});
it('should decode params', () => {
2018-12-13 13:39:08 +05:30
expect(commonUtils.urlParamsToArray('?label_name%5B%5D=test')[0]).toBe('label_name[]=test');
2018-03-17 18:26:18 +05:30
});
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
it('should remove the question mark from the search params', () => {
2018-11-20 20:47:30 +05:30
const paramsArray = commonUtils.urlParamsToArray('?test=thing');
2018-12-13 13:39:08 +05:30
expect(paramsArray[0][0]).not.toBe('?');
2018-03-17 18:26:18 +05:30
});
2018-11-20 20:47:30 +05:30
});
2017-08-17 22:00:37 +05:30
2018-11-20 20:47:30 +05:30
describe('urlParamsToObject', () => {
it('parses path for label with trailing +', () => {
2018-12-13 13:39:08 +05:30
expect(commonUtils.urlParamsToObject('label_name[]=label%2B', {})).toEqual({
2018-11-20 20:47:30 +05:30
label_name: ['label+'],
});
});
2017-08-17 22:00:37 +05:30
2018-11-20 20:47:30 +05:30
it('parses path for milestone with trailing +', () => {
2018-12-13 13:39:08 +05:30
expect(commonUtils.urlParamsToObject('milestone_title=A%2B', {})).toEqual({
2018-11-20 20:47:30 +05:30
milestone_title: 'A+',
});
});
2017-08-17 22:00:37 +05:30
2018-11-20 20:47:30 +05:30
it('parses path for search terms with spaces', () => {
2018-12-13 13:39:08 +05:30
expect(commonUtils.urlParamsToObject('search=two+words', {})).toEqual({
2018-11-20 20:47:30 +05:30
search: 'two words',
});
2017-08-17 22:00:37 +05:30
});
2018-03-17 18:26:18 +05:30
});
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
describe('handleLocationHash', () => {
beforeEach(() => {
spyOn(window.document, 'getElementById').and.callThrough();
});
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
afterEach(() => {
window.history.pushState({}, null, '');
});
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
function expectGetElementIdToHaveBeenCalledWith(elementId) {
expect(window.document.getElementById).toHaveBeenCalledWith(elementId);
}
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
it('decodes hash parameter', () => {
window.history.pushState({}, null, '#random-hash');
commonUtils.handleLocationHash();
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
expectGetElementIdToHaveBeenCalledWith('random-hash');
expectGetElementIdToHaveBeenCalledWith('user-content-random-hash');
});
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
it('decodes cyrillic hash parameter', () => {
window.history.pushState({}, null, '#definição');
commonUtils.handleLocationHash();
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
expectGetElementIdToHaveBeenCalledWith('definição');
expectGetElementIdToHaveBeenCalledWith('user-content-definição');
});
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
it('decodes encoded cyrillic hash parameter', () => {
window.history.pushState({}, null, '#defini%C3%A7%C3%A3o');
commonUtils.handleLocationHash();
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
expectGetElementIdToHaveBeenCalledWith('definição');
expectGetElementIdToHaveBeenCalledWith('user-content-definição');
2017-08-17 22:00:37 +05:30
});
2018-03-17 18:26:18 +05:30
it('scrolls element into view', () => {
document.body.innerHTML += `
<div id="parent">
<div style="height: 2000px;"></div>
<div id="test" style="height: 2000px;"></div>
</div>
`;
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
window.history.pushState({}, null, '#test');
commonUtils.handleLocationHash();
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
expectGetElementIdToHaveBeenCalledWith('test');
2018-12-13 13:39:08 +05:30
2018-03-17 18:26:18 +05:30
expect(window.scrollY).toBe(document.getElementById('test').offsetTop);
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
document.getElementById('parent').remove();
});
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
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>
`;
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
window.history.pushState({}, null, '#test');
commonUtils.handleLocationHash();
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
expectGetElementIdToHaveBeenCalledWith('test');
expectGetElementIdToHaveBeenCalledWith('user-content-test');
2018-12-13 13:39:08 +05:30
2018-03-17 18:26:18 +05:30
expect(window.scrollY).toBe(document.getElementById('user-content-test').offsetTop);
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
document.getElementById('parent').remove();
});
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
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');
2018-12-13 13:39:08 +05:30
2018-03-17 18:26:18 +05:30
expect(window.scrollY).toBe(document.getElementById('user-content-test').offsetTop - 50);
expect(window.scrollBy).toHaveBeenCalledWith(0, -50);
document.getElementById('parent').remove();
});
});
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
describe('historyPushState', () => {
afterEach(() => {
window.history.replaceState({}, null, null);
2017-08-17 22:00:37 +05:30
});
2018-03-17 18:26:18 +05:30
it('should call pushState with the correct path', () => {
spyOn(window.history, 'pushState');
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
commonUtils.historyPushState('newpath?page=2');
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
expect(window.history.pushState).toHaveBeenCalled();
expect(window.history.pushState.calls.allArgs()[0][2]).toContain('newpath?page=2');
});
});
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
describe('parseQueryStringIntoObject', () => {
it('should return object with query parameters', () => {
2018-12-13 13:39:08 +05:30
expect(commonUtils.parseQueryStringIntoObject('scope=all&page=2')).toEqual({
scope: 'all',
page: '2',
});
2018-03-17 18:26:18 +05:30
expect(commonUtils.parseQueryStringIntoObject('scope=all')).toEqual({ scope: 'all' });
expect(commonUtils.parseQueryStringIntoObject()).toEqual({});
});
});
2018-03-27 19:54:05 +05:30
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');
});
});
2018-03-17 18:26:18 +05:30
describe('buildUrlWithCurrentLocation', () => {
it('should build an url with current location and given parameters', () => {
expect(commonUtils.buildUrlWithCurrentLocation()).toEqual(window.location.pathname);
2018-12-13 13:39:08 +05:30
expect(commonUtils.buildUrlWithCurrentLocation('?page=2')).toEqual(
`${window.location.pathname}?page=2`,
);
2018-03-17 18:26:18 +05:30
});
});
2017-09-10 17:25:29 +05:30
2019-03-02 22:35:43 +05:30
describe('debounceByAnimationFrame', () => {
it('debounces a function to allow a maximum of one call per animation frame', done => {
const spy = jasmine.createSpy('spy');
const debouncedSpy = commonUtils.debounceByAnimationFrame(spy);
window.requestAnimationFrame(() => {
debouncedSpy();
debouncedSpy();
window.requestAnimationFrame(() => {
expect(spy).toHaveBeenCalledTimes(1);
done();
});
});
});
});
2018-03-17 18:26:18 +05:30
describe('getParameterByName', () => {
beforeEach(() => {
window.history.pushState({}, null, '?scope=all&p=2');
});
2017-09-10 17:25:29 +05:30
2018-03-17 18:26:18 +05:30
afterEach(() => {
window.history.replaceState({}, null, null);
2017-08-17 22:00:37 +05:30
});
2018-03-17 18:26:18 +05:30
it('should return valid parameter', () => {
const value = commonUtils.getParameterByName('scope');
2018-12-13 13:39:08 +05:30
2018-03-17 18:26:18 +05:30
expect(commonUtils.getParameterByName('p')).toEqual('2');
expect(value).toBe('all');
});
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
it('should return invalid parameter', () => {
const value = commonUtils.getParameterByName('fakeParameter');
2018-12-13 13:39:08 +05:30
2018-03-17 18:26:18 +05:30
expect(value).toBe(null);
});
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
it('should return valid paramentes if URL is provided', () => {
let value = commonUtils.getParameterByName('foo', 'http://cocteau.twins/?foo=bar');
2018-12-13 13:39:08 +05:30
2018-03-17 18:26:18 +05:30
expect(value).toBe('bar');
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
value = commonUtils.getParameterByName('manan', 'http://cocteau.twins/?foo=bar&manan=canchu');
2018-12-13 13:39:08 +05:30
2018-03-17 18:26:18 +05:30
expect(value).toBe('canchu');
2017-08-17 22:00:37 +05:30
});
2018-03-17 18:26:18 +05:30
});
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
describe('normalizedHeaders', () => {
it('should upperCase all the header keys to keep them consistent', () => {
const apiHeaders = {
'X-Something-Workhorse': { workhorse: 'ok' },
'x-something-nginx': { nginx: 'ok' },
};
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
const normalized = commonUtils.normalizeHeaders(apiHeaders);
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
const WORKHORSE = 'X-SOMETHING-WORKHORSE';
const NGINX = 'X-SOMETHING-NGINX';
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
expect(normalized[WORKHORSE].workhorse).toBe('ok');
expect(normalized[NGINX].nginx).toBe('ok');
});
});
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
describe('normalizeCRLFHeaders', () => {
2018-12-13 13:39:08 +05:30
beforeEach(function() {
this.CLRFHeaders =
'a-header: a-value\nAnother-Header: ANOTHER-VALUE\nLaSt-HeAdEr: last-VALUE';
2018-03-17 18:26:18 +05:30
spyOn(String.prototype, 'split').and.callThrough();
this.normalizeCRLFHeaders = commonUtils.normalizeCRLFHeaders(this.CLRFHeaders);
});
2017-08-17 22:00:37 +05:30
2018-12-13 13:39:08 +05:30
it('should split by newline', function() {
2018-03-17 18:26:18 +05:30
expect(String.prototype.split).toHaveBeenCalledWith('\n');
});
2017-08-17 22:00:37 +05:30
2018-12-13 13:39:08 +05:30
it('should split by colon+space for each header', function() {
expect(String.prototype.split.calls.allArgs().filter(args => args[0] === ': ').length).toBe(
3,
);
2017-08-17 22:00:37 +05:30
});
2018-12-13 13:39:08 +05:30
it('should return a normalized headers object', function() {
2018-03-17 18:26:18 +05:30
expect(this.normalizeCRLFHeaders).toEqual({
'A-HEADER': 'a-value',
'ANOTHER-HEADER': 'ANOTHER-VALUE',
'LAST-HEADER': 'last-VALUE',
2017-08-17 22:00:37 +05:30
});
});
2018-03-17 18:26:18 +05:30
});
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
describe('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(commonUtils.parseIntPagination(pagination)).toEqual(expectedPagination);
});
});
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
describe('isMetaClick', () => {
it('should identify meta click on Windows/Linux', () => {
const e = {
metaKey: false,
ctrlKey: true,
which: 1,
};
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
expect(commonUtils.isMetaClick(e)).toBe(true);
});
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
it('should identify meta click on macOS', () => {
const e = {
metaKey: true,
ctrlKey: false,
which: 1,
};
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
expect(commonUtils.isMetaClick(e)).toBe(true);
});
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
it('should identify as meta click on middle-click or Mouse-wheel click', () => {
const e = {
metaKey: false,
ctrlKey: false,
which: 2,
};
expect(commonUtils.isMetaClick(e)).toBe(true);
});
});
2019-07-07 11:18:12 +05:30
describe('contentTop', () => {
it('does not add height for fileTitle or compareVersionsHeader if screen is too small', () => {
spyOn(breakpointInstance, 'isDesktop').and.returnValue(false);
setFixtures(`
<div class="diff-file file-title-flex-parent">
blah blah blah
</div>
<div class="mr-version-controls">
more blah blah blah
</div>
`);
expect(commonUtils.contentTop()).toBe(0);
});
it('adds height for fileTitle and compareVersionsHeader screen is large enough', () => {
spyOn(breakpointInstance, 'isDesktop').and.returnValue(true);
setFixtures(`
<div class="diff-file file-title-flex-parent">
blah blah blah
</div>
<div class="mr-version-controls">
more blah blah blah
</div>
`);
expect(commonUtils.contentTop()).toBe(18);
});
});
2019-02-15 15:39:39 +05:30
describe('parseBoolean', () => {
2019-03-02 22:35:43 +05:30
const { parseBoolean } = commonUtils;
2019-02-15 15:39:39 +05:30
it('returns true for "true"', () => {
2019-03-02 22:35:43 +05:30
expect(parseBoolean('true')).toEqual(true);
2019-02-15 15:39:39 +05:30
});
it('returns false for "false"', () => {
2019-03-02 22:35:43 +05:30
expect(parseBoolean('false')).toEqual(false);
2019-02-15 15:39:39 +05:30
});
it('returns false for "something"', () => {
2019-03-02 22:35:43 +05:30
expect(parseBoolean('something')).toEqual(false);
2019-02-15 15:39:39 +05:30
});
it('returns false for null', () => {
2019-03-02 22:35:43 +05:30
expect(parseBoolean(null)).toEqual(false);
});
it('is idempotent', () => {
const input = ['true', 'false', 'something', null];
input.forEach(value => {
const result = parseBoolean(value);
expect(parseBoolean(result)).toBe(result);
});
2019-02-15 15:39:39 +05:30
});
});
2018-03-17 18:26:18 +05:30
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));
});
2018-12-13 13:39:08 +05:30
it('solves the promise from the callback', done => {
2018-03-17 18:26:18 +05:30
const expectedResponseValue = 'Success!';
2018-12-13 13:39:08 +05:30
commonUtils
.backOff((next, stop) =>
new Promise(resolve => {
resolve(expectedResponseValue);
})
.then(resp => {
stop(resp);
})
.catch(done.fail),
)
.then(respBackoff => {
expect(respBackoff).toBe(expectedResponseValue);
done();
2018-03-17 18:26:18 +05:30
})
2018-12-13 13:39:08 +05:30
.catch(done.fail);
2018-03-17 18:26:18 +05:30
});
2017-08-17 22:00:37 +05:30
2018-12-13 13:39:08 +05:30
it('catches the rejected promise from the callback ', done => {
2018-03-17 18:26:18 +05:30
const errorMessage = 'Mistakes were made!';
2018-12-13 13:39:08 +05:30
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();
});
2018-03-17 18:26:18 +05:30
});
2017-08-17 22:00:37 +05:30
2018-12-13 13:39:08 +05:30
it('solves the promise correctly after retrying a third time', done => {
2018-03-17 18:26:18 +05:30
let numberOfCalls = 1;
const expectedResponseValue = 'Success!';
2018-12-13 13:39:08 +05:30
commonUtils
.backOff((next, stop) =>
Promise.resolve(expectedResponseValue)
.then(resp => {
if (numberOfCalls < 3) {
numberOfCalls += 1;
next();
} else {
stop(resp);
}
})
.catch(done.fail),
)
.then(respBackoff => {
const timeouts = window.setTimeout.calls.allArgs().map(([, timeout]) => timeout);
expect(timeouts).toEqual([2000, 4000]);
expect(respBackoff).toBe(expectedResponseValue);
done();
})
.catch(done.fail);
});
it('rejects the backOff promise after timing out', done => {
2019-02-15 15:39:39 +05:30
commonUtils
.backOff(next => next(), 64000)
.catch(errBackoffResp => {
const timeouts = window.setTimeout.calls.allArgs().map(([, timeout]) => timeout);
2018-12-13 13:39:08 +05:30
2019-02-15 15:39:39 +05:30
expect(timeouts).toEqual([2000, 4000, 8000, 16000, 32000, 32000]);
expect(errBackoffResp instanceof Error).toBe(true);
expect(errBackoffResp.message).toBe('BACKOFF_TIMEOUT');
done();
});
2018-03-17 18:26:18 +05:30
});
});
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
describe('setFavicon', () => {
beforeEach(() => {
const favicon = document.createElement('link');
favicon.setAttribute('id', 'favicon');
favicon.setAttribute('href', 'default/favicon');
2018-11-08 19:23:39 +05:30
favicon.setAttribute('data-default-href', 'default/favicon');
2018-03-17 18:26:18 +05:30
document.body.appendChild(favicon);
});
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
afterEach(() => {
document.body.removeChild(document.getElementById('favicon'));
});
2018-11-20 20:47:30 +05:30
2018-03-17 18:26:18 +05:30
it('should set page favicon to provided favicon', () => {
const faviconPath = '//custom_favicon';
commonUtils.setFavicon(faviconPath);
expect(document.getElementById('favicon').getAttribute('href')).toEqual(faviconPath);
2017-08-17 22:00:37 +05:30
});
2018-03-17 18:26:18 +05:30
});
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
describe('resetFavicon', () => {
beforeEach(() => {
const favicon = document.createElement('link');
favicon.setAttribute('id', 'favicon');
2018-11-08 19:23:39 +05:30
favicon.setAttribute('data-original-href', 'default/favicon');
2018-03-17 18:26:18 +05:30
document.body.appendChild(favicon);
});
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
afterEach(() => {
document.body.removeChild(document.getElementById('favicon'));
2017-08-17 22:00:37 +05:30
});
2018-11-08 19:23:39 +05:30
it('should reset page favicon to the default icon', () => {
const favicon = document.getElementById('favicon');
favicon.setAttribute('href', 'new/favicon');
2018-03-17 18:26:18 +05:30
commonUtils.resetFavicon();
2018-12-13 13:39:08 +05:30
2018-03-17 18:26:18 +05:30
expect(document.getElementById('favicon').getAttribute('href')).toEqual('default/favicon');
});
});
2018-11-08 19:23:39 +05:30
describe('createOverlayIcon', () => {
2018-12-13 13:39:08 +05:30
it('should return the favicon with the overlay', done => {
commonUtils
.createOverlayIcon(faviconDataUrl, overlayDataUrl)
2019-03-02 22:35:43 +05:30
.then(url => Promise.all([urlToImage(url), urlToImage(faviconWithOverlayDataUrl)]))
.then(([actual, expected]) => {
expect(actual).toImageDiffEqual(expected, PIXEL_TOLERANCE);
2018-12-13 13:39:08 +05:30
done();
})
.catch(done.fail);
2018-11-08 19:23:39 +05:30
});
});
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'));
});
2018-12-13 13:39:08 +05:30
it('should set page favicon to provided favicon overlay', done => {
commonUtils
.setFaviconOverlay(overlayDataUrl)
2019-03-02 22:35:43 +05:30
.then(() => document.getElementById('favicon').getAttribute('href'))
.then(url => Promise.all([urlToImage(url), urlToImage(faviconWithOverlayDataUrl)]))
.then(([actual, expected]) => {
expect(actual).toImageDiffEqual(expected, PIXEL_TOLERANCE);
2018-12-13 13:39:08 +05:30
done();
})
.catch(done.fail);
2018-11-08 19:23:39 +05:30
});
});
2018-03-17 18:26:18 +05:30
describe('setCiStatusFavicon', () => {
const BUILD_URL = `${gl.TEST_HOST}/frontend-fixtures/builds-project/-/jobs/1/status.json`;
let mock;
beforeEach(() => {
const favicon = document.createElement('link');
favicon.setAttribute('id', 'favicon');
2018-11-08 19:23:39 +05:30
favicon.setAttribute('href', 'null');
favicon.setAttribute('data-original-href', faviconDataUrl);
2018-03-17 18:26:18 +05:30
document.body.appendChild(favicon);
mock = new MockAdapter(axios);
});
afterEach(() => {
mock.restore();
document.body.removeChild(document.getElementById('favicon'));
});
2018-12-13 13:39:08 +05:30
it('should reset favicon in case of error', done => {
2018-11-20 20:47:30 +05:30
mock.onGet(BUILD_URL).replyOnce(500);
2018-03-17 18:26:18 +05:30
2018-12-13 13:39:08 +05:30
commonUtils.setCiStatusFavicon(BUILD_URL).catch(() => {
const favicon = document.getElementById('favicon');
expect(favicon.getAttribute('href')).toEqual(faviconDataUrl);
done();
});
2018-03-17 18:26:18 +05:30
});
2018-12-13 13:39:08 +05:30
it('should set page favicon to CI status favicon based on provided status', done => {
2018-03-17 18:26:18 +05:30
mock.onGet(BUILD_URL).reply(200, {
2018-11-08 19:23:39 +05:30
favicon: overlayDataUrl,
2017-08-17 22:00:37 +05:30
});
2018-03-17 18:26:18 +05:30
2018-12-13 13:39:08 +05:30
commonUtils
.setCiStatusFavicon(BUILD_URL)
2019-03-02 22:35:43 +05:30
.then(() => document.getElementById('favicon').getAttribute('href'))
.then(url => Promise.all([urlToImage(url), urlToImage(faviconWithOverlayDataUrl)]))
.then(([actual, expected]) => {
expect(actual).toImageDiffEqual(expected, PIXEL_TOLERANCE);
2018-03-17 18:26:18 +05:30
done();
})
.catch(done.fail);
});
});
describe('spriteIcon', () => {
let beforeGon;
beforeEach(() => {
window.gon = window.gon || {};
beforeGon = Object.assign({}, window.gon);
window.gon.sprite_icons = 'icons.svg';
2017-08-17 22:00:37 +05:30
});
2018-03-17 18:26:18 +05:30
afterEach(() => {
window.gon = beforeGon;
});
it('should return the svg for a linked icon', () => {
2018-12-13 13:39:08 +05:30
expect(commonUtils.spriteIcon('test')).toEqual(
'<svg ><use xlink:href="icons.svg#test" /></svg>',
);
2018-03-17 18:26:18 +05:30
});
it('should set svg className when passed', () => {
2018-12-13 13:39:08 +05:30
expect(commonUtils.spriteIcon('test', 'fa fa-test')).toEqual(
'<svg class="fa fa-test"><use xlink:href="icons.svg#test" /></svg>',
);
2018-03-17 18:26:18 +05:30
});
});
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
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);
2018-12-13 13:39:08 +05:30
Object.keys(convertedObj).forEach(prop => {
2018-03-17 18:26:18 +05:30
expect(snakeRegEx.test(prop)).toBeFalsy();
expect(convertedObj[prop]).toBe(mockObj[mappings[prop]]);
2017-08-17 22:00:37 +05:30
});
});
2018-03-17 18:26:18 +05:30
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);
});
2018-11-08 19:23:39 +05:30
it('does not deep-convert by default', () => {
const obj = {
snake_key: {
child_snake_key: 'value',
},
};
2018-12-13 13:39:08 +05:30
expect(commonUtils.convertObjectPropsToCamelCase(obj)).toEqual({
2018-11-08 19:23:39 +05:30
snakeKey: {
child_snake_key: 'value',
},
});
});
2019-03-02 22:35:43 +05:30
describe('with options', () => {
const objWithoutChildren = {
project_name: 'GitLab CE',
group_name: 'GitLab.org',
license_type: 'MIT',
};
2018-11-08 19:23:39 +05:30
2019-03-02 22:35:43 +05:30
const objWithChildren = {
project_name: 'GitLab CE',
group_name: 'GitLab.org',
license_type: 'MIT',
tech_stack: {
backend: 'Ruby',
frontend_framework: 'Vue',
database: 'PostgreSQL',
},
};
2018-11-08 19:23:39 +05:30
2019-03-02 22:35:43 +05:30
describe('when options.deep is true', () => {
it('converts object with child objects', () => {
const obj = {
snake_key: {
child_snake_key: 'value',
},
};
2018-11-08 19:23:39 +05:30
2019-03-02 22:35:43 +05:30
expect(commonUtils.convertObjectPropsToCamelCase(obj, { deep: true })).toEqual({
snakeKey: {
childSnakeKey: 'value',
},
});
});
it('converts array with child objects', () => {
const arr = [
2018-11-08 19:23:39 +05:30
{
child_snake_key: 'value',
},
2019-03-02 22:35:43 +05:30
];
2018-11-08 19:23:39 +05:30
2019-03-02 22:35:43 +05:30
expect(commonUtils.convertObjectPropsToCamelCase(arr, { deep: true })).toEqual([
2018-11-08 19:23:39 +05:30
{
childSnakeKey: 'value',
},
2019-03-02 22:35:43 +05:30
]);
});
it('converts array with child arrays', () => {
const arr = [
[
{
child_snake_key: 'value',
},
],
];
expect(commonUtils.convertObjectPropsToCamelCase(arr, { deep: true })).toEqual([
[
{
childSnakeKey: 'value',
},
],
]);
});
});
describe('when options.dropKeys is provided', () => {
it('discards properties mentioned in `dropKeys` array', () => {
expect(
commonUtils.convertObjectPropsToCamelCase(objWithoutChildren, {
dropKeys: ['group_name'],
}),
).toEqual({
projectName: 'GitLab CE',
licenseType: 'MIT',
});
});
it('discards properties mentioned in `dropKeys` array when `deep` is true', () => {
expect(
commonUtils.convertObjectPropsToCamelCase(objWithChildren, {
deep: true,
dropKeys: ['group_name', 'database'],
}),
).toEqual({
projectName: 'GitLab CE',
licenseType: 'MIT',
techStack: {
backend: 'Ruby',
frontendFramework: 'Vue',
},
});
});
});
describe('when options.ignoreKeyNames is provided', () => {
it('leaves properties mentioned in `ignoreKeyNames` array intact', () => {
expect(
commonUtils.convertObjectPropsToCamelCase(objWithoutChildren, {
ignoreKeyNames: ['group_name'],
}),
).toEqual({
projectName: 'GitLab CE',
licenseType: 'MIT',
group_name: 'GitLab.org',
});
});
it('leaves properties mentioned in `ignoreKeyNames` array intact when `deep` is true', () => {
expect(
commonUtils.convertObjectPropsToCamelCase(objWithChildren, {
deep: true,
ignoreKeyNames: ['group_name', 'frontend_framework'],
}),
).toEqual({
projectName: 'GitLab CE',
group_name: 'GitLab.org',
licenseType: 'MIT',
techStack: {
backend: 'Ruby',
frontend_framework: 'Vue',
database: 'PostgreSQL',
},
});
});
2018-11-08 19:23:39 +05:30
});
});
2017-08-17 22:00:37 +05:30
});
2018-11-18 11:00:15 +05:30
describe('roundOffFloat', () => {
it('Rounds off decimal places of a float number with provided precision', () => {
expect(commonUtils.roundOffFloat(3.141592, 3)).toBe(3.142);
});
it('Rounds off a float number to a whole number when provided precision is zero', () => {
expect(commonUtils.roundOffFloat(3.141592, 0)).toBe(3);
expect(commonUtils.roundOffFloat(3.5, 0)).toBe(4);
});
it('Rounds off float number to nearest 0, 10, 100, 1000 and so on when provided precision is below 0', () => {
expect(commonUtils.roundOffFloat(34567.14159, -1)).toBe(34570);
expect(commonUtils.roundOffFloat(34567.14159, -2)).toBe(34600);
expect(commonUtils.roundOffFloat(34567.14159, -3)).toBe(35000);
expect(commonUtils.roundOffFloat(34567.14159, -4)).toBe(30000);
expect(commonUtils.roundOffFloat(34567.14159, -5)).toBe(0);
});
});
2019-03-02 22:35:43 +05:30
describe('isInViewport', () => {
let el;
beforeEach(() => {
el = document.createElement('div');
});
afterEach(() => {
document.body.removeChild(el);
});
it('returns true when provided `el` is in viewport', () => {
2019-07-07 11:18:12 +05:30
el.setAttribute('style', `position: absolute; right: ${window.innerWidth + 0.2};`);
2019-03-02 22:35:43 +05:30
document.body.appendChild(el);
expect(commonUtils.isInViewport(el)).toBe(true);
});
it('returns false when provided `el` is not in viewport', () => {
el.setAttribute('style', 'position: absolute; top: -1000px; left: -1000px;');
document.body.appendChild(el);
expect(commonUtils.isInViewport(el)).toBe(false);
});
});
2019-07-31 22:56:46 +05:30
describe('isScopedLabel', () => {
it('returns true when `::` is present in title', () => {
expect(commonUtils.isScopedLabel({ title: 'foo::bar' })).toBe(true);
});
it('returns false when `::` is not present', () => {
expect(commonUtils.isScopedLabel({ title: 'foobar' })).toBe(false);
});
});
2018-03-17 18:26:18 +05:30
});