Prettify all spec files

This commit is contained in:
Mike Greiling 2018-10-17 02:13:26 -05:00
parent 5a6fffcffc
commit f666026d71
No known key found for this signature in database
GPG Key ID: 0303DF507FA67596
285 changed files with 5458 additions and 4850 deletions

View File

@ -10,8 +10,8 @@ describe('Ajax Loading Spinner', () => {
AjaxLoadingSpinner.init();
});
it('change current icon with spinner icon and disable link while waiting ajax response', (done) => {
spyOn($, 'ajax').and.callFake((req) => {
it('change current icon with spinner icon and disable link while waiting ajax response', done => {
spyOn($, 'ajax').and.callFake(req => {
const xhr = new XMLHttpRequest();
const ajaxLoadingSpinner = document.querySelector('.js-ajax-loading-spinner');
const icon = ajaxLoadingSpinner.querySelector('i');
@ -33,8 +33,8 @@ describe('Ajax Loading Spinner', () => {
document.querySelector('.js-ajax-loading-spinner').click();
});
it('use original icon again and enabled the link after complete the ajax request', (done) => {
spyOn($, 'ajax').and.callFake((req) => {
it('use original icon again and enabled the link after complete the ajax request', done => {
spyOn($, 'ajax').and.callFake(req => {
const xhr = new XMLHttpRequest();
const ajaxLoadingSpinner = document.querySelector('.js-ajax-loading-spinner');

View File

@ -21,7 +21,7 @@ describe('avatar_helper', () => {
it(`wraps around if id is bigger than ${IDENTICON_BG_COUNT}`, () => {
expect(getIdenticonBackgroundClass(IDENTICON_BG_COUNT + 4)).toEqual('bg5');
expect(getIdenticonBackgroundClass((IDENTICON_BG_COUNT * 5) + 6)).toEqual('bg7');
expect(getIdenticonBackgroundClass(IDENTICON_BG_COUNT * 5 + 6)).toEqual('bg7');
});
});

View File

@ -1,60 +1,60 @@
import BindInOut from '~/behaviors/bind_in_out';
import ClassSpecHelper from '../helpers/class_spec_helper';
describe('BindInOut', function () {
describe('constructor', function () {
beforeEach(function () {
describe('BindInOut', function() {
describe('constructor', function() {
beforeEach(function() {
this.in = {};
this.out = {};
this.bindInOut = new BindInOut(this.in, this.out);
});
it('should set .in', function () {
it('should set .in', function() {
expect(this.bindInOut.in).toBe(this.in);
});
it('should set .out', function () {
it('should set .out', function() {
expect(this.bindInOut.out).toBe(this.out);
});
it('should set .eventWrapper', function () {
it('should set .eventWrapper', function() {
expect(this.bindInOut.eventWrapper).toEqual({});
});
describe('if .in is an input', function () {
beforeEach(function () {
describe('if .in is an input', function() {
beforeEach(function() {
this.bindInOut = new BindInOut({ tagName: 'INPUT' });
});
it('should set .eventType to keyup ', function () {
it('should set .eventType to keyup ', function() {
expect(this.bindInOut.eventType).toEqual('keyup');
});
});
describe('if .in is a textarea', function () {
beforeEach(function () {
describe('if .in is a textarea', function() {
beforeEach(function() {
this.bindInOut = new BindInOut({ tagName: 'TEXTAREA' });
});
it('should set .eventType to keyup ', function () {
it('should set .eventType to keyup ', function() {
expect(this.bindInOut.eventType).toEqual('keyup');
});
});
describe('if .in is not an input or textarea', function () {
beforeEach(function () {
describe('if .in is not an input or textarea', function() {
beforeEach(function() {
this.bindInOut = new BindInOut({ tagName: 'SELECT' });
});
it('should set .eventType to change ', function () {
it('should set .eventType to change ', function() {
expect(this.bindInOut.eventType).toEqual('change');
});
});
});
describe('addEvents', function () {
beforeEach(function () {
describe('addEvents', function() {
beforeEach(function() {
this.in = jasmine.createSpyObj('in', ['addEventListener']);
this.bindInOut = new BindInOut(this.in);
@ -62,25 +62,24 @@ describe('BindInOut', function () {
this.addEvents = this.bindInOut.addEvents();
});
it('should set .eventWrapper.updateOut', function () {
it('should set .eventWrapper.updateOut', function() {
expect(this.bindInOut.eventWrapper.updateOut).toEqual(jasmine.any(Function));
});
it('should call .addEventListener', function () {
expect(this.in.addEventListener)
.toHaveBeenCalledWith(
this.bindInOut.eventType,
this.bindInOut.eventWrapper.updateOut,
);
it('should call .addEventListener', function() {
expect(this.in.addEventListener).toHaveBeenCalledWith(
this.bindInOut.eventType,
this.bindInOut.eventWrapper.updateOut,
);
});
it('should return the instance', function () {
it('should return the instance', function() {
expect(this.addEvents).toBe(this.bindInOut);
});
});
describe('updateOut', function () {
beforeEach(function () {
describe('updateOut', function() {
beforeEach(function() {
this.in = { value: 'the-value' };
this.out = { textContent: 'not-the-value' };
@ -89,17 +88,17 @@ describe('BindInOut', function () {
this.updateOut = this.bindInOut.updateOut();
});
it('should set .out.textContent to .in.value', function () {
it('should set .out.textContent to .in.value', function() {
expect(this.out.textContent).toBe(this.in.value);
});
it('should return the instance', function () {
it('should return the instance', function() {
expect(this.updateOut).toBe(this.bindInOut);
});
});
describe('removeEvents', function () {
beforeEach(function () {
describe('removeEvents', function() {
beforeEach(function() {
this.in = jasmine.createSpyObj('in', ['removeEventListener']);
this.updateOut = () => {};
@ -109,21 +108,20 @@ describe('BindInOut', function () {
this.removeEvents = this.bindInOut.removeEvents();
});
it('should call .removeEventListener', function () {
expect(this.in.removeEventListener)
.toHaveBeenCalledWith(
this.bindInOut.eventType,
this.updateOut,
);
it('should call .removeEventListener', function() {
expect(this.in.removeEventListener).toHaveBeenCalledWith(
this.bindInOut.eventType,
this.updateOut,
);
});
it('should return the instance', function () {
it('should return the instance', function() {
expect(this.removeEvents).toBe(this.bindInOut);
});
});
describe('initAll', function () {
beforeEach(function () {
describe('initAll', function() {
beforeEach(function() {
this.ins = [0, 1, 2];
this.instances = [];
@ -136,43 +134,47 @@ describe('BindInOut', function () {
ClassSpecHelper.itShouldBeAStaticMethod(BindInOut, 'initAll');
it('should call .querySelectorAll', function () {
it('should call .querySelectorAll', function() {
expect(document.querySelectorAll).toHaveBeenCalledWith('*[data-bind-in]');
});
it('should call .map', function () {
it('should call .map', function() {
expect(Array.prototype.map).toHaveBeenCalledWith(jasmine.any(Function));
});
it('should call .init for each element', function () {
it('should call .init for each element', function() {
expect(BindInOut.init.calls.count()).toEqual(3);
});
it('should return an array of instances', function () {
it('should return an array of instances', function() {
expect(this.initAll).toEqual(jasmine.any(Array));
});
});
describe('init', function () {
beforeEach(function () {
spyOn(BindInOut.prototype, 'addEvents').and.callFake(function () { return this; });
spyOn(BindInOut.prototype, 'updateOut').and.callFake(function () { return this; });
describe('init', function() {
beforeEach(function() {
spyOn(BindInOut.prototype, 'addEvents').and.callFake(function() {
return this;
});
spyOn(BindInOut.prototype, 'updateOut').and.callFake(function() {
return this;
});
this.init = BindInOut.init({}, {});
});
ClassSpecHelper.itShouldBeAStaticMethod(BindInOut, 'init');
it('should call .addEvents', function () {
it('should call .addEvents', function() {
expect(BindInOut.prototype.addEvents).toHaveBeenCalled();
});
it('should call .updateOut', function () {
it('should call .updateOut', function() {
expect(BindInOut.prototype.updateOut).toHaveBeenCalled();
});
describe('if no anOut is provided', function () {
beforeEach(function () {
describe('if no anOut is provided', function() {
beforeEach(function() {
this.anIn = { dataset: { bindIn: 'the-data-bind-in' } };
spyOn(document, 'querySelector');
@ -180,9 +182,10 @@ describe('BindInOut', function () {
BindInOut.init(this.anIn);
});
it('should call .querySelector', function () {
expect(document.querySelector)
.toHaveBeenCalledWith(`*[data-bind-out="${this.anIn.dataset.bindIn}"]`);
it('should call .querySelector', function() {
expect(document.querySelector).toHaveBeenCalledWith(
`*[data-bind-out="${this.anIn.dataset.bindIn}"]`,
);
});
});
});

View File

@ -56,7 +56,7 @@ describe('CopyAsGFM', () => {
const fragment = document.createDocumentFragment();
const node = document.createElement('div');
node.innerHTML = html;
Array.from(node.childNodes).forEach((item) => fragment.appendChild(item));
Array.from(node.childNodes).forEach(item => fragment.appendChild(item));
return fragment;
},
}),

View File

@ -13,7 +13,7 @@ describe('Unicode Support Map', () => {
spyOn(JSON, 'stringify').and.returnValue(stringSupportMap);
});
describe('if isLocalStorageAvailable is `true`', function () {
describe('if isLocalStorageAvailable is `true`', function() {
beforeEach(() => {
AccessorUtilities.isLocalStorageAccessSafe.and.returnValue(true);
@ -36,7 +36,7 @@ describe('Unicode Support Map', () => {
});
});
describe('if isLocalStorageAvailable is `false`', function () {
describe('if isLocalStorageAvailable is `false`', function() {
beforeEach(() => {
AccessorUtilities.isLocalStorageAccessSafe.and.returnValue(false);

View File

@ -1,7 +1,7 @@
import $ from 'jquery';
import '~/behaviors/quick_submit';
describe('Quick Submit behavior', function () {
describe('Quick Submit behavior', function() {
const keydownEvent = (options = { keyCode: 13, metaKey: true }) => $.Event('keydown', options);
preloadFixtures('snippets/show.html.raw');

View File

@ -32,18 +32,30 @@ describe('requiresInput', () => {
it('enables submit when all required fields receive input', () => {
$('.js-requires-input').requiresInput();
$('#required1').val('input1').change();
$('#required1')
.val('input1')
.change();
expect(submitButton).toBeDisabled();
$('#optional1').val('input1').change();
$('#optional1')
.val('input1')
.change();
expect(submitButton).toBeDisabled();
$('#required2').val('input2').change();
$('#required3').val('input3').change();
$('#required4').val('input4').change();
$('#required5').val('1').change();
$('#required2')
.val('input2')
.change();
$('#required3')
.val('input3')
.change();
$('#required4')
.val('input4')
.change();
$('#required5')
.val('1')
.change();
expect($('.submit')).not.toBeDisabled();
});

View File

@ -36,12 +36,7 @@ function setupSecretFixture(
placeholderClass = 'js-secret-value-placeholder',
) {
const wrapper = document.createElement('div');
wrapper.innerHTML = generateFixtureMarkup(
secrets,
isRevealed,
valueClass,
placeholderClass,
);
wrapper.innerHTML = generateFixtureMarkup(secrets, isRevealed, valueClass, placeholderClass);
const secretValues = new SecretValues({
container: wrapper.querySelector('.js-secret-container'),
@ -127,12 +122,12 @@ describe('setupSecretValues', () => {
const placeholders = wrapper.querySelectorAll('.js-secret-value-placeholder');
expect(values.length).toEqual(3);
values.forEach((value) => {
values.forEach(value => {
expect(value.classList.contains('hide')).toEqual(true);
});
expect(placeholders.length).toEqual(3);
placeholders.forEach((placeholder) => {
placeholders.forEach(placeholder => {
expect(placeholder.classList.contains('hide')).toEqual(false);
});
});
@ -146,24 +141,24 @@ describe('setupSecretValues', () => {
revealButton.click();
expect(values.length).toEqual(3);
values.forEach((value) => {
values.forEach(value => {
expect(value.classList.contains('hide')).toEqual(false);
});
expect(placeholders.length).toEqual(3);
placeholders.forEach((placeholder) => {
placeholders.forEach(placeholder => {
expect(placeholder.classList.contains('hide')).toEqual(true);
});
revealButton.click();
expect(values.length).toEqual(3);
values.forEach((value) => {
values.forEach(value => {
expect(value.classList.contains('hide')).toEqual(true);
});
expect(placeholders.length).toEqual(3);
placeholders.forEach((placeholder) => {
placeholders.forEach(placeholder => {
expect(placeholder.classList.contains('hide')).toEqual(false);
});
});
@ -175,7 +170,9 @@ describe('setupSecretValues', () => {
it('should toggle values and placeholders', () => {
const wrapper = setupSecretFixture(secrets, false);
// Insert the new dynamic row
wrapper.querySelector('.js-secret-container').insertAdjacentHTML('afterbegin', generateValueMarkup('foobarbazdynamic'));
wrapper
.querySelector('.js-secret-container')
.insertAdjacentHTML('afterbegin', generateValueMarkup('foobarbazdynamic'));
const revealButton = wrapper.querySelector('.js-secret-value-reveal-button');
const values = wrapper.querySelectorAll('.js-secret-value');
@ -184,24 +181,24 @@ describe('setupSecretValues', () => {
revealButton.click();
expect(values.length).toEqual(4);
values.forEach((value) => {
values.forEach(value => {
expect(value.classList.contains('hide')).toEqual(false);
});
expect(placeholders.length).toEqual(4);
placeholders.forEach((placeholder) => {
placeholders.forEach(placeholder => {
expect(placeholder.classList.contains('hide')).toEqual(true);
});
revealButton.click();
expect(values.length).toEqual(4);
values.forEach((value) => {
values.forEach(value => {
expect(value.classList.contains('hide')).toEqual(true);
});
expect(placeholders.length).toEqual(4);
placeholders.forEach((placeholder) => {
placeholders.forEach(placeholder => {
expect(placeholder.classList.contains('hide')).toEqual(false);
});
});

View File

@ -1,21 +1,15 @@
import {
BoxGeometry,
} from 'three/build/three.module';
import { BoxGeometry } from 'three/build/three.module';
import MeshObject from '~/blob/3d_viewer/mesh_object';
describe('Mesh object', () => {
it('defaults to non-wireframe material', () => {
const object = new MeshObject(
new BoxGeometry(10, 10, 10),
);
const object = new MeshObject(new BoxGeometry(10, 10, 10));
expect(object.material.wireframe).toBeFalsy();
});
it('changes to wirefame material', () => {
const object = new MeshObject(
new BoxGeometry(10, 10, 10),
);
const object = new MeshObject(new BoxGeometry(10, 10, 10));
object.changeMaterial('wireframe');
@ -23,18 +17,14 @@ describe('Mesh object', () => {
});
it('scales object down', () => {
const object = new MeshObject(
new BoxGeometry(10, 10, 10),
);
const object = new MeshObject(new BoxGeometry(10, 10, 10));
const { radius } = object.geometry.boundingSphere;
expect(radius).not.toBeGreaterThan(4);
});
it('does not scale object down', () => {
const object = new MeshObject(
new BoxGeometry(1, 1, 1),
);
const object = new MeshObject(new BoxGeometry(1, 1, 1));
const { radius } = object.geometry.boundingSphere;
expect(radius).toBeLessThan(1);

View File

@ -16,10 +16,13 @@ describe('Balsamiq integration spec', () => {
});
describe('successful response', () => {
beforeEach((done) => {
beforeEach(done => {
endpoint = bmprPath;
balsamiqViewer.loadFile(endpoint).then(done).catch(done.fail);
balsamiqViewer
.loadFile(endpoint)
.then(done)
.catch(done.fail);
});
it('does not show loading icon', () => {
@ -32,10 +35,13 @@ describe('Balsamiq integration spec', () => {
});
describe('error getting file', () => {
beforeEach((done) => {
beforeEach(done => {
endpoint = 'invalid/path/to/file.bmpr';
balsamiqViewer.loadFile(endpoint).then(done.fail, null).catch(done);
balsamiqViewer
.loadFile(endpoint)
.then(done.fail, null)
.catch(done);
});
it('does not show loading icon', () => {

View File

@ -18,9 +18,7 @@ describe('BalsamiqViewer', () => {
});
});
describe('fileLoaded', () => {
});
describe('fileLoaded', () => {});
describe('loadFile', () => {
let xhr;
@ -64,12 +62,16 @@ describe('BalsamiqViewer', () => {
viewer = jasmine.createSpyObj('viewer', ['appendChild']);
previews = [document.createElement('ul'), document.createElement('ul')];
balsamiqViewer = jasmine.createSpyObj('balsamiqViewer', ['initDatabase', 'getPreviews', 'renderPreview']);
balsamiqViewer = jasmine.createSpyObj('balsamiqViewer', [
'initDatabase',
'getPreviews',
'renderPreview',
]);
balsamiqViewer.viewer = viewer;
balsamiqViewer.getPreviews.and.returnValue(previews);
balsamiqViewer.renderPreview.and.callFake(preview => preview);
viewer.appendChild.and.callFake((containerElement) => {
viewer.appendChild.and.callFake(containerElement => {
container = containerElement;
});
@ -198,7 +200,9 @@ describe('BalsamiqViewer', () => {
});
it('should call database.exec', () => {
expect(database.exec).toHaveBeenCalledWith(`SELECT * FROM resources WHERE id = '${resourceID}'`);
expect(database.exec).toHaveBeenCalledWith(
`SELECT * FROM resources WHERE id = '${resourceID}'`,
);
});
it('should return the selected resource', () => {
@ -281,7 +285,7 @@ describe('BalsamiqViewer', () => {
expect(BalsamiqViewer.parseTitle).toHaveBeenCalledWith(resource);
});
it('should return the template string', function () {
it('should return the template string', function() {
expect(renderTemplate.replace(/\s/g, '')).toEqual(template.replace(/\s/g, ''));
});
});

View File

@ -1,7 +1,7 @@
import $ from 'jquery';
import BlobFileDropzone from '~/blob/blob_file_dropzone';
describe('BlobFileDropzone', function () {
describe('BlobFileDropzone', function() {
preloadFixtures('blob/show.html.raw');
beforeEach(() => {

View File

@ -16,8 +16,7 @@ describe('BlobForkSuggestion', () => {
cancelButtons: cancelButton,
suggestionSections: suggestionSection,
actionTextPieces: actionTextPiece,
})
.init();
}).init();
});
afterEach(() => {

View File

@ -12,29 +12,27 @@ describe('iPython notebook renderer', () => {
it('shows loading icon', () => {
renderNotebook();
expect(
document.querySelector('.loading'),
).not.toBeNull();
expect(document.querySelector('.loading')).not.toBeNull();
});
describe('successful response', () => {
let mock;
beforeEach((done) => {
beforeEach(done => {
mock = new MockAdapter(axios);
mock.onGet('/test').reply(200, {
cells: [{
cell_type: 'markdown',
source: ['# test'],
}, {
cell_type: 'code',
execution_count: 1,
source: [
'def test(str)',
' return str',
],
outputs: [],
}],
cells: [
{
cell_type: 'markdown',
source: ['# test'],
},
{
cell_type: 'code',
execution_count: 1,
source: ['def test(str)', ' return str'],
outputs: [],
},
],
});
renderNotebook();
@ -49,35 +47,23 @@ describe('iPython notebook renderer', () => {
});
it('does not show loading icon', () => {
expect(
document.querySelector('.loading'),
).toBeNull();
expect(document.querySelector('.loading')).toBeNull();
});
it('renders the notebook', () => {
expect(
document.querySelector('.md'),
).not.toBeNull();
expect(document.querySelector('.md')).not.toBeNull();
});
it('renders the markdown cell', () => {
expect(
document.querySelector('h1'),
).not.toBeNull();
expect(document.querySelector('h1')).not.toBeNull();
expect(
document.querySelector('h1').textContent.trim(),
).toBe('test');
expect(document.querySelector('h1').textContent.trim()).toBe('test');
});
it('highlights code', () => {
expect(
document.querySelector('.token'),
).not.toBeNull();
expect(document.querySelector('.token')).not.toBeNull();
expect(
document.querySelector('.language-python'),
).not.toBeNull();
expect(document.querySelector('.language-python')).not.toBeNull();
});
});
@ -86,12 +72,10 @@ describe('iPython notebook renderer', () => {
beforeEach(done => {
mock = new MockAdapter(axios);
mock
.onGet('/test')
.reply(() =>
// eslint-disable-next-line prefer-promise-reject-errors
Promise.reject({ status: 200, data: '{ "cells": [{"cell_type": "markdown"} }' }),
);
mock.onGet('/test').reply(() =>
// eslint-disable-next-line prefer-promise-reject-errors
Promise.reject({ status: 200, data: '{ "cells": [{"cell_type": "markdown"} }' }),
);
renderNotebook();
@ -105,22 +89,20 @@ describe('iPython notebook renderer', () => {
});
it('does not show loading icon', () => {
expect(
document.querySelector('.loading'),
).toBeNull();
expect(document.querySelector('.loading')).toBeNull();
});
it('shows error message', () => {
expect(
document.querySelector('.md').textContent.trim(),
).toBe('An error occurred whilst parsing the file.');
expect(document.querySelector('.md').textContent.trim()).toBe(
'An error occurred whilst parsing the file.',
);
});
});
describe('error getting file', () => {
let mock;
beforeEach((done) => {
beforeEach(done => {
mock = new MockAdapter(axios);
mock.onGet('/test').reply(500, '');
@ -136,15 +118,13 @@ describe('iPython notebook renderer', () => {
});
it('does not show loading icon', () => {
expect(
document.querySelector('.loading'),
).toBeNull();
expect(document.querySelector('.loading')).toBeNull();
});
it('shows error message', () => {
expect(
document.querySelector('.md').textContent.trim(),
).toBe('An error occurred whilst loading the file. Please try again later.');
expect(document.querySelector('.md').textContent.trim()).toBe(
'An error occurred whilst loading the file. Please try again later.',
);
});
});
});

View File

@ -5,7 +5,7 @@ describe('PDF renderer', () => {
let viewer;
let app;
const checkLoaded = (done) => {
const checkLoaded = done => {
if (app.loading) {
setTimeout(() => {
checkLoaded(done);
@ -26,39 +26,31 @@ describe('PDF renderer', () => {
it('shows loading icon', () => {
renderPDF();
expect(
document.querySelector('.loading'),
).not.toBeNull();
expect(document.querySelector('.loading')).not.toBeNull();
});
describe('successful response', () => {
beforeEach((done) => {
beforeEach(done => {
app = renderPDF();
checkLoaded(done);
});
it('does not show loading icon', () => {
expect(
document.querySelector('.loading'),
).toBeNull();
expect(document.querySelector('.loading')).toBeNull();
});
it('renders the PDF', () => {
expect(
document.querySelector('.pdf-viewer'),
).not.toBeNull();
expect(document.querySelector('.pdf-viewer')).not.toBeNull();
});
it('renders the PDF page', () => {
expect(
document.querySelector('.pdf-page'),
).not.toBeNull();
expect(document.querySelector('.pdf-page')).not.toBeNull();
});
});
describe('error getting file', () => {
beforeEach((done) => {
beforeEach(done => {
viewer.dataset.endpoint = 'invalid/path/to/file.pdf';
app = renderPDF();
@ -66,15 +58,13 @@ describe('PDF renderer', () => {
});
it('does not show loading icon', () => {
expect(
document.querySelector('.loading'),
).toBeNull();
expect(document.querySelector('.loading')).toBeNull();
});
it('shows error message', () => {
expect(
document.querySelector('.md').textContent.trim(),
).toBe('An error occurred whilst loading the file. Please try again later.');
expect(document.querySelector('.md').textContent.trim()).toBe(
'An error occurred whilst loading the file. Please try again later.',
);
});
});
});

View File

@ -4,15 +4,13 @@ import SketchLoader from '~/blob/sketch';
describe('Sketch viewer', () => {
const generateZipFileArrayBuffer = (zipFile, resolve, done) => {
zipFile
.generateAsync({ type: 'arrayBuffer' })
.then((content) => {
resolve(content);
zipFile.generateAsync({ type: 'arrayBuffer' }).then(content => {
resolve(content);
setTimeout(() => {
done();
}, 100);
});
setTimeout(() => {
done();
}, 100);
});
};
preloadFixtures('static/sketch_viewer.html.raw');
@ -22,60 +20,63 @@ describe('Sketch viewer', () => {
});
describe('with error message', () => {
beforeEach((done) => {
spyOn(SketchLoader.prototype, 'getZipFile').and.callFake(() => new Promise((resolve, reject) => {
reject();
beforeEach(done => {
spyOn(SketchLoader.prototype, 'getZipFile').and.callFake(
() =>
new Promise((resolve, reject) => {
reject();
setTimeout(() => {
done();
});
}));
setTimeout(() => {
done();
});
}),
);
new SketchLoader(document.getElementById('js-sketch-viewer'));
});
it('renders error message', () => {
expect(
document.querySelector('#js-sketch-viewer p'),
).not.toBeNull();
expect(document.querySelector('#js-sketch-viewer p')).not.toBeNull();
expect(
document.querySelector('#js-sketch-viewer p').textContent.trim(),
).toContain('Cannot show preview.');
expect(document.querySelector('#js-sketch-viewer p').textContent.trim()).toContain(
'Cannot show preview.',
);
});
it('removes render the loading icon', () => {
expect(
document.querySelector('.js-loading-icon'),
).toBeNull();
expect(document.querySelector('.js-loading-icon')).toBeNull();
});
});
describe('success', () => {
beforeEach((done) => {
spyOn(SketchLoader.prototype, 'getZipFile').and.callFake(() => new Promise((resolve) => {
const zipFile = new JSZip();
zipFile.folder('previews')
.file('preview.png', 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAMAAAAoyzS7AAAAA1BMVEUAAACnej3aAAAAAXRSTlMAQObYZgAAAA1JREFUeNoBAgD9/wAAAAIAAVMrnDAAAAAASUVORK5CYII=', {
base64: true,
});
beforeEach(done => {
spyOn(SketchLoader.prototype, 'getZipFile').and.callFake(
() =>
new Promise(resolve => {
const zipFile = new JSZip();
zipFile
.folder('previews')
.file(
'preview.png',
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAMAAAAoyzS7AAAAA1BMVEUAAACnej3aAAAAAXRSTlMAQObYZgAAAA1JREFUeNoBAgD9/wAAAAIAAVMrnDAAAAAASUVORK5CYII=',
{
base64: true,
},
);
generateZipFileArrayBuffer(zipFile, resolve, done);
}));
generateZipFileArrayBuffer(zipFile, resolve, done);
}),
);
new SketchLoader(document.getElementById('js-sketch-viewer'));
});
it('does not render error message', () => {
expect(
document.querySelector('#js-sketch-viewer p'),
).toBeNull();
expect(document.querySelector('#js-sketch-viewer p')).toBeNull();
});
it('removes render the loading icon', () => {
expect(
document.querySelector('.js-loading-icon'),
).toBeNull();
expect(document.querySelector('.js-loading-icon')).toBeNull();
});
it('renders preview img', () => {
@ -95,24 +96,25 @@ describe('Sketch viewer', () => {
});
describe('incorrect file', () => {
beforeEach((done) => {
spyOn(SketchLoader.prototype, 'getZipFile').and.callFake(() => new Promise((resolve) => {
const zipFile = new JSZip();
beforeEach(done => {
spyOn(SketchLoader.prototype, 'getZipFile').and.callFake(
() =>
new Promise(resolve => {
const zipFile = new JSZip();
generateZipFileArrayBuffer(zipFile, resolve, done);
}));
generateZipFileArrayBuffer(zipFile, resolve, done);
}),
);
new SketchLoader(document.getElementById('js-sketch-viewer'));
});
it('renders error message', () => {
expect(
document.querySelector('#js-sketch-viewer p'),
).not.toBeNull();
expect(document.querySelector('#js-sketch-viewer p')).not.toBeNull();
expect(
document.querySelector('#js-sketch-viewer p').textContent.trim(),
).toContain('Cannot show preview.');
expect(document.querySelector('#js-sketch-viewer p').textContent.trim()).toContain(
'Cannot show preview.',
);
});
});
});

View File

@ -35,12 +35,13 @@ describe('Blob viewer', () => {
window.location.hash = '';
});
it('loads source file after switching views', (done) => {
it('loads source file after switching views', done => {
document.querySelector('.js-blob-viewer-switch-btn[data-viewer="simple"]').click();
setTimeout(() => {
expect(
document.querySelector('.js-blob-viewer-switch-btn[data-viewer="simple"]')
document
.querySelector('.js-blob-viewer-switch-btn[data-viewer="simple"]')
.classList.contains('hidden'),
).toBeFalsy();
@ -48,14 +49,15 @@ describe('Blob viewer', () => {
});
});
it('loads source file when line number is in hash', (done) => {
it('loads source file when line number is in hash', done => {
window.location.hash = '#L1';
new BlobViewer();
setTimeout(() => {
expect(
document.querySelector('.js-blob-viewer-switch-btn[data-viewer="simple"]')
document
.querySelector('.js-blob-viewer-switch-btn[data-viewer="simple"]')
.classList.contains('hidden'),
).toBeFalsy();
@ -63,12 +65,13 @@ describe('Blob viewer', () => {
});
});
it('doesnt reload file if already loaded', (done) => {
const asyncClick = () => new Promise((resolve) => {
document.querySelector('.js-blob-viewer-switch-btn[data-viewer="simple"]').click();
it('doesnt reload file if already loaded', done => {
const asyncClick = () =>
new Promise(resolve => {
document.querySelector('.js-blob-viewer-switch-btn[data-viewer="simple"]').click();
setTimeout(resolve);
});
setTimeout(resolve);
});
asyncClick()
.then(() => asyncClick())
@ -93,15 +96,13 @@ describe('Blob viewer', () => {
});
it('disabled on load', () => {
expect(
copyButton.classList.contains('disabled'),
).toBeTruthy();
expect(copyButton.classList.contains('disabled')).toBeTruthy();
});
it('has tooltip when disabled', () => {
expect(
copyButton.getAttribute('data-original-title'),
).toBe('Switch to the source to copy it to the clipboard');
expect(copyButton.getAttribute('data-original-title')).toBe(
'Switch to the source to copy it to the clipboard',
);
});
it('is blurred when clicked and disabled', () => {
@ -121,25 +122,21 @@ describe('Blob viewer', () => {
expect(copyButton.blur).not.toHaveBeenCalled();
});
it('enables after switching to simple view', (done) => {
it('enables after switching to simple view', done => {
document.querySelector('.js-blob-viewer-switch-btn[data-viewer="simple"]').click();
setTimeout(() => {
expect(
copyButton.classList.contains('disabled'),
).toBeFalsy();
expect(copyButton.classList.contains('disabled')).toBeFalsy();
done();
});
});
it('updates tooltip after switching to simple view', (done) => {
it('updates tooltip after switching to simple view', done => {
document.querySelector('.js-blob-viewer-switch-btn[data-viewer="simple"]').click();
setTimeout(() => {
expect(
copyButton.getAttribute('data-original-title'),
).toBe('Copy source to clipboard');
expect(copyButton.getAttribute('data-original-title')).toBe('Copy source to clipboard');
done();
});
@ -162,9 +159,7 @@ describe('Blob viewer', () => {
blob.switchToViewer('simple');
expect(
simpleBtn.classList.contains('active'),
).toBeTruthy();
expect(simpleBtn.classList.contains('active')).toBeTruthy();
expect(simpleBtn.blur).toHaveBeenCalled();
});

View File

@ -7,29 +7,35 @@ describe('Boards blank state', () => {
let vm;
let fail = false;
beforeEach((done) => {
beforeEach(done => {
const Comp = Vue.extend(BoardBlankState);
boardsStore.create();
gl.boardService = mockBoardService();
spyOn(gl.boardService, 'generateDefaultLists').and.callFake(() => new Promise((resolve, reject) => {
if (fail) {
reject();
} else {
resolve({
data: [{
id: 1,
title: 'To Do',
label: { id: 1 },
}, {
id: 2,
title: 'Doing',
label: { id: 2 },
}],
});
}
}));
spyOn(gl.boardService, 'generateDefaultLists').and.callFake(
() =>
new Promise((resolve, reject) => {
if (fail) {
reject();
} else {
resolve({
data: [
{
id: 1,
title: 'To Do',
label: { id: 1 },
},
{
id: 2,
title: 'Doing',
label: { id: 2 },
},
],
});
}
}),
);
vm = new Comp();
@ -40,20 +46,18 @@ describe('Boards blank state', () => {
});
it('renders pre-defined labels', () => {
expect(
vm.$el.querySelectorAll('.board-blank-state-list li').length,
).toBe(2);
expect(vm.$el.querySelectorAll('.board-blank-state-list li').length).toBe(2);
expect(
vm.$el.querySelectorAll('.board-blank-state-list li')[0].textContent.trim(),
).toEqual('To Do');
expect(vm.$el.querySelectorAll('.board-blank-state-list li')[0].textContent.trim()).toEqual(
'To Do',
);
expect(
vm.$el.querySelectorAll('.board-blank-state-list li')[1].textContent.trim(),
).toEqual('Doing');
expect(vm.$el.querySelectorAll('.board-blank-state-list li')[1].textContent.trim()).toEqual(
'Doing',
);
});
it('clears blank state', (done) => {
it('clears blank state', done => {
vm.$el.querySelector('.btn-default').click();
setTimeout(() => {
@ -63,7 +67,7 @@ describe('Boards blank state', () => {
});
});
it('creates pre-defined labels', (done) => {
it('creates pre-defined labels', done => {
vm.$el.querySelector('.btn-success').click();
setTimeout(() => {
@ -75,7 +79,7 @@ describe('Boards blank state', () => {
});
});
it('resets the store if request fails', (done) => {
it('resets the store if request fails', done => {
fail = true;
vm.$el.querySelector('.btn-success').click();

View File

@ -18,7 +18,7 @@ describe('Board card', () => {
let vm;
let mock;
beforeEach((done) => {
beforeEach(done => {
mock = new MockAdapter(axios);
mock.onAny().reply(boardsMockInterceptor);
@ -71,7 +71,7 @@ describe('Board card', () => {
expect(vm.$el.classList.contains('user-can-drag')).toBe(true);
});
it('does not add user-can-drag class disabled', (done) => {
it('does not add user-can-drag class disabled', done => {
vm.disabled = true;
setTimeout(() => {
@ -84,7 +84,7 @@ describe('Board card', () => {
expect(vm.$el.classList.contains('is-disabled')).toBe(false);
});
it('adds disabled class is disabled is true', (done) => {
it('adds disabled class is disabled is true', done => {
vm.disabled = true;
setTimeout(() => {
@ -96,8 +96,23 @@ describe('Board card', () => {
describe('mouse events', () => {
const triggerEvent = (eventName, el = vm.$el) => {
const event = document.createEvent('MouseEvents');
event.initMouseEvent(eventName, true, true, window, 1, 0, 0, 0, 0, false, false,
false, false, 0, null);
event.initMouseEvent(
eventName,
true,
true,
window,
1,
0,
0,
0,
0,
false,
false,
false,
false,
0,
null,
);
el.dispatchEvent(event);
};
@ -134,13 +149,15 @@ describe('Board card', () => {
expect(boardsStore.detail.issue).toEqual({});
});
it('does not set detail issue if img is clicked', (done) => {
vm.issue.assignees = [new ListAssignee({
id: 1,
name: 'testing 123',
username: 'test',
avatar: 'test_image',
})];
it('does not set detail issue if img is clicked', done => {
vm.issue.assignees = [
new ListAssignee({
id: 1,
name: 'testing 123',
username: 'test',
avatar: 'test_image',
}),
];
Vue.nextTick(() => {
triggerEvent('mouseup', vm.$el.querySelector('img'));
@ -167,7 +184,7 @@ describe('Board card', () => {
expect(boardsStore.detail.list).toEqual(vm.list);
});
it('adds active class if detail issue is set', (done) => {
it('adds active class if detail issue is set', done => {
vm.detailIssue.issue = vm.issue;
Vue.nextTick()

View File

@ -28,7 +28,7 @@ describe('Issue boards new issue form', () => {
return vm.submit(dummySubmitEvent);
};
beforeEach((done) => {
beforeEach(done => {
setFixtures('<div class="test-container"></div>');
const BoardNewIssueComp = Vue.extend(boardNewIssue);
@ -60,7 +60,7 @@ describe('Issue boards new issue form', () => {
mock.restore();
});
it('calls submit if submit button is clicked', (done) => {
it('calls submit if submit button is clicked', done => {
spyOn(vm, 'submit').and.callFake(e => e.preventDefault());
vm.title = 'Testing Title';
@ -78,7 +78,7 @@ describe('Issue boards new issue form', () => {
expect(vm.$el.querySelector('.btn-success').disabled).toBe(true);
});
it('enables submit button if title is not empty', (done) => {
it('enables submit button if title is not empty', done => {
vm.title = 'Testing Title';
Vue.nextTick()
@ -90,7 +90,7 @@ describe('Issue boards new issue form', () => {
.catch(done.fail);
});
it('clears title after clicking cancel', (done) => {
it('clears title after clicking cancel', done => {
vm.$el.querySelector('.btn-default').click();
Vue.nextTick()
@ -101,7 +101,7 @@ describe('Issue boards new issue form', () => {
.catch(done.fail);
});
it('does not create new issue if title is empty', (done) => {
it('does not create new issue if title is empty', done => {
submitIssue()
.then(() => {
expect(list.newIssue).not.toHaveBeenCalled();
@ -111,7 +111,7 @@ describe('Issue boards new issue form', () => {
});
describe('submit success', () => {
it('creates new issue', (done) => {
it('creates new issue', done => {
vm.title = 'submit title';
Vue.nextTick()
@ -123,7 +123,7 @@ describe('Issue boards new issue form', () => {
.catch(done.fail);
});
it('enables button after submit', (done) => {
it('enables button after submit', done => {
vm.title = 'submit issue';
Vue.nextTick()
@ -135,7 +135,7 @@ describe('Issue boards new issue form', () => {
.catch(done.fail);
});
it('clears title after submit', (done) => {
it('clears title after submit', done => {
vm.title = 'submit issue';
Vue.nextTick()
@ -147,7 +147,7 @@ describe('Issue boards new issue form', () => {
.catch(done.fail);
});
it('sets detail issue after submit', (done) => {
it('sets detail issue after submit', done => {
expect(boardsStore.detail.issue.title).toBe(undefined);
vm.title = 'submit issue';
@ -160,7 +160,7 @@ describe('Issue boards new issue form', () => {
.catch(done.fail);
});
it('sets detail list after submit', (done) => {
it('sets detail list after submit', done => {
vm.title = 'submit issue';
Vue.nextTick()
@ -179,7 +179,7 @@ describe('Issue boards new issue form', () => {
vm.title = 'error';
});
it('removes issue', (done) => {
it('removes issue', done => {
Vue.nextTick()
.then(submitIssue)
.then(() => {
@ -189,7 +189,7 @@ describe('Issue boards new issue form', () => {
.catch(done.fail);
});
it('shows error', (done) => {
it('shows error', done => {
Vue.nextTick()
.then(submitIssue)
.then(() => {

View File

@ -23,13 +23,16 @@ describe('Store', () => {
gl.boardService = mockBoardService();
boardsStore.create();
spyOn(gl.boardService, 'moveIssue').and.callFake(() => new Promise((resolve) => {
resolve();
}));
spyOn(gl.boardService, 'moveIssue').and.callFake(
() =>
new Promise(resolve => {
resolve();
}),
);
Cookies.set('issue_board_welcome_hidden', 'false', {
expires: 365 * 10,
path: ''
path: '',
});
});
@ -62,7 +65,7 @@ describe('Store', () => {
expect(list).toBeDefined();
});
it('gets issue when new list added', (done) => {
it('gets issue when new list added', done => {
boardsStore.addList(listObj);
const list = boardsStore.findList('id', listObj.id);
@ -75,7 +78,7 @@ describe('Store', () => {
}, 0);
});
it('persists new list', (done) => {
it('persists new list', done => {
boardsStore.new({
title: 'Test',
list_type: 'label',
@ -83,8 +86,8 @@ describe('Store', () => {
id: 1,
title: 'Testing',
color: 'red',
description: 'testing;'
}
description: 'testing;',
},
});
expect(boardsStore.state.lists.length).toBe(1);
@ -111,7 +114,7 @@ describe('Store', () => {
it('check for blank state adding when closed list exist', () => {
boardsStore.addList({
list_type: 'closed'
list_type: 'closed',
});
expect(boardsStore.shouldAddBlankState()).toBe(true);
@ -146,7 +149,7 @@ describe('Store', () => {
expect(listOne.position).toBe(1);
});
it('moves an issue from one list to another', (done) => {
it('moves an issue from one list to another', done => {
const listOne = boardsStore.addList(listObj);
const listTwo = boardsStore.addList(listObjDuplicate);
@ -165,7 +168,7 @@ describe('Store', () => {
}, 0);
});
it('moves an issue from backlog to a list', (done) => {
it('moves an issue from backlog to a list', done => {
const backlog = boardsStore.addList({
...listObj,
list_type: 'backlog',
@ -187,7 +190,7 @@ describe('Store', () => {
}, 0);
});
it('moves issue to top of another list', (done) => {
it('moves issue to top of another list', done => {
const listOne = boardsStore.addList(listObj);
const listTwo = boardsStore.addList(listObjDuplicate);
@ -210,7 +213,7 @@ describe('Store', () => {
}, 0);
});
it('moves issue to bottom of another list', (done) => {
it('moves issue to bottom of another list', done => {
const listOne = boardsStore.addList(listObj);
const listTwo = boardsStore.addList(listObjDuplicate);
@ -233,7 +236,7 @@ describe('Store', () => {
}, 0);
});
it('moves issue in list', (done) => {
it('moves issue in list', done => {
const issue = new ListIssue({
title: 'Testing',
id: 2,

View File

@ -21,18 +21,22 @@ describe('Issue model', () => {
id: 1,
iid: 1,
confidential: false,
labels: [{
id: 1,
title: 'test',
color: 'red',
description: 'testing'
}],
assignees: [{
id: 1,
name: 'name',
username: 'username',
avatar_url: 'http://avatar_url',
}],
labels: [
{
id: 1,
title: 'test',
color: 'red',
description: 'testing',
},
],
assignees: [
{
id: 1,
name: 'name',
username: 'username',
avatar_url: 'http://avatar_url',
},
],
});
});
@ -45,7 +49,7 @@ describe('Issue model', () => {
id: 2,
title: 'bug',
color: 'blue',
description: 'bugs!'
description: 'bugs!',
});
expect(issue.labels.length).toBe(2);
@ -56,7 +60,7 @@ describe('Issue model', () => {
id: 2,
title: 'test',
color: 'blue',
description: 'bugs!'
description: 'bugs!',
});
expect(issue.labels.length).toBe(1);
@ -80,7 +84,7 @@ describe('Issue model', () => {
id: 2,
title: 'bug',
color: 'blue',
description: 'bugs!'
description: 'bugs!',
});
expect(issue.labels.length).toBe(2);
@ -158,7 +162,7 @@ describe('Issue model', () => {
});
describe('update', () => {
it('passes assignee ids when there are assignees', (done) => {
it('passes assignee ids when there are assignees', done => {
spyOn(Vue.http, 'patch').and.callFake((url, data) => {
expect(data.issue.assignee_ids).toEqual([1]);
done();
@ -167,7 +171,7 @@ describe('Issue model', () => {
issue.update('url');
});
it('passes assignee ids of [0] when there are no assignees', (done) => {
it('passes assignee ids of [0] when there are no assignees', done => {
spyOn(Vue.http, 'patch').and.callFake((url, data) => {
expect(data.issue.assignee_ids).toEqual([0]);
done();

View File

@ -31,21 +31,21 @@ describe('List model', () => {
mock.restore();
});
it('gets issues when created', (done) => {
it('gets issues when created', done => {
setTimeout(() => {
expect(list.issues.length).toBe(1);
done();
}, 0);
});
it('saves list and returns ID', (done) => {
it('saves list and returns ID', done => {
list = new List({
title: 'test',
label: {
id: _.random(10000),
title: 'test',
color: 'red'
}
color: 'red',
},
});
list.save();
@ -57,7 +57,7 @@ describe('List model', () => {
}, 0);
});
it('destroys the list', (done) => {
it('destroys the list', done => {
boardsStore.addList(listObj);
list = boardsStore.findList('id', listObj.id);
@ -70,7 +70,7 @@ describe('List model', () => {
}, 0);
});
it('gets issue from list', (done) => {
it('gets issue from list', done => {
setTimeout(() => {
const issue = list.findIssue(1);
@ -79,7 +79,7 @@ describe('List model', () => {
}, 0);
});
it('removes issue', (done) => {
it('removes issue', done => {
setTimeout(() => {
const issue = list.findIssue(1);
@ -109,8 +109,13 @@ describe('List model', () => {
listDup.updateIssueLabel(issue, list);
expect(gl.boardService.moveIssue)
.toHaveBeenCalledWith(issue.id, list.id, listDup.id, undefined, undefined);
expect(gl.boardService.moveIssue).toHaveBeenCalledWith(
issue.id,
list.id,
listDup.id,
undefined,
undefined,
);
});
describe('page number', () => {
@ -120,14 +125,16 @@ describe('List model', () => {
it('increase page number if current issue count is more than the page size', () => {
for (let i = 0; i < 30; i += 1) {
list.issues.push(new ListIssue({
title: 'Testing',
id: _.random(10000) + i,
iid: _.random(10000) + i,
confidential: false,
labels: [list.label],
assignees: [],
}));
list.issues.push(
new ListIssue({
title: 'Testing',
id: _.random(10000) + i,
iid: _.random(10000) + i,
confidential: false,
labels: [list.label],
assignees: [],
}),
);
}
list.issuesSize = 50;
@ -140,13 +147,15 @@ describe('List model', () => {
});
it('does not increase page number if issue count is less than the page size', () => {
list.issues.push(new ListIssue({
title: 'Testing',
id: _.random(10000),
confidential: false,
labels: [list.label],
assignees: [],
}));
list.issues.push(
new ListIssue({
title: 'Testing',
id: _.random(10000),
confidential: false,
labels: [list.label],
assignees: [],
}),
);
list.issuesSize = 2;
list.nextPage();
@ -158,21 +167,25 @@ describe('List model', () => {
describe('newIssue', () => {
beforeEach(() => {
spyOn(gl.boardService, 'newIssue').and.returnValue(Promise.resolve({
data: {
id: 42,
},
}));
spyOn(gl.boardService, 'newIssue').and.returnValue(
Promise.resolve({
data: {
id: 42,
},
}),
);
});
it('adds new issue to top of list', (done) => {
list.issues.push(new ListIssue({
title: 'Testing',
id: _.random(10000),
confidential: false,
labels: [list.label],
assignees: [],
}));
it('adds new issue to top of list', done => {
list.issues.push(
new ListIssue({
title: 'Testing',
id: _.random(10000),
confidential: false,
labels: [list.label],
assignees: [],
}),
);
const dummyIssue = new ListIssue({
title: 'new issue',
id: _.random(10000),
@ -181,7 +194,8 @@ describe('List model', () => {
assignees: [],
});
list.newIssue(dummyIssue)
list
.newIssue(dummyIssue)
.then(() => {
expect(list.issues.length).toBe(2);
expect(list.issues[0]).toBe(dummyIssue);

View File

@ -3,47 +3,45 @@
import $ from 'jquery';
import '~/commons/bootstrap';
(function() {
describe('Bootstrap jQuery extensions', function() {
describe('disable', function() {
beforeEach(function() {
return setFixtures('<input type="text" />');
});
it('adds the disabled attribute', function() {
var $input;
$input = $('input').first();
$input.disable();
expect($input).toHaveAttr('disabled', 'disabled');
});
return it('adds the disabled class', function() {
var $input;
$input = $('input').first();
$input.disable();
expect($input).toHaveClass('disabled');
});
describe('Bootstrap jQuery extensions', function() {
describe('disable', function() {
beforeEach(function() {
return setFixtures('<input type="text" />');
});
return describe('enable', function() {
beforeEach(function() {
return setFixtures('<input type="text" disabled="disabled" class="disabled" />');
});
it('removes the disabled attribute', function() {
var $input;
$input = $('input').first();
$input.enable();
it('adds the disabled attribute', function() {
var $input;
$input = $('input').first();
$input.disable();
expect($input).not.toHaveAttr('disabled');
});
return it('removes the disabled class', function() {
var $input;
$input = $('input').first();
$input.enable();
expect($input).toHaveAttr('disabled', 'disabled');
});
return it('adds the disabled class', function() {
var $input;
$input = $('input').first();
$input.disable();
expect($input).not.toHaveClass('disabled');
});
expect($input).toHaveClass('disabled');
});
});
}).call(window);
return describe('enable', function() {
beforeEach(function() {
return setFixtures('<input type="text" disabled="disabled" class="disabled" />');
});
it('removes the disabled attribute', function() {
var $input;
$input = $('input').first();
$input.enable();
expect($input).not.toHaveAttr('disabled');
});
return it('removes the disabled class', function() {
var $input;
$input = $('input').first();
$input.enable();
expect($input).not.toHaveClass('disabled');
});
});
});

View File

@ -10,11 +10,12 @@ import LinkedTabs from '~/lib/utils/bootstrap_linked_tabs';
describe('when is initialized', () => {
beforeEach(() => {
spyOn(window.history, 'replaceState').and.callFake(function () {});
spyOn(window.history, 'replaceState').and.callFake(function() {});
});
it('should activate the tab correspondent to the given action', () => {
const linkedTabs = new LinkedTabs({ // eslint-disable-line
const linkedTabs = new LinkedTabs({
// eslint-disable-line
action: 'tab1',
defaultAction: 'tab1',
parentEl: '.linked-tabs',
@ -24,7 +25,8 @@ import LinkedTabs from '~/lib/utils/bootstrap_linked_tabs';
});
it('should active the default tab action when the action is show', () => {
const linkedTabs = new LinkedTabs({ // eslint-disable-line
const linkedTabs = new LinkedTabs({
// eslint-disable-line
action: 'show',
defaultAction: 'tab1',
parentEl: '.linked-tabs',
@ -45,14 +47,21 @@ import LinkedTabs from '~/lib/utils/bootstrap_linked_tabs';
});
const secondTab = document.querySelector('.linked-tabs li:nth-child(2) a');
const newState = secondTab.getAttribute('href') + linkedTabs.currentLocation.search + linkedTabs.currentLocation.hash;
const newState =
secondTab.getAttribute('href') +
linkedTabs.currentLocation.search +
linkedTabs.currentLocation.hash;
secondTab.click();
if (historySpy) {
expect(historySpy).toHaveBeenCalledWith({
url: newState,
}, document.title, newState);
expect(historySpy).toHaveBeenCalledWith(
{
url: newState,
},
document.title,
newState,
);
}
});
});

View File

@ -1,9 +1,7 @@
import bp, {
breakpoints,
} from '~/breakpoints';
import bp, { breakpoints } from '~/breakpoints';
describe('breakpoints', () => {
Object.keys(breakpoints).forEach((key) => {
Object.keys(breakpoints).forEach(key => {
const size = breakpoints[key];
it(`returns ${key} when larger than ${size}`, () => {

View File

@ -43,7 +43,7 @@ describe('AjaxFormVariableList', () => {
});
describe('onSaveClicked', () => {
it('shows loading spinner while waiting for the request', (done) => {
it('shows loading spinner while waiting for the request', done => {
const loadingIcon = saveButton.querySelector('.js-secret-variables-save-loading-icon');
mock.onPatch(VARIABLE_PATCH_ENDPOINT).reply(() => {
@ -54,7 +54,8 @@ describe('AjaxFormVariableList', () => {
expect(loadingIcon.classList.contains(HIDE_CLASS)).toEqual(true);
ajaxVariableList.onSaveClicked()
ajaxVariableList
.onSaveClicked()
.then(() => {
expect(loadingIcon.classList.contains(HIDE_CLASS)).toEqual(true);
})
@ -62,27 +63,30 @@ describe('AjaxFormVariableList', () => {
.catch(done.fail);
});
it('calls `updateRowsWithPersistedVariables` with the persisted variables', (done) => {
it('calls `updateRowsWithPersistedVariables` with the persisted variables', done => {
const variablesResponse = [{ id: 1, key: 'foo', value: 'bar' }];
mock.onPatch(VARIABLE_PATCH_ENDPOINT).reply(200, {
variables: variablesResponse,
});
ajaxVariableList.onSaveClicked()
ajaxVariableList
.onSaveClicked()
.then(() => {
expect(ajaxVariableList.updateRowsWithPersistedVariables)
.toHaveBeenCalledWith(variablesResponse);
expect(ajaxVariableList.updateRowsWithPersistedVariables).toHaveBeenCalledWith(
variablesResponse,
);
})
.then(done)
.catch(done.fail);
});
it('hides any previous error box', (done) => {
it('hides any previous error box', done => {
mock.onPatch(VARIABLE_PATCH_ENDPOINT).reply(200);
expect(errorBox.classList.contains(HIDE_CLASS)).toEqual(true);
ajaxVariableList.onSaveClicked()
ajaxVariableList
.onSaveClicked()
.then(() => {
expect(errorBox.classList.contains(HIDE_CLASS)).toEqual(true);
})
@ -90,14 +94,15 @@ describe('AjaxFormVariableList', () => {
.catch(done.fail);
});
it('disables remove buttons while waiting for the request', (done) => {
it('disables remove buttons while waiting for the request', done => {
mock.onPatch(VARIABLE_PATCH_ENDPOINT).reply(() => {
expect(ajaxVariableList.variableList.toggleEnableRow).toHaveBeenCalledWith(false);
return [200, {}];
});
ajaxVariableList.onSaveClicked()
ajaxVariableList
.onSaveClicked()
.then(() => {
expect(ajaxVariableList.variableList.toggleEnableRow).toHaveBeenCalledWith(true);
})
@ -105,7 +110,7 @@ describe('AjaxFormVariableList', () => {
.catch(done.fail);
});
it('hides secret values', (done) => {
it('hides secret values', done => {
mock.onPatch(VARIABLE_PATCH_ENDPOINT).reply(200, {});
const row = container.querySelector('.js-row:first-child');
@ -118,7 +123,8 @@ describe('AjaxFormVariableList', () => {
expect(valuePlaceholder.classList.contains(HIDE_CLASS)).toBe(true);
expect(valueInput.classList.contains(HIDE_CLASS)).toBe(false);
ajaxVariableList.onSaveClicked()
ajaxVariableList
.onSaveClicked()
.then(() => {
expect(valuePlaceholder.classList.contains(HIDE_CLASS)).toBe(false);
expect(valueInput.classList.contains(HIDE_CLASS)).toBe(true);
@ -127,29 +133,31 @@ describe('AjaxFormVariableList', () => {
.catch(done.fail);
});
it('shows error box with validation errors', (done) => {
it('shows error box with validation errors', done => {
const validationError = 'some validation error';
mock.onPatch(VARIABLE_PATCH_ENDPOINT).reply(400, [
validationError,
]);
mock.onPatch(VARIABLE_PATCH_ENDPOINT).reply(400, [validationError]);
expect(errorBox.classList.contains(HIDE_CLASS)).toEqual(true);
ajaxVariableList.onSaveClicked()
ajaxVariableList
.onSaveClicked()
.then(() => {
expect(errorBox.classList.contains(HIDE_CLASS)).toEqual(false);
expect(errorBox.textContent.trim().replace(/\n+\s+/m, ' ')).toEqual(`Validation failed ${validationError}`);
expect(errorBox.textContent.trim().replace(/\n+\s+/m, ' ')).toEqual(
`Validation failed ${validationError}`,
);
})
.then(done)
.catch(done.fail);
});
it('shows flash message when request fails', (done) => {
it('shows flash message when request fails', done => {
mock.onPatch(VARIABLE_PATCH_ENDPOINT).reply(500);
expect(errorBox.classList.contains(HIDE_CLASS)).toEqual(true);
ajaxVariableList.onSaveClicked()
ajaxVariableList
.onSaveClicked()
.then(() => {
expect(errorBox.classList.contains(HIDE_CLASS)).toEqual(true);
})
@ -200,11 +208,13 @@ describe('AjaxFormVariableList', () => {
expect(idInput.value).toEqual('');
ajaxVariableList.updateRowsWithPersistedVariables([{
id: 3,
key: 'foo',
value: 'bar',
}]);
ajaxVariableList.updateRowsWithPersistedVariables([
{
id: 3,
key: 'foo',
value: 'bar',
},
]);
expect(idInput.value).toEqual('3');
expect(row.dataset.isPersisted).toEqual('true');

View File

@ -33,7 +33,8 @@ describe('VariableList', () => {
it('should add another row when editing the last rows key input', () => {
const $row = $wrapper.find('.js-row');
$row.find('.js-ci-variable-input-key')
$row
.find('.js-ci-variable-input-key')
.val('foo')
.trigger('input');
@ -47,7 +48,8 @@ describe('VariableList', () => {
it('should add another row when editing the last rows value textarea', () => {
const $row = $wrapper.find('.js-row');
$row.find('.js-ci-variable-input-value')
$row
.find('.js-ci-variable-input-value')
.val('foo')
.trigger('input');
@ -61,13 +63,15 @@ describe('VariableList', () => {
it('should remove empty row after blurring', () => {
const $row = $wrapper.find('.js-row');
$row.find('.js-ci-variable-input-key')
$row
.find('.js-ci-variable-input-key')
.val('foo')
.trigger('input');
expect($wrapper.find('.js-row').length).toBe(2);
$row.find('.js-ci-variable-input-key')
$row
.find('.js-ci-variable-input-key')
.val('')
.trigger('input')
.trigger('blur');
@ -121,7 +125,7 @@ describe('VariableList', () => {
variableList.init();
});
it('should add another row when editing the last rows protected checkbox', (done) => {
it('should add another row when editing the last rows protected checkbox', done => {
const $row = $wrapper.find('.js-row:last-child');
$row.find('.ci-variable-protected-item .js-project-feature-toggle').click();
@ -130,7 +134,9 @@ describe('VariableList', () => {
expect($wrapper.find('.js-row').length).toBe(2);
// Check for the correct default in the new row
const $protectedInput = $wrapper.find('.js-row:last-child').find('.js-ci-variable-input-protected');
const $protectedInput = $wrapper
.find('.js-row:last-child')
.find('.js-ci-variable-input-protected');
expect($protectedInput.val()).toBe('false');
})
@ -205,7 +211,8 @@ describe('VariableList', () => {
const $inputValue = $row.find('.js-ci-variable-input-value');
const $placeholder = $row.find('.js-secret-value-placeholder');
$row.find('.js-ci-variable-input-value')
$row
.find('.js-ci-variable-input-value')
.val('foo')
.trigger('input');

View File

@ -20,8 +20,12 @@ describe('NativeFormVariableList', () => {
it('should clear out the `name` attribute on the inputs for the last empty row on form submission (avoid BE validation)', () => {
const $row = $wrapper.find('.js-row');
expect($row.find('.js-ci-variable-input-key').attr('name')).toBe('schedule[variables_attributes][][key]');
expect($row.find('.js-ci-variable-input-value').attr('name')).toBe('schedule[variables_attributes][][secret_value]');
expect($row.find('.js-ci-variable-input-key').attr('name')).toBe(
'schedule[variables_attributes][][key]',
);
expect($row.find('.js-ci-variable-input-value').attr('name')).toBe(
'schedule[variables_attributes][][secret_value]',
);
$wrapper.closest('form').trigger('trigger-submit');

View File

@ -10,7 +10,7 @@ describe('CloseReopenReportToggle', () => {
const button = {};
let commentTypeToggle;
beforeEach(function () {
beforeEach(function() {
commentTypeToggle = new CloseReopenReportToggle({
dropdownTrigger,
dropdownList,
@ -18,15 +18,15 @@ describe('CloseReopenReportToggle', () => {
});
});
it('sets .dropdownTrigger', function () {
it('sets .dropdownTrigger', function() {
expect(commentTypeToggle.dropdownTrigger).toBe(dropdownTrigger);
});
it('sets .dropdownList', function () {
it('sets .dropdownList', function() {
expect(commentTypeToggle.dropdownList).toBe(dropdownList);
});
it('sets .button', function () {
it('sets .button', function() {
expect(commentTypeToggle.button).toBe(button);
});
});

View File

@ -21,21 +21,21 @@ describe('Clusters', () => {
});
describe('toggle', () => {
it('should update the button and the input field on click', (done) => {
const toggleButton = document.querySelector('.js-cluster-enable-toggle-area .js-project-feature-toggle');
const toggleInput = document.querySelector('.js-cluster-enable-toggle-area .js-project-feature-toggle-input');
it('should update the button and the input field on click', done => {
const toggleButton = document.querySelector(
'.js-cluster-enable-toggle-area .js-project-feature-toggle',
);
const toggleInput = document.querySelector(
'.js-cluster-enable-toggle-area .js-project-feature-toggle-input',
);
toggleButton.click();
getSetTimeoutPromise()
.then(() => {
expect(
toggleButton.classList,
).not.toContain('is-checked');
expect(toggleButton.classList).not.toContain('is-checked');
expect(
toggleInput.getAttribute('value'),
).toEqual('false');
expect(toggleInput.getAttribute('value')).toEqual('false');
})
.then(done)
.catch(done.fail);
@ -46,29 +46,21 @@ describe('Clusters', () => {
it('should update token field type', () => {
cluster.showTokenButton.click();
expect(
cluster.tokenField.getAttribute('type'),
).toEqual('text');
expect(cluster.tokenField.getAttribute('type')).toEqual('text');
cluster.showTokenButton.click();
expect(
cluster.tokenField.getAttribute('type'),
).toEqual('password');
expect(cluster.tokenField.getAttribute('type')).toEqual('password');
});
it('should update show token button text', () => {
cluster.showTokenButton.click();
expect(
cluster.showTokenButton.textContent,
).toEqual('Hide');
expect(cluster.showTokenButton.textContent).toEqual('Hide');
cluster.showTokenButton.click();
expect(
cluster.showTokenButton.textContent,
).toEqual('Show');
expect(cluster.showTokenButton.textContent).toEqual('Show');
});
});
@ -91,35 +83,45 @@ describe('Clusters', () => {
});
it('shows an alert when something gets newly installed', () => {
cluster.checkForNewInstalls({
...INITIAL_APP_MAP,
helm: { status: APPLICATION_STATUS.INSTALLING, title: 'Helm Tiller' },
}, {
...INITIAL_APP_MAP,
helm: { status: APPLICATION_STATUS.INSTALLED, title: 'Helm Tiller' },
});
cluster.checkForNewInstalls(
{
...INITIAL_APP_MAP,
helm: { status: APPLICATION_STATUS.INSTALLING, title: 'Helm Tiller' },
},
{
...INITIAL_APP_MAP,
helm: { status: APPLICATION_STATUS.INSTALLED, title: 'Helm Tiller' },
},
);
const flashMessage = document.querySelector('.js-cluster-application-notice .flash-text');
expect(flashMessage).not.toBeNull();
expect(flashMessage.textContent.trim()).toEqual('Helm Tiller was successfully installed on your Kubernetes cluster');
expect(flashMessage.textContent.trim()).toEqual(
'Helm Tiller was successfully installed on your Kubernetes cluster',
);
});
it('shows an alert when multiple things gets newly installed', () => {
cluster.checkForNewInstalls({
...INITIAL_APP_MAP,
helm: { status: APPLICATION_STATUS.INSTALLING, title: 'Helm Tiller' },
ingress: { status: APPLICATION_STATUS.INSTALLABLE, title: 'Ingress' },
}, {
...INITIAL_APP_MAP,
helm: { status: APPLICATION_STATUS.INSTALLED, title: 'Helm Tiller' },
ingress: { status: APPLICATION_STATUS.INSTALLED, title: 'Ingress' },
});
cluster.checkForNewInstalls(
{
...INITIAL_APP_MAP,
helm: { status: APPLICATION_STATUS.INSTALLING, title: 'Helm Tiller' },
ingress: { status: APPLICATION_STATUS.INSTALLABLE, title: 'Ingress' },
},
{
...INITIAL_APP_MAP,
helm: { status: APPLICATION_STATUS.INSTALLED, title: 'Helm Tiller' },
ingress: { status: APPLICATION_STATUS.INSTALLED, title: 'Ingress' },
},
);
const flashMessage = document.querySelector('.js-cluster-application-notice .flash-text');
expect(flashMessage).not.toBeNull();
expect(flashMessage.textContent.trim()).toEqual('Helm Tiller, Ingress was successfully installed on your Kubernetes cluster');
expect(flashMessage.textContent.trim()).toEqual(
'Helm Tiller, Ingress was successfully installed on your Kubernetes cluster',
);
});
});
@ -128,33 +130,21 @@ describe('Clusters', () => {
it('should show the creating container', () => {
cluster.updateContainer(null, 'creating');
expect(
cluster.creatingContainer.classList.contains('hidden'),
).toBeFalsy();
expect(cluster.creatingContainer.classList.contains('hidden')).toBeFalsy();
expect(
cluster.successContainer.classList.contains('hidden'),
).toBeTruthy();
expect(cluster.successContainer.classList.contains('hidden')).toBeTruthy();
expect(
cluster.errorContainer.classList.contains('hidden'),
).toBeTruthy();
expect(cluster.errorContainer.classList.contains('hidden')).toBeTruthy();
});
it('should continue to show `creating` banner with subsequent updates of the same status', () => {
cluster.updateContainer('creating', 'creating');
expect(
cluster.creatingContainer.classList.contains('hidden'),
).toBeFalsy();
expect(cluster.creatingContainer.classList.contains('hidden')).toBeFalsy();
expect(
cluster.successContainer.classList.contains('hidden'),
).toBeTruthy();
expect(cluster.successContainer.classList.contains('hidden')).toBeTruthy();
expect(
cluster.errorContainer.classList.contains('hidden'),
).toBeTruthy();
expect(cluster.errorContainer.classList.contains('hidden')).toBeTruthy();
});
});
@ -162,33 +152,21 @@ describe('Clusters', () => {
it('should show the success container and fresh the page', () => {
cluster.updateContainer(null, 'created');
expect(
cluster.creatingContainer.classList.contains('hidden'),
).toBeTruthy();
expect(cluster.creatingContainer.classList.contains('hidden')).toBeTruthy();
expect(
cluster.successContainer.classList.contains('hidden'),
).toBeFalsy();
expect(cluster.successContainer.classList.contains('hidden')).toBeFalsy();
expect(
cluster.errorContainer.classList.contains('hidden'),
).toBeTruthy();
expect(cluster.errorContainer.classList.contains('hidden')).toBeTruthy();
});
it('should not show a banner when status is already `created`', () => {
cluster.updateContainer('created', 'created');
expect(
cluster.creatingContainer.classList.contains('hidden'),
).toBeTruthy();
expect(cluster.creatingContainer.classList.contains('hidden')).toBeTruthy();
expect(
cluster.successContainer.classList.contains('hidden'),
).toBeTruthy();
expect(cluster.successContainer.classList.contains('hidden')).toBeTruthy();
expect(
cluster.errorContainer.classList.contains('hidden'),
).toBeTruthy();
expect(cluster.errorContainer.classList.contains('hidden')).toBeTruthy();
});
});
@ -196,43 +174,29 @@ describe('Clusters', () => {
it('should show the error container', () => {
cluster.updateContainer(null, 'errored', 'this is an error');
expect(
cluster.creatingContainer.classList.contains('hidden'),
).toBeTruthy();
expect(cluster.creatingContainer.classList.contains('hidden')).toBeTruthy();
expect(
cluster.successContainer.classList.contains('hidden'),
).toBeTruthy();
expect(cluster.successContainer.classList.contains('hidden')).toBeTruthy();
expect(
cluster.errorContainer.classList.contains('hidden'),
).toBeFalsy();
expect(cluster.errorContainer.classList.contains('hidden')).toBeFalsy();
expect(
cluster.errorReasonContainer.textContent,
).toContain('this is an error');
expect(cluster.errorReasonContainer.textContent).toContain('this is an error');
});
it('should show `error` banner when previously `creating`', () => {
cluster.updateContainer('creating', 'errored');
expect(
cluster.creatingContainer.classList.contains('hidden'),
).toBeTruthy();
expect(cluster.creatingContainer.classList.contains('hidden')).toBeTruthy();
expect(
cluster.successContainer.classList.contains('hidden'),
).toBeTruthy();
expect(cluster.successContainer.classList.contains('hidden')).toBeTruthy();
expect(
cluster.errorContainer.classList.contains('hidden'),
).toBeFalsy();
expect(cluster.errorContainer.classList.contains('hidden')).toBeFalsy();
});
});
});
describe('installApplication', () => {
it('tries to install helm', (done) => {
it('tries to install helm', done => {
spyOn(cluster.service, 'installApplication').and.returnValue(Promise.resolve());
expect(cluster.store.state.applications.helm.requestStatus).toEqual(null);
@ -252,7 +216,7 @@ describe('Clusters', () => {
.catch(done.fail);
});
it('tries to install ingress', (done) => {
it('tries to install ingress', done => {
spyOn(cluster.service, 'installApplication').and.returnValue(Promise.resolve());
expect(cluster.store.state.applications.ingress.requestStatus).toEqual(null);
@ -272,7 +236,7 @@ describe('Clusters', () => {
.catch(done.fail);
});
it('tries to install runner', (done) => {
it('tries to install runner', done => {
spyOn(cluster.service, 'installApplication').and.returnValue(Promise.resolve());
expect(cluster.store.state.applications.runner.requestStatus).toEqual(null);
@ -292,27 +256,34 @@ describe('Clusters', () => {
.catch(done.fail);
});
it('tries to install jupyter', (done) => {
it('tries to install jupyter', done => {
spyOn(cluster.service, 'installApplication').and.returnValue(Promise.resolve());
expect(cluster.store.state.applications.jupyter.requestStatus).toEqual(null);
cluster.installApplication({ id: 'jupyter', params: { hostname: cluster.store.state.applications.jupyter.hostname } });
cluster.installApplication({
id: 'jupyter',
params: { hostname: cluster.store.state.applications.jupyter.hostname },
});
expect(cluster.store.state.applications.jupyter.requestStatus).toEqual(REQUEST_LOADING);
expect(cluster.store.state.applications.jupyter.requestReason).toEqual(null);
expect(cluster.service.installApplication).toHaveBeenCalledWith('jupyter', { hostname: cluster.store.state.applications.jupyter.hostname });
expect(cluster.service.installApplication).toHaveBeenCalledWith('jupyter', {
hostname: cluster.store.state.applications.jupyter.hostname,
});
getSetTimeoutPromise()
.then(() => {
expect(cluster.store.state.applications.jupyter.requestStatus).toEqual(REQUEST_SUCCESS);
expect(cluster.store.state.applications.jupyter.requestReason).toEqual(null);
})
.then(done)
.catch(done.fail);
.then(() => {
expect(cluster.store.state.applications.jupyter.requestStatus).toEqual(REQUEST_SUCCESS);
expect(cluster.store.state.applications.jupyter.requestReason).toEqual(null);
})
.then(done)
.catch(done.fail);
});
it('sets error request status when the request fails', (done) => {
spyOn(cluster.service, 'installApplication').and.returnValue(Promise.reject(new Error('STUBBED ERROR')));
it('sets error request status when the request fails', done => {
spyOn(cluster.service, 'installApplication').and.returnValue(
Promise.reject(new Error('STUBBED ERROR')),
);
expect(cluster.store.state.applications.helm.requestStatus).toEqual(null);

View File

@ -215,7 +215,9 @@ describe('Application Row', () => {
status: null,
requestStatus: null,
});
const generalErrorMessage = vm.$el.querySelector('.js-cluster-application-general-error-message');
const generalErrorMessage = vm.$el.querySelector(
'.js-cluster-application-general-error-message',
);
expect(generalErrorMessage).toBeNull();
});
@ -227,10 +229,16 @@ describe('Application Row', () => {
status: APPLICATION_STATUS.ERROR,
statusReason,
});
const generalErrorMessage = vm.$el.querySelector('.js-cluster-application-general-error-message');
const statusErrorMessage = vm.$el.querySelector('.js-cluster-application-status-error-message');
const generalErrorMessage = vm.$el.querySelector(
'.js-cluster-application-general-error-message',
);
const statusErrorMessage = vm.$el.querySelector(
'.js-cluster-application-status-error-message',
);
expect(generalErrorMessage.textContent.trim()).toEqual(`Something went wrong while installing ${DEFAULT_APPLICATION_STATE.title}`);
expect(generalErrorMessage.textContent.trim()).toEqual(
`Something went wrong while installing ${DEFAULT_APPLICATION_STATE.title}`,
);
expect(statusErrorMessage.textContent.trim()).toEqual(statusReason);
});
@ -242,10 +250,16 @@ describe('Application Row', () => {
requestStatus: REQUEST_FAILURE,
requestReason,
});
const generalErrorMessage = vm.$el.querySelector('.js-cluster-application-general-error-message');
const requestErrorMessage = vm.$el.querySelector('.js-cluster-application-request-error-message');
const generalErrorMessage = vm.$el.querySelector(
'.js-cluster-application-general-error-message',
);
const requestErrorMessage = vm.$el.querySelector(
'.js-cluster-application-request-error-message',
);
expect(generalErrorMessage.textContent.trim()).toEqual(`Something went wrong while installing ${DEFAULT_APPLICATION_STATE.title}`);
expect(generalErrorMessage.textContent.trim()).toEqual(
`Something went wrong while installing ${DEFAULT_APPLICATION_STATE.title}`,
);
expect(requestErrorMessage.textContent.trim()).toEqual(requestReason);
});
});

View File

@ -6,67 +6,77 @@ const CLUSTERS_MOCK_DATA = {
data: {
status: 'errored',
status_reason: 'Failed to request to CloudPlatform.',
applications: [{
name: 'helm',
status: APPLICATION_STATUS.INSTALLABLE,
status_reason: null,
}, {
name: 'ingress',
status: APPLICATION_STATUS.ERROR,
status_reason: 'Cannot connect',
external_ip: null,
}, {
name: 'runner',
status: APPLICATION_STATUS.INSTALLING,
status_reason: null,
},
{
name: 'prometheus',
status: APPLICATION_STATUS.ERROR,
status_reason: 'Cannot connect',
}, {
name: 'jupyter',
status: APPLICATION_STATUS.INSTALLING,
status_reason: 'Cannot connect',
}],
applications: [
{
name: 'helm',
status: APPLICATION_STATUS.INSTALLABLE,
status_reason: null,
},
{
name: 'ingress',
status: APPLICATION_STATUS.ERROR,
status_reason: 'Cannot connect',
external_ip: null,
},
{
name: 'runner',
status: APPLICATION_STATUS.INSTALLING,
status_reason: null,
},
{
name: 'prometheus',
status: APPLICATION_STATUS.ERROR,
status_reason: 'Cannot connect',
},
{
name: 'jupyter',
status: APPLICATION_STATUS.INSTALLING,
status_reason: 'Cannot connect',
},
],
},
},
'/gitlab-org/gitlab-shell/clusters/2/status.json': {
data: {
status: 'errored',
status_reason: 'Failed to request to CloudPlatform.',
applications: [{
name: 'helm',
status: APPLICATION_STATUS.INSTALLED,
status_reason: null,
}, {
name: 'ingress',
status: APPLICATION_STATUS.INSTALLED,
status_reason: 'Cannot connect',
external_ip: '1.1.1.1',
}, {
name: 'runner',
status: APPLICATION_STATUS.INSTALLING,
status_reason: null,
},
{
name: 'prometheus',
status: APPLICATION_STATUS.ERROR,
status_reason: 'Cannot connect',
}, {
name: 'jupyter',
status: APPLICATION_STATUS.INSTALLABLE,
status_reason: 'Cannot connect',
}],
applications: [
{
name: 'helm',
status: APPLICATION_STATUS.INSTALLED,
status_reason: null,
},
{
name: 'ingress',
status: APPLICATION_STATUS.INSTALLED,
status_reason: 'Cannot connect',
external_ip: '1.1.1.1',
},
{
name: 'runner',
status: APPLICATION_STATUS.INSTALLING,
status_reason: null,
},
{
name: 'prometheus',
status: APPLICATION_STATUS.ERROR,
status_reason: 'Cannot connect',
},
{
name: 'jupyter',
status: APPLICATION_STATUS.INSTALLABLE,
status_reason: 'Cannot connect',
},
],
},
},
},
POST: {
'/gitlab-org/gitlab-shell/clusters/1/applications/helm': { },
'/gitlab-org/gitlab-shell/clusters/1/applications/ingress': { },
'/gitlab-org/gitlab-shell/clusters/1/applications/runner': { },
'/gitlab-org/gitlab-shell/clusters/1/applications/prometheus': { },
'/gitlab-org/gitlab-shell/clusters/1/applications/jupyter': { },
'/gitlab-org/gitlab-shell/clusters/1/applications/helm': {},
'/gitlab-org/gitlab-shell/clusters/1/applications/ingress': {},
'/gitlab-org/gitlab-shell/clusters/1/applications/runner': {},
'/gitlab-org/gitlab-shell/clusters/1/applications/prometheus': {},
'/gitlab-org/gitlab-shell/clusters/1/applications/jupyter': {},
},
};
@ -81,7 +91,4 @@ const DEFAULT_APPLICATION_STATE = {
requestReason: null,
};
export {
CLUSTERS_MOCK_DATA,
DEFAULT_APPLICATION_STATE,
};
export { CLUSTERS_MOCK_DATA, DEFAULT_APPLICATION_STATE };

View File

@ -53,7 +53,8 @@ describe('Clusters Store', () => {
describe('updateStateFromServer', () => {
it('should store new polling data from server', () => {
const mockResponseData = CLUSTERS_MOCK_DATA.GET['/gitlab-org/gitlab-shell/clusters/1/status.json'].data;
const mockResponseData =
CLUSTERS_MOCK_DATA.GET['/gitlab-org/gitlab-shell/clusters/1/status.json'].data;
store.updateStateFromServer(mockResponseData);
expect(store.state).toEqual({
@ -104,13 +105,14 @@ describe('Clusters Store', () => {
});
it('sets default hostname for jupyter when ingress has a ip address', () => {
const mockResponseData = CLUSTERS_MOCK_DATA.GET['/gitlab-org/gitlab-shell/clusters/2/status.json'].data;
const mockResponseData =
CLUSTERS_MOCK_DATA.GET['/gitlab-org/gitlab-shell/clusters/2/status.json'].data;
store.updateStateFromServer(mockResponseData);
expect(
store.state.applications.jupyter.hostname,
).toEqual(`jupyter.${store.state.applications.ingress.externalIp}.nip.io`);
expect(store.state.applications.jupyter.hostname).toEqual(
`jupyter.${store.state.applications.ingress.externalIp}.nip.io`,
);
});
});
});

View File

@ -18,10 +18,8 @@ describe('Issuable right sidebar collapsed todo toggle', () => {
new Sidebar();
loadFixtures(fixtureName);
document.querySelector('.js-right-sidebar')
.classList.toggle('right-sidebar-expanded');
document.querySelector('.js-right-sidebar')
.classList.toggle('right-sidebar-collapsed');
document.querySelector('.js-right-sidebar').classList.toggle('right-sidebar-expanded');
document.querySelector('.js-right-sidebar').classList.toggle('right-sidebar-collapsed');
mock = new MockAdapter(axios);
@ -44,9 +42,7 @@ describe('Issuable right sidebar collapsed todo toggle', () => {
});
it('shows add todo button', () => {
expect(
document.querySelector('.js-issuable-todo.sidebar-collapsed-icon'),
).not.toBeNull();
expect(document.querySelector('.js-issuable-todo.sidebar-collapsed-icon')).not.toBeNull();
expect(
document.querySelector('.js-issuable-todo.sidebar-collapsed-icon .fa-plus-square'),
@ -63,7 +59,7 @@ describe('Issuable right sidebar collapsed todo toggle', () => {
).toBe('Add todo');
});
it('toggle todo state', (done) => {
it('toggle todo state', done => {
document.querySelector('.js-issuable-todo.sidebar-collapsed-icon').click();
setTimeout(() => {
@ -79,7 +75,7 @@ describe('Issuable right sidebar collapsed todo toggle', () => {
});
});
it('toggle todo state of expanded todo toggle', (done) => {
it('toggle todo state of expanded todo toggle', done => {
document.querySelector('.js-issuable-todo.sidebar-collapsed-icon').click();
setTimeout(() => {
@ -91,19 +87,21 @@ describe('Issuable right sidebar collapsed todo toggle', () => {
});
});
it('toggles todo button tooltip', (done) => {
it('toggles todo button tooltip', done => {
document.querySelector('.js-issuable-todo.sidebar-collapsed-icon').click();
setTimeout(() => {
expect(
document.querySelector('.js-issuable-todo.sidebar-collapsed-icon').getAttribute('data-original-title'),
document
.querySelector('.js-issuable-todo.sidebar-collapsed-icon')
.getAttribute('data-original-title'),
).toBe('Mark todo as done');
done();
});
});
it('marks todo as done', (done) => {
it('marks todo as done', done => {
document.querySelector('.js-issuable-todo.sidebar-collapsed-icon').click();
timeoutPromise()
@ -128,25 +126,29 @@ describe('Issuable right sidebar collapsed todo toggle', () => {
.catch(done.fail);
});
it('updates aria-label to mark todo as done', (done) => {
it('updates aria-label to mark todo as done', done => {
document.querySelector('.js-issuable-todo.sidebar-collapsed-icon').click();
setTimeout(() => {
expect(
document.querySelector('.js-issuable-todo.sidebar-collapsed-icon').getAttribute('aria-label'),
document
.querySelector('.js-issuable-todo.sidebar-collapsed-icon')
.getAttribute('aria-label'),
).toBe('Mark todo as done');
done();
});
});
it('updates aria-label to add todo', (done) => {
it('updates aria-label to add todo', done => {
document.querySelector('.js-issuable-todo.sidebar-collapsed-icon').click();
timeoutPromise()
.then(() => {
expect(
document.querySelector('.js-issuable-todo.sidebar-collapsed-icon').getAttribute('aria-label'),
document
.querySelector('.js-issuable-todo.sidebar-collapsed-icon')
.getAttribute('aria-label'),
).toBe('Mark todo as done');
document.querySelector('.js-issuable-todo.sidebar-collapsed-icon').click();
@ -154,7 +156,9 @@ describe('Issuable right sidebar collapsed todo toggle', () => {
.then(timeoutPromise)
.then(() => {
expect(
document.querySelector('.js-issuable-todo.sidebar-collapsed-icon').getAttribute('aria-label'),
document
.querySelector('.js-issuable-todo.sidebar-collapsed-icon')
.getAttribute('aria-label'),
).toBe('Add todo');
})
.then(done)

View File

@ -1,9 +1,9 @@
import CommentTypeToggle from '~/comment_type_toggle';
import InputSetter from '~/droplab/plugins/input_setter';
describe('CommentTypeToggle', function () {
describe('class constructor', function () {
beforeEach(function () {
describe('CommentTypeToggle', function() {
describe('class constructor', function() {
beforeEach(function() {
this.dropdownTrigger = {};
this.dropdownList = {};
this.noteTypeInput = {};
@ -19,33 +19,33 @@ describe('CommentTypeToggle', function () {
});
});
it('should set .dropdownTrigger', function () {
it('should set .dropdownTrigger', function() {
expect(this.commentTypeToggle.dropdownTrigger).toBe(this.dropdownTrigger);
});
it('should set .dropdownList', function () {
it('should set .dropdownList', function() {
expect(this.commentTypeToggle.dropdownList).toBe(this.dropdownList);
});
it('should set .noteTypeInput', function () {
it('should set .noteTypeInput', function() {
expect(this.commentTypeToggle.noteTypeInput).toBe(this.noteTypeInput);
});
it('should set .submitButton', function () {
it('should set .submitButton', function() {
expect(this.commentTypeToggle.submitButton).toBe(this.submitButton);
});
it('should set .closeButton', function () {
it('should set .closeButton', function() {
expect(this.commentTypeToggle.closeButton).toBe(this.closeButton);
});
it('should set .reopenButton', function () {
it('should set .reopenButton', function() {
expect(this.commentTypeToggle.reopenButton).toBe(this.reopenButton);
});
});
describe('initDroplab', function () {
beforeEach(function () {
describe('initDroplab', function() {
beforeEach(function() {
this.commentTypeToggle = {
dropdownTrigger: {},
dropdownList: {},
@ -58,25 +58,27 @@ describe('CommentTypeToggle', function () {
this.droplab = jasmine.createSpyObj('droplab', ['init']);
this.droplabConstructor = spyOnDependency(CommentTypeToggle, 'DropLab').and.returnValue(this.droplab);
this.droplabConstructor = spyOnDependency(CommentTypeToggle, 'DropLab').and.returnValue(
this.droplab,
);
spyOn(this.commentTypeToggle, 'setConfig').and.returnValue(this.config);
CommentTypeToggle.prototype.initDroplab.call(this.commentTypeToggle);
});
it('should instantiate a DropLab instance', function () {
it('should instantiate a DropLab instance', function() {
expect(this.droplabConstructor).toHaveBeenCalled();
});
it('should set .droplab', function () {
it('should set .droplab', function() {
expect(this.commentTypeToggle.droplab).toBe(this.droplab);
});
it('should call .setConfig', function () {
it('should call .setConfig', function() {
expect(this.commentTypeToggle.setConfig).toHaveBeenCalled();
});
it('should call DropLab.prototype.init', function () {
it('should call DropLab.prototype.init', function() {
expect(this.droplab.init).toHaveBeenCalledWith(
this.commentTypeToggle.dropdownTrigger,
this.commentTypeToggle.dropdownList,
@ -86,9 +88,9 @@ describe('CommentTypeToggle', function () {
});
});
describe('setConfig', function () {
describe('if no .closeButton is provided', function () {
beforeEach(function () {
describe('setConfig', function() {
describe('if no .closeButton is provided', function() {
beforeEach(function() {
this.commentTypeToggle = {
dropdownTrigger: {},
dropdownList: {},
@ -100,28 +102,33 @@ describe('CommentTypeToggle', function () {
this.setConfig = CommentTypeToggle.prototype.setConfig.call(this.commentTypeToggle);
});
it('should not add .closeButton related InputSetter config', function () {
it('should not add .closeButton related InputSetter config', function() {
expect(this.setConfig).toEqual({
InputSetter: [{
input: this.commentTypeToggle.noteTypeInput,
valueAttribute: 'data-value',
}, {
input: this.commentTypeToggle.submitButton,
valueAttribute: 'data-submit-text',
}, {
input: this.commentTypeToggle.reopenButton,
valueAttribute: 'data-reopen-text',
}, {
input: this.commentTypeToggle.reopenButton,
valueAttribute: 'data-reopen-text',
inputAttribute: 'data-alternative-text',
}],
InputSetter: [
{
input: this.commentTypeToggle.noteTypeInput,
valueAttribute: 'data-value',
},
{
input: this.commentTypeToggle.submitButton,
valueAttribute: 'data-submit-text',
},
{
input: this.commentTypeToggle.reopenButton,
valueAttribute: 'data-reopen-text',
},
{
input: this.commentTypeToggle.reopenButton,
valueAttribute: 'data-reopen-text',
inputAttribute: 'data-alternative-text',
},
],
});
});
});
describe('if no .reopenButton is provided', function () {
beforeEach(function () {
describe('if no .reopenButton is provided', function() {
beforeEach(function() {
this.commentTypeToggle = {
dropdownTrigger: {},
dropdownList: {},
@ -133,22 +140,27 @@ describe('CommentTypeToggle', function () {
this.setConfig = CommentTypeToggle.prototype.setConfig.call(this.commentTypeToggle);
});
it('should not add .reopenButton related InputSetter config', function () {
it('should not add .reopenButton related InputSetter config', function() {
expect(this.setConfig).toEqual({
InputSetter: [{
input: this.commentTypeToggle.noteTypeInput,
valueAttribute: 'data-value',
}, {
input: this.commentTypeToggle.submitButton,
valueAttribute: 'data-submit-text',
}, {
input: this.commentTypeToggle.closeButton,
valueAttribute: 'data-close-text',
}, {
input: this.commentTypeToggle.closeButton,
valueAttribute: 'data-close-text',
inputAttribute: 'data-alternative-text',
}],
InputSetter: [
{
input: this.commentTypeToggle.noteTypeInput,
valueAttribute: 'data-value',
},
{
input: this.commentTypeToggle.submitButton,
valueAttribute: 'data-submit-text',
},
{
input: this.commentTypeToggle.closeButton,
valueAttribute: 'data-close-text',
},
{
input: this.commentTypeToggle.closeButton,
valueAttribute: 'data-close-text',
inputAttribute: 'data-alternative-text',
},
],
});
});
});

View File

@ -26,15 +26,18 @@ describe('Commit pipeline status component', () => {
beforeEach(() => {
mock = new MockAdapter(axios);
mock.onGet('/dummy/endpoint').reply(() => {
const res = Promise.resolve([200, {
pipelines: [
{
details: {
status: mockCiStatus,
const res = Promise.resolve([
200,
{
pipelines: [
{
details: {
status: mockCiStatus,
},
},
},
],
}]);
],
},
]);
return res;
});
vm = mountComponent(Component, {
@ -48,7 +51,7 @@ describe('Commit pipeline status component', () => {
mock.restore();
});
it('shows the loading icon when polling is starting', (done) => {
it('shows the loading icon when polling is starting', done => {
expect(vm.$el.querySelector('.loading-container')).not.toBe(null);
setTimeout(() => {
expect(vm.$el.querySelector('.loading-container')).toBe(null);
@ -56,17 +59,19 @@ describe('Commit pipeline status component', () => {
});
});
it('contains a ciStatus when the polling is succesful ', (done) => {
it('contains a ciStatus when the polling is succesful ', done => {
setTimeout(() => {
expect(vm.ciStatus).toEqual(mockCiStatus);
done();
});
});
it('contains a ci-status icon when polling is succesful', (done) => {
it('contains a ci-status icon when polling is succesful', done => {
setTimeout(() => {
expect(vm.$el.querySelector('.ci-status-icon')).not.toBe(null);
expect(vm.$el.querySelector('.ci-status-icon').classList).toContain(`ci-status-icon-${mockCiStatus.group}`);
expect(vm.$el.querySelector('.ci-status-icon').classList).toContain(
`ci-status-icon-${mockCiStatus.group}`,
);
done();
});
});
@ -89,7 +94,7 @@ describe('Commit pipeline status component', () => {
mock.restore();
});
it('calls an errorCallback', (done) => {
it('calls an errorCallback', done => {
spyOn(vm, 'errorCallback').and.callThrough();
vm.$mount();
setTimeout(() => {

View File

@ -4,7 +4,7 @@ import axios from '~/lib/utils/axios_utils';
import pipelinesTable from '~/commit/pipelines/pipelines_table.vue';
import mountComponent from 'spec/helpers/vue_mount_component_helper';
describe('Pipelines table in Commits and Merge requests', function () {
describe('Pipelines table in Commits and Merge requests', function() {
const jsonFixtureName = 'pipelines/pipelines.json';
let pipeline;
let PipelinesTable;
@ -29,7 +29,7 @@ describe('Pipelines table in Commits and Merge requests', function () {
describe('successful request', () => {
describe('without pipelines', () => {
beforeEach(function () {
beforeEach(function() {
mock.onGet('endpoint.json').reply(200, []);
vm = mountComponent(PipelinesTable, {
@ -41,7 +41,7 @@ describe('Pipelines table in Commits and Merge requests', function () {
});
});
it('should render the empty state', function (done) {
it('should render the empty state', function(done) {
setTimeout(() => {
expect(vm.$el.querySelector('.empty-state')).toBeDefined();
expect(vm.$el.querySelector('.realtime-loading')).toBe(null);
@ -63,7 +63,7 @@ describe('Pipelines table in Commits and Merge requests', function () {
});
});
it('should render a table with the received pipelines', (done) => {
it('should render a table with the received pipelines', done => {
setTimeout(() => {
expect(vm.$el.querySelectorAll('.ci-table .commit').length).toEqual(1);
expect(vm.$el.querySelector('.realtime-loading')).toBe(null);
@ -79,11 +79,11 @@ describe('Pipelines table in Commits and Merge requests', function () {
mock.onGet('endpoint.json').reply(200, [pipeline]);
});
it('should receive update-pipelines-count event', (done) => {
it('should receive update-pipelines-count event', done => {
const element = document.createElement('div');
document.body.appendChild(element);
element.addEventListener('update-pipelines-count', (event) => {
element.addEventListener('update-pipelines-count', event => {
expect(event.detail.pipelines).toEqual([pipeline]);
done();
});
@ -114,7 +114,7 @@ describe('Pipelines table in Commits and Merge requests', function () {
});
});
it('should render error state', function (done) {
it('should render error state', function(done) {
setTimeout(() => {
expect(vm.$el.querySelector('.js-pipelines-error-state')).toBeDefined();
expect(vm.$el.querySelector('.realtime-loading')).toBe(null);

View File

@ -3,7 +3,10 @@ import * as CommitMergeRequests from '~/commit_merge_requests';
describe('CommitMergeRequests', () => {
describe('createContent', () => {
it('should return created content', () => {
const content1 = CommitMergeRequests.createContent([{ iid: 1, path: '/path1', title: 'foo' }, { iid: 2, path: '/path2', title: 'baz' }])[0];
const content1 = CommitMergeRequests.createContent([
{ iid: 1, path: '/path1', title: 'foo' },
{ iid: 2, path: '/path2', title: 'baz' },
])[0];
expect(content1.tagName).toEqual('SPAN');
expect(content1.childElementCount).toEqual(4);

View File

@ -1,19 +1,23 @@
import $ from 'jquery';
import CreateItemDropdown from '~/create_item_dropdown';
const DROPDOWN_ITEM_DATA = [{
title: 'one',
id: 'one',
text: 'one',
}, {
title: 'two',
id: 'two',
text: 'two',
}, {
title: 'three',
id: 'three',
text: 'three',
}];
const DROPDOWN_ITEM_DATA = [
{
title: 'one',
id: 'one',
text: 'one',
},
{
title: 'two',
id: 'two',
text: 'two',
},
{
title: 'three',
id: 'three',
text: 'three',
},
];
describe('CreateItemDropdown', () => {
preloadFixtures('static/create_item_dropdown.html.raw');
@ -23,7 +27,8 @@ describe('CreateItemDropdown', () => {
function createItemAndClearInput(text) {
// Filter for the new item
$wrapperEl.find('.dropdown-input-field')
$wrapperEl
.find('.dropdown-input-field')
.val(text)
.trigger('input');
@ -32,7 +37,8 @@ describe('CreateItemDropdown', () => {
$createButton.click();
// Clear out the filter
$wrapperEl.find('.dropdown-input-field')
$wrapperEl
.find('.dropdown-input-field')
.val('')
.trigger('input');
}
@ -85,7 +91,8 @@ describe('CreateItemDropdown', () => {
$('.js-dropdown-menu-toggle').click();
// Filter for the new item
$wrapperEl.find('.dropdown-input-field')
$wrapperEl
.find('.dropdown-input-field')
.val(NEW_ITEM_TEXT)
.trigger('input');
});
@ -140,9 +147,7 @@ describe('CreateItemDropdown', () => {
$('.js-dropdown-menu-toggle').click();
// Filter for an item
filterInput
.val('one')
.trigger('input');
filterInput.val('one').trigger('input');
const $itemElsAfterFilter = $wrapperEl.find('.js-dropdown-content a');

View File

@ -17,21 +17,20 @@ describe('Cycle analytics banner', () => {
});
it('should render cycle analytics information', () => {
expect(
vm.$el.querySelector('h4').textContent.trim(),
).toEqual('Introducing Cycle Analytics');
expect(vm.$el.querySelector('h4').textContent.trim()).toEqual('Introducing Cycle Analytics');
expect(
vm.$el.querySelector('p').textContent.trim().replace(/[\r\n]+/g, ' '),
).toContain('Cycle Analytics gives an overview of how much time it takes to go from idea to production in your project.');
vm.$el
.querySelector('p')
.textContent.trim()
.replace(/[\r\n]+/g, ' '),
).toContain(
'Cycle Analytics gives an overview of how much time it takes to go from idea to production in your project.',
);
expect(
vm.$el.querySelector('a').textContent.trim(),
).toEqual('Read more');
expect(vm.$el.querySelector('a').textContent.trim()).toEqual('Read more');
expect(
vm.$el.querySelector('a').getAttribute('href'),
).toEqual('path');
expect(vm.$el.querySelector('a').getAttribute('href')).toEqual('path');
});
it('should emit an event when close button is clicked', () => {

View File

@ -10,7 +10,7 @@ describe('Deploy keys app component', () => {
let vm;
let mock;
beforeEach((done) => {
beforeEach(done => {
// set up axios mock before component
mock = new MockAdapter(axios);
mock.onGet(`${TEST_HOST}/dummy/`).replyOnce(200, data);

View File

@ -44,8 +44,7 @@ describe('diffs/components/app', () => {
it('shows comments message, with commit', done => {
vm.$store.state.diffs.commit = getDiffWithCommit().commit;
vm
.$nextTick()
vm.$nextTick()
.then(() => {
expect(vm.$el).toContainText('Only comments from the following commit are shown below');
expect(vm.$el).toContainElement('.blob-commit-info');
@ -58,8 +57,7 @@ describe('diffs/components/app', () => {
vm.$store.state.diffs.mergeRequestDiff = { latest: false };
vm.$store.state.diffs.targetBranch = 'master';
vm
.$nextTick()
vm.$nextTick()
.then(() => {
expect(vm.$el).toContainText(
"Not all comments are displayed because you're viewing an old version of the diff.",
@ -72,8 +70,7 @@ describe('diffs/components/app', () => {
it('shows comments message, with startVersion', done => {
vm.$store.state.diffs.startVersion = 'test';
vm
.$nextTick()
vm.$nextTick()
.then(() => {
expect(vm.$el).toContainText(
"Not all comments are displayed because you're comparing two versions of the diff.",

View File

@ -14,7 +14,8 @@ const TEST_PIPELINE_STATUS_PATH = `${TEST_HOST}/pipeline/status`;
const getTitleElement = vm => vm.$el.querySelector('.commit-row-message.item-title');
const getDescElement = vm => vm.$el.querySelector('pre.commit-row-description');
const getDescExpandElement = vm => vm.$el.querySelector('.commit-content .text-expander.js-toggle-button');
const getDescExpandElement = vm =>
vm.$el.querySelector('.commit-content .text-expander.js-toggle-button');
const getShaElement = vm => vm.$el.querySelector('.commit-sha-group');
const getAvatarElement = vm => vm.$el.querySelector('.user-avatar-link');
const getCommitterElement = vm => vm.$el.querySelector('.commiter');

View File

@ -316,7 +316,9 @@ describe('diff_file_header', () => {
const button = vm.$el.querySelector('.btn-clipboard');
expect(button).not.toBe(null);
expect(button.dataset.clipboardText).toBe('{"text":"files/ruby/popen.rb","gfm":"`files/ruby/popen.rb`"}');
expect(button.dataset.clipboardText).toBe(
'{"text":"files/ruby/popen.rb","gfm":"`files/ruby/popen.rb`"}',
);
});
describe('file mode', () => {

View File

@ -99,7 +99,9 @@ describe('DiffFile', () => {
);
expect(vm.$el.querySelector('.js-too-large-diff')).toBeDefined();
expect(vm.$el.querySelector('.js-too-large-diff a').href.indexOf(BLOB_LINK)).toBeGreaterThan(-1);
expect(
vm.$el.querySelector('.js-too-large-diff a').href.indexOf(BLOB_LINK),
).toBeGreaterThan(-1);
done();
});

View File

@ -5,8 +5,5 @@ const FIXTURE = 'merge_request_diffs/with_commit.json';
preloadFixtures(FIXTURE);
export default function getDiffWithCommit() {
return convertObjectPropsToCamelCase(
getJSONFixture(FIXTURE),
{ deep: true },
);
return convertObjectPropsToCamelCase(getJSONFixture(FIXTURE), { deep: true });
}

View File

@ -1,4 +1,3 @@
import DirtySubmitForm from '~/dirty_submit/dirty_submit_form';
import { setInput, createForm } from './helper';

View File

@ -2,9 +2,9 @@ import DropDown from '~/droplab/drop_down';
import utils from '~/droplab/utils';
import { SELECTED_CLASS } from '~/droplab/constants';
describe('DropLab DropDown', function () {
describe('class constructor', function () {
beforeEach(function () {
describe('DropLab DropDown', function() {
describe('class constructor', function() {
beforeEach(function() {
spyOn(DropDown.prototype, 'getItems');
spyOn(DropDown.prototype, 'initTemplateString');
spyOn(DropDown.prototype, 'addEvents');
@ -13,32 +13,32 @@ describe('DropLab DropDown', function () {
this.dropdown = new DropDown(this.list);
});
it('sets the .hidden property to true', function () {
it('sets the .hidden property to true', function() {
expect(this.dropdown.hidden).toBe(true);
});
it('sets the .list property', function () {
it('sets the .list property', function() {
expect(this.dropdown.list).toBe(this.list);
});
it('calls .getItems', function () {
it('calls .getItems', function() {
expect(DropDown.prototype.getItems).toHaveBeenCalled();
});
it('calls .initTemplateString', function () {
it('calls .initTemplateString', function() {
expect(DropDown.prototype.initTemplateString).toHaveBeenCalled();
});
it('calls .addEvents', function () {
it('calls .addEvents', function() {
expect(DropDown.prototype.addEvents).toHaveBeenCalled();
});
it('sets the .initialState property to the .list.innerHTML', function () {
it('sets the .initialState property to the .list.innerHTML', function() {
expect(this.dropdown.initialState).toBe(this.list.innerHTML);
});
describe('if the list argument is a string', function () {
beforeEach(function () {
describe('if the list argument is a string', function() {
beforeEach(function() {
this.element = {};
this.selector = '.selector';
@ -47,18 +47,18 @@ describe('DropLab DropDown', function () {
this.dropdown = new DropDown(this.selector);
});
it('calls .querySelector with the selector string', function () {
it('calls .querySelector with the selector string', function() {
expect(Document.prototype.querySelector).toHaveBeenCalledWith(this.selector);
});
it('sets the .list property element', function () {
it('sets the .list property element', function() {
expect(this.dropdown.list).toBe(this.element);
});
});
});
describe('getItems', function () {
beforeEach(function () {
describe('getItems', function() {
beforeEach(function() {
this.list = { querySelectorAll: () => {} };
this.dropdown = { list: this.list };
this.nodeList = [];
@ -68,37 +68,37 @@ describe('DropLab DropDown', function () {
this.getItems = DropDown.prototype.getItems.call(this.dropdown);
});
it('calls .querySelectorAll with a list item query', function () {
it('calls .querySelectorAll with a list item query', function() {
expect(this.list.querySelectorAll).toHaveBeenCalledWith('li');
});
it('sets the .items property to the returned list items', function () {
it('sets the .items property to the returned list items', function() {
expect(this.dropdown.items).toEqual(jasmine.any(Array));
});
it('returns the .items', function () {
it('returns the .items', function() {
expect(this.getItems).toEqual(jasmine.any(Array));
});
});
describe('initTemplateString', function () {
beforeEach(function () {
describe('initTemplateString', function() {
beforeEach(function() {
this.items = [{ outerHTML: '<a></a>' }, { outerHTML: '<img>' }];
this.dropdown = { items: this.items };
DropDown.prototype.initTemplateString.call(this.dropdown);
});
it('should set .templateString to the last items .outerHTML', function () {
it('should set .templateString to the last items .outerHTML', function() {
expect(this.dropdown.templateString).toBe(this.items[1].outerHTML);
});
it('should not set .templateString to a non-last items .outerHTML', function () {
it('should not set .templateString to a non-last items .outerHTML', function() {
expect(this.dropdown.templateString).not.toBe(this.items[0].outerHTML);
});
describe('if .items is not set', function () {
beforeEach(function () {
describe('if .items is not set', function() {
beforeEach(function() {
this.dropdown = { getItems: () => {} };
spyOn(this.dropdown, 'getItems').and.returnValue([]);
@ -106,26 +106,26 @@ describe('DropLab DropDown', function () {
DropDown.prototype.initTemplateString.call(this.dropdown);
});
it('should call .getItems', function () {
it('should call .getItems', function() {
expect(this.dropdown.getItems).toHaveBeenCalled();
});
});
describe('if items array is empty', function () {
beforeEach(function () {
describe('if items array is empty', function() {
beforeEach(function() {
this.dropdown = { items: [] };
DropDown.prototype.initTemplateString.call(this.dropdown);
});
it('should set .templateString to an empty string', function () {
it('should set .templateString to an empty string', function() {
expect(this.dropdown.templateString).toBe('');
});
});
});
describe('clickEvent', function () {
beforeEach(function () {
describe('clickEvent', function() {
beforeEach(function() {
this.classList = jasmine.createSpyObj('classList', ['contains']);
this.list = { dispatchEvent: () => {} };
this.dropdown = {
@ -143,7 +143,7 @@ describe('DropLab DropDown', function () {
};
this.customEvent = {};
this.dummyListItem = document.createElement('li');
spyOn(this.event.target, 'closest').and.callFake((selector) => {
spyOn(this.event.target, 'closest').and.callFake(selector => {
if (selector === 'li') {
return this.dummyListItem;
}
@ -159,51 +159,51 @@ describe('DropLab DropDown', function () {
this.classList.contains.and.returnValue(false);
});
it('should call event.target.closest', function () {
it('should call event.target.closest', function() {
DropDown.prototype.clickEvent.call(this.dropdown, this.event);
expect(this.event.target.closest).toHaveBeenCalledWith('.droplab-item-ignore');
expect(this.event.target.closest).toHaveBeenCalledWith('li');
});
it('should call addSelectedClass', function () {
it('should call addSelectedClass', function() {
DropDown.prototype.clickEvent.call(this.dropdown, this.event);
expect(this.dropdown.addSelectedClass).toHaveBeenCalledWith(this.dummyListItem);
});
it('should call .preventDefault', function () {
it('should call .preventDefault', function() {
DropDown.prototype.clickEvent.call(this.dropdown, this.event);
expect(this.event.preventDefault).toHaveBeenCalled();
});
it('should call .hide', function () {
it('should call .hide', function() {
DropDown.prototype.clickEvent.call(this.dropdown, this.event);
expect(this.dropdown.hide).toHaveBeenCalled();
});
it('should construct CustomEvent', function () {
it('should construct CustomEvent', function() {
DropDown.prototype.clickEvent.call(this.dropdown, this.event);
expect(window.CustomEvent).toHaveBeenCalledWith('click.dl', jasmine.any(Object));
});
it('should call .dispatchEvent with the customEvent', function () {
it('should call .dispatchEvent with the customEvent', function() {
DropDown.prototype.clickEvent.call(this.dropdown, this.event);
expect(this.list.dispatchEvent).toHaveBeenCalledWith(this.customEvent);
});
describe('if the target is a UL element', function () {
beforeEach(function () {
describe('if the target is a UL element', function() {
beforeEach(function() {
this.event.target = document.createElement('ul');
spyOn(this.event.target, 'closest');
});
it('should return immediately', function () {
it('should return immediately', function() {
DropDown.prototype.clickEvent.call(this.dropdown, this.event);
expect(this.event.target.closest).not.toHaveBeenCalled();
@ -211,8 +211,8 @@ describe('DropLab DropDown', function () {
});
});
describe('if the target has the droplab-item-ignore class', function () {
beforeEach(function () {
describe('if the target has the droplab-item-ignore class', function() {
beforeEach(function() {
this.ignoredButton = document.createElement('button');
this.ignoredButton.classList.add('droplab-item-ignore');
this.event.target = this.ignoredButton;
@ -220,7 +220,7 @@ describe('DropLab DropDown', function () {
spyOn(this.ignoredButton, 'closest').and.callThrough();
});
it('does not select element', function () {
it('does not select element', function() {
DropDown.prototype.clickEvent.call(this.dropdown, this.event);
expect(this.ignoredButton.closest.calls.count()).toBe(1);
@ -229,13 +229,13 @@ describe('DropLab DropDown', function () {
});
});
describe('if no selected element exists', function () {
beforeEach(function () {
describe('if no selected element exists', function() {
beforeEach(function() {
this.event.preventDefault.calls.reset();
this.dummyListItem = null;
});
it('should return before .preventDefault is called', function () {
it('should return before .preventDefault is called', function() {
DropDown.prototype.clickEvent.call(this.dropdown, this.event);
expect(this.event.preventDefault).not.toHaveBeenCalled();
@ -244,12 +244,12 @@ describe('DropLab DropDown', function () {
});
describe('if hideOnClick is false', () => {
beforeEach(function () {
beforeEach(function() {
this.dropdown.hideOnClick = false;
this.dropdown.hide.calls.reset();
});
it('should not call .hide', function () {
it('should not call .hide', function() {
DropDown.prototype.clickEvent.call(this.dropdown, this.event);
expect(this.dropdown.hide).not.toHaveBeenCalled();
@ -257,8 +257,8 @@ describe('DropLab DropDown', function () {
});
});
describe('addSelectedClass', function () {
beforeEach(function () {
describe('addSelectedClass', function() {
beforeEach(function() {
this.items = Array(4).forEach((item, i) => {
this.items[i] = { classList: { add: () => {} } };
spyOn(this.items[i].classList, 'add');
@ -272,17 +272,17 @@ describe('DropLab DropDown', function () {
DropDown.prototype.addSelectedClass.call(this.dropdown, this.selected);
});
it('should call .removeSelectedClasses', function () {
it('should call .removeSelectedClasses', function() {
expect(this.dropdown.removeSelectedClasses).toHaveBeenCalled();
});
it('should call .classList.add', function () {
it('should call .classList.add', function() {
expect(this.selected.classList.add).toHaveBeenCalledWith(SELECTED_CLASS);
});
});
describe('removeSelectedClasses', function () {
beforeEach(function () {
describe('removeSelectedClasses', function() {
beforeEach(function() {
this.items = Array(4);
this.items.forEach((item, i) => {
this.items[i] = { classList: { add: () => {} } };
@ -293,14 +293,14 @@ describe('DropLab DropDown', function () {
DropDown.prototype.removeSelectedClasses.call(this.dropdown);
});
it('should call .classList.remove for all items', function () {
it('should call .classList.remove for all items', function() {
this.items.forEach((item, i) => {
expect(this.items[i].classList.add).toHaveBeenCalledWith(SELECTED_CLASS);
});
});
describe('if .items is not set', function () {
beforeEach(function () {
describe('if .items is not set', function() {
beforeEach(function() {
this.dropdown = { getItems: () => {} };
spyOn(this.dropdown, 'getItems').and.returnValue([]);
@ -308,14 +308,14 @@ describe('DropLab DropDown', function () {
DropDown.prototype.removeSelectedClasses.call(this.dropdown);
});
it('should call .getItems', function () {
it('should call .getItems', function() {
expect(this.dropdown.getItems).toHaveBeenCalled();
});
});
});
describe('addEvents', function () {
beforeEach(function () {
describe('addEvents', function() {
beforeEach(function() {
this.list = {
addEventListener: () => {},
querySelectorAll: () => [],
@ -328,7 +328,7 @@ describe('DropLab DropDown', function () {
};
});
it('should call .addEventListener', function () {
it('should call .addEventListener', function() {
spyOn(this.list, 'addEventListener');
DropDown.prototype.addEvents.call(this.dropdown);
@ -338,8 +338,8 @@ describe('DropLab DropDown', function () {
});
});
describe('setData', function () {
beforeEach(function () {
describe('setData', function() {
beforeEach(function() {
this.dropdown = { render: () => {} };
this.data = ['data'];
@ -348,17 +348,17 @@ describe('DropLab DropDown', function () {
DropDown.prototype.setData.call(this.dropdown, this.data);
});
it('should set .data', function () {
it('should set .data', function() {
expect(this.dropdown.data).toBe(this.data);
});
it('should call .render with the .data', function () {
it('should call .render with the .data', function() {
expect(this.dropdown.render).toHaveBeenCalledWith(this.data);
});
});
describe('addData', function () {
beforeEach(function () {
describe('addData', function() {
beforeEach(function() {
this.dropdown = { render: () => {}, data: ['data1'] };
this.data = ['data2'];
@ -368,20 +368,20 @@ describe('DropLab DropDown', function () {
DropDown.prototype.addData.call(this.dropdown, this.data);
});
it('should call .concat with data', function () {
it('should call .concat with data', function() {
expect(Array.prototype.concat).toHaveBeenCalledWith(this.data);
});
it('should set .data with concatination', function () {
it('should set .data with concatination', function() {
expect(this.dropdown.data).toEqual(['data1', 'data2']);
});
it('should call .render with the .data', function () {
it('should call .render with the .data', function() {
expect(this.dropdown.render).toHaveBeenCalledWith(['data1', 'data2']);
});
describe('if .data is undefined', function () {
beforeEach(function () {
describe('if .data is undefined', function() {
beforeEach(function() {
this.dropdown = { render: () => {}, data: undefined };
this.data = ['data2'];
@ -390,14 +390,14 @@ describe('DropLab DropDown', function () {
DropDown.prototype.addData.call(this.dropdown, this.data);
});
it('should set .data with concatination', function () {
it('should set .data with concatination', function() {
expect(this.dropdown.data).toEqual(['data2']);
});
});
});
describe('render', function () {
beforeEach(function () {
describe('render', function() {
beforeEach(function() {
this.list = { querySelector: () => {}, dispatchEvent: () => {} };
this.dropdown = { renderChildren: () => {}, list: this.list };
this.renderableList = {};
@ -413,45 +413,45 @@ describe('DropLab DropDown', function () {
DropDown.prototype.render.call(this.dropdown, this.data);
});
it('should call .map', function () {
it('should call .map', function() {
expect(this.data.map).toHaveBeenCalledWith(jasmine.any(Function));
});
it('should call .renderChildren for each data item', function () {
it('should call .renderChildren for each data item', function() {
expect(this.dropdown.renderChildren.calls.count()).toBe(this.data.length);
});
it('sets the renderableList .innerHTML', function () {
it('sets the renderableList .innerHTML', function() {
expect(this.renderableList.innerHTML).toBe('01');
});
it('should call render.dl', function () {
it('should call render.dl', function() {
expect(window.CustomEvent).toHaveBeenCalledWith('render.dl', jasmine.any(Object));
});
it('should call dispatchEvent with the customEvent', function () {
it('should call dispatchEvent with the customEvent', function() {
expect(this.list.dispatchEvent).toHaveBeenCalledWith(this.customEvent);
});
describe('if no data argument is passed', function () {
beforeEach(function () {
describe('if no data argument is passed', function() {
beforeEach(function() {
this.data.map.calls.reset();
this.dropdown.renderChildren.calls.reset();
DropDown.prototype.render.call(this.dropdown, undefined);
});
it('should not call .map', function () {
it('should not call .map', function() {
expect(this.data.map).not.toHaveBeenCalled();
});
it('should not call .renderChildren', function () {
it('should not call .renderChildren', function() {
expect(this.dropdown.renderChildren).not.toHaveBeenCalled();
});
});
describe('if no dynamic list is present', function () {
beforeEach(function () {
describe('if no dynamic list is present', function() {
beforeEach(function() {
this.list = { querySelector: () => {}, dispatchEvent: () => {} };
this.dropdown = { renderChildren: () => {}, list: this.list };
this.data = [0, 1];
@ -463,14 +463,14 @@ describe('DropLab DropDown', function () {
DropDown.prototype.render.call(this.dropdown, this.data);
});
it('sets the .list .innerHTML', function () {
it('sets the .list .innerHTML', function() {
expect(this.list.innerHTML).toBe('01');
});
});
});
describe('renderChildren', function () {
beforeEach(function () {
describe('renderChildren', function() {
beforeEach(function() {
this.templateString = 'templateString';
this.dropdown = { templateString: this.templateString };
this.data = { droplab_hidden: true };
@ -484,44 +484,44 @@ describe('DropLab DropDown', function () {
this.renderChildren = DropDown.prototype.renderChildren.call(this.dropdown, this.data);
});
it('should call utils.t with .templateString and data', function () {
it('should call utils.t with .templateString and data', function() {
expect(utils.template).toHaveBeenCalledWith(this.templateString, this.data);
});
it('should call document.createElement', function () {
it('should call document.createElement', function() {
expect(document.createElement).toHaveBeenCalledWith('div');
});
it('should set the templates .innerHTML to the HTML', function () {
it('should set the templates .innerHTML to the HTML', function() {
expect(this.template.innerHTML).toBe(this.html);
});
it('should call .setImagesSrc with the template', function () {
it('should call .setImagesSrc with the template', function() {
expect(DropDown.setImagesSrc).toHaveBeenCalledWith(this.template);
});
it('should set the template display to none', function () {
it('should set the template display to none', function() {
expect(this.template.firstChild.style.display).toBe('none');
});
it('should return the templates .firstChild.outerHTML', function () {
it('should return the templates .firstChild.outerHTML', function() {
expect(this.renderChildren).toBe(this.template.firstChild.outerHTML);
});
describe('if droplab_hidden is false', function () {
beforeEach(function () {
describe('if droplab_hidden is false', function() {
beforeEach(function() {
this.data = { droplab_hidden: false };
this.renderChildren = DropDown.prototype.renderChildren.call(this.dropdown, this.data);
});
it('should set the template display to block', function () {
it('should set the template display to block', function() {
expect(this.template.firstChild.style.display).toBe('block');
});
});
});
describe('setImagesSrc', function () {
beforeEach(function () {
describe('setImagesSrc', function() {
beforeEach(function() {
this.template = { querySelectorAll: () => {} };
spyOn(this.template, 'querySelectorAll').and.returnValue([]);
@ -529,64 +529,64 @@ describe('DropLab DropDown', function () {
DropDown.setImagesSrc(this.template);
});
it('should call .querySelectorAll', function () {
it('should call .querySelectorAll', function() {
expect(this.template.querySelectorAll).toHaveBeenCalledWith('img[data-src]');
});
});
describe('show', function () {
beforeEach(function () {
describe('show', function() {
beforeEach(function() {
this.list = { style: {} };
this.dropdown = { list: this.list, hidden: true };
DropDown.prototype.show.call(this.dropdown);
});
it('it should set .list display to block', function () {
it('it should set .list display to block', function() {
expect(this.list.style.display).toBe('block');
});
it('it should set .hidden to false', function () {
it('it should set .hidden to false', function() {
expect(this.dropdown.hidden).toBe(false);
});
describe('if .hidden is false', function () {
beforeEach(function () {
describe('if .hidden is false', function() {
beforeEach(function() {
this.list = { style: {} };
this.dropdown = { list: this.list, hidden: false };
this.show = DropDown.prototype.show.call(this.dropdown);
});
it('should return undefined', function () {
it('should return undefined', function() {
expect(this.show).toEqual(undefined);
});
it('should not set .list display to block', function () {
it('should not set .list display to block', function() {
expect(this.list.style.display).not.toEqual('block');
});
});
});
describe('hide', function () {
beforeEach(function () {
describe('hide', function() {
beforeEach(function() {
this.list = { style: {} };
this.dropdown = { list: this.list };
DropDown.prototype.hide.call(this.dropdown);
});
it('it should set .list display to none', function () {
it('it should set .list display to none', function() {
expect(this.list.style.display).toBe('none');
});
it('it should set .hidden to true', function () {
it('it should set .hidden to true', function() {
expect(this.dropdown.hidden).toBe(true);
});
});
describe('toggle', function () {
beforeEach(function () {
describe('toggle', function() {
beforeEach(function() {
this.hidden = true;
this.dropdown = { hidden: this.hidden, show: () => {}, hide: () => {} };
@ -596,12 +596,12 @@ describe('DropLab DropDown', function () {
DropDown.prototype.toggle.call(this.dropdown);
});
it('should call .show', function () {
it('should call .show', function() {
expect(this.dropdown.show).toHaveBeenCalled();
});
describe('if .hidden is false', function () {
beforeEach(function () {
describe('if .hidden is false', function() {
beforeEach(function() {
this.hidden = false;
this.dropdown = { hidden: this.hidden, show: () => {}, hide: () => {} };
@ -611,14 +611,14 @@ describe('DropLab DropDown', function () {
DropDown.prototype.toggle.call(this.dropdown);
});
it('should call .hide', function () {
it('should call .hide', function() {
expect(this.dropdown.hide).toHaveBeenCalled();
});
});
});
describe('destroy', function () {
beforeEach(function () {
describe('destroy', function() {
beforeEach(function() {
this.list = { removeEventListener: () => {} };
this.eventWrapper = { clickEvent: 'clickEvent' };
this.dropdown = { list: this.list, hide: () => {}, eventWrapper: this.eventWrapper };
@ -629,12 +629,15 @@ describe('DropLab DropDown', function () {
DropDown.prototype.destroy.call(this.dropdown);
});
it('it should call .hide', function () {
it('it should call .hide', function() {
expect(this.dropdown.hide).toHaveBeenCalled();
});
it('it should call .removeEventListener', function () {
expect(this.list.removeEventListener).toHaveBeenCalledWith('click', this.eventWrapper.clickEvent);
it('it should call .removeEventListener', function() {
expect(this.list.removeEventListener).toHaveBeenCalledWith(
'click',
this.eventWrapper.clickEvent,
);
});
});
});

View File

@ -1,8 +1,8 @@
import Hook from '~/droplab/hook';
describe('Hook', function () {
describe('class constructor', function () {
beforeEach(function () {
describe('Hook', function() {
describe('class constructor', function() {
beforeEach(function() {
this.trigger = { id: 'id' };
this.list = {};
this.plugins = {};
@ -14,58 +14,58 @@ describe('Hook', function () {
this.hook = new Hook(this.trigger, this.list, this.plugins, this.config);
});
it('should set .trigger', function () {
it('should set .trigger', function() {
expect(this.hook.trigger).toBe(this.trigger);
});
it('should set .list', function () {
it('should set .list', function() {
expect(this.hook.list).toBe(this.dropdown);
});
it('should call DropDown constructor', function () {
it('should call DropDown constructor', function() {
expect(this.dropdownConstructor).toHaveBeenCalledWith(this.list, this.config);
});
it('should set .type', function () {
it('should set .type', function() {
expect(this.hook.type).toBe('Hook');
});
it('should set .event', function () {
it('should set .event', function() {
expect(this.hook.event).toBe('click');
});
it('should set .plugins', function () {
it('should set .plugins', function() {
expect(this.hook.plugins).toBe(this.plugins);
});
it('should set .config', function () {
it('should set .config', function() {
expect(this.hook.config).toBe(this.config);
});
it('should set .id', function () {
it('should set .id', function() {
expect(this.hook.id).toBe(this.trigger.id);
});
describe('if config argument is undefined', function () {
beforeEach(function () {
describe('if config argument is undefined', function() {
beforeEach(function() {
this.config = undefined;
this.hook = new Hook(this.trigger, this.list, this.plugins, this.config);
});
it('should set .config to an empty object', function () {
it('should set .config to an empty object', function() {
expect(this.hook.config).toEqual({});
});
});
describe('if plugins argument is undefined', function () {
beforeEach(function () {
describe('if plugins argument is undefined', function() {
beforeEach(function() {
this.plugins = undefined;
this.hook = new Hook(this.trigger, this.list, this.plugins, this.config);
});
it('should set .plugins to an empty array', function () {
it('should set .plugins to an empty array', function() {
expect(this.hook.plugins).toEqual([]);
});
});

View File

@ -38,8 +38,8 @@ describe('AjaxFilter', () => {
dummyList.list.appendChild(dynamicList);
});
it('calls onLoadingFinished after loading data', (done) => {
ajaxSpy = (url) => {
it('calls onLoadingFinished after loading data', done => {
ajaxSpy = url => {
expect(url).toBe('dummy endpoint?dummy search key=');
return Promise.resolve(dummyData);
};
@ -52,16 +52,16 @@ describe('AjaxFilter', () => {
.catch(done.fail);
});
it('does not call onLoadingFinished if Ajax call fails', (done) => {
it('does not call onLoadingFinished if Ajax call fails', done => {
const dummyError = new Error('My dummy is sick! :-(');
ajaxSpy = (url) => {
ajaxSpy = url => {
expect(url).toBe('dummy endpoint?dummy search key=');
return Promise.reject(dummyError);
};
AjaxFilter.trigger()
.then(done.fail)
.catch((error) => {
.catch(error => {
expect(error).toBe(dummyError);
expect(dummyConfig.onLoadingFinished.calls.count()).toBe(0);
})

View File

@ -29,7 +29,7 @@ describe('Ajax', () => {
it('overrides AjaxCache', () => {
spyOn(AjaxCache, 'override').and.callFake((endpoint, results) => {
expect(results).toEqual(processedArray);
expect(results).toEqual(processedArray);
});
Ajax.preprocessing(config, []);

View File

@ -1,8 +1,8 @@
import InputSetter from '~/droplab/plugins/input_setter';
describe('InputSetter', function () {
describe('init', function () {
beforeEach(function () {
describe('InputSetter', function() {
describe('init', function() {
beforeEach(function() {
this.config = { InputSetter: {} };
this.hook = { config: this.config };
this.inputSetter = jasmine.createSpyObj('inputSetter', ['addEvents']);
@ -10,60 +10,62 @@ describe('InputSetter', function () {
InputSetter.init.call(this.inputSetter, this.hook);
});
it('should set .hook', function () {
it('should set .hook', function() {
expect(this.inputSetter.hook).toBe(this.hook);
});
it('should set .config', function () {
it('should set .config', function() {
expect(this.inputSetter.config).toBe(this.config.InputSetter);
});
it('should set .eventWrapper', function () {
it('should set .eventWrapper', function() {
expect(this.inputSetter.eventWrapper).toEqual({});
});
it('should call .addEvents', function () {
it('should call .addEvents', function() {
expect(this.inputSetter.addEvents).toHaveBeenCalled();
});
describe('if config.InputSetter is not set', function () {
beforeEach(function () {
describe('if config.InputSetter is not set', function() {
beforeEach(function() {
this.config = { InputSetter: undefined };
this.hook = { config: this.config };
InputSetter.init.call(this.inputSetter, this.hook);
});
it('should set .config to an empty object', function () {
it('should set .config to an empty object', function() {
expect(this.inputSetter.config).toEqual({});
});
it('should set hook.config to an empty object', function () {
it('should set hook.config to an empty object', function() {
expect(this.hook.config.InputSetter).toEqual({});
});
})
});
});
describe('addEvents', function () {
beforeEach(function () {
describe('addEvents', function() {
beforeEach(function() {
this.hook = { list: { list: jasmine.createSpyObj('list', ['addEventListener']) } };
this.inputSetter = { eventWrapper: {}, hook: this.hook, setInputs: () => {} };
InputSetter.addEvents.call(this.inputSetter);
});
it('should set .eventWrapper.setInputs', function () {
it('should set .eventWrapper.setInputs', function() {
expect(this.inputSetter.eventWrapper.setInputs).toEqual(jasmine.any(Function));
});
it('should call .addEventListener', function () {
expect(this.hook.list.list.addEventListener)
.toHaveBeenCalledWith('click.dl', this.inputSetter.eventWrapper.setInputs);
it('should call .addEventListener', function() {
expect(this.hook.list.list.addEventListener).toHaveBeenCalledWith(
'click.dl',
this.inputSetter.eventWrapper.setInputs,
);
});
});
describe('removeEvents', function () {
beforeEach(function () {
describe('removeEvents', function() {
beforeEach(function() {
this.hook = { list: { list: jasmine.createSpyObj('list', ['removeEventListener']) } };
this.eventWrapper = jasmine.createSpyObj('eventWrapper', ['setInputs']);
this.inputSetter = { eventWrapper: this.eventWrapper, hook: this.hook };
@ -71,14 +73,16 @@ describe('InputSetter', function () {
InputSetter.removeEvents.call(this.inputSetter);
});
it('should call .removeEventListener', function () {
expect(this.hook.list.list.removeEventListener)
.toHaveBeenCalledWith('click.dl', this.eventWrapper.setInputs);
it('should call .removeEventListener', function() {
expect(this.hook.list.list.removeEventListener).toHaveBeenCalledWith(
'click.dl',
this.eventWrapper.setInputs,
);
});
});
describe('setInputs', function () {
beforeEach(function () {
describe('setInputs', function() {
beforeEach(function() {
this.event = { detail: { selected: {} } };
this.config = [0, 1];
this.inputSetter = { config: this.config, setInput: () => {} };
@ -88,7 +92,7 @@ describe('InputSetter', function () {
InputSetter.setInputs.call(this.inputSetter, this.event);
});
it('should call .setInput for each config element', function () {
it('should call .setInput for each config element', function() {
const allArgs = this.inputSetter.setInput.calls.allArgs();
expect(allArgs.length).toEqual(2);
@ -99,21 +103,21 @@ describe('InputSetter', function () {
});
});
describe('if config isnt an array', function () {
beforeEach(function () {
describe('if config isnt an array', function() {
beforeEach(function() {
this.inputSetter = { config: {}, setInput: () => {} };
InputSetter.setInputs.call(this.inputSetter, this.event);
});
it('should set .config to an array with .config as the first element', function () {
it('should set .config to an array with .config as the first element', function() {
expect(this.inputSetter.config).toEqual([{}]);
});
});
});
describe('setInput', function () {
beforeEach(function () {
describe('setInput', function() {
beforeEach(function() {
this.selectedItem = { getAttribute: () => {} };
this.input = { value: 'oldValue', tagName: 'INPUT', hasAttribute: () => {} };
this.config = { valueAttribute: {}, input: this.input };
@ -126,20 +130,20 @@ describe('InputSetter', function () {
InputSetter.setInput.call(this.inputSetter, this.config, this.selectedItem);
});
it('should call .getAttribute', function () {
it('should call .getAttribute', function() {
expect(this.selectedItem.getAttribute).toHaveBeenCalledWith(this.config.valueAttribute);
});
it('should call .hasAttribute', function () {
it('should call .hasAttribute', function() {
expect(this.input.hasAttribute).toHaveBeenCalledWith(undefined);
});
it('should set the value of the input', function () {
it('should set the value of the input', function() {
expect(this.input.value).toBe(this.newValue);
});
describe('if no config.input is provided', function () {
beforeEach(function () {
describe('if no config.input is provided', function() {
beforeEach(function() {
this.config = { valueAttribute: {} };
this.trigger = { value: 'oldValue', tagName: 'INPUT', hasAttribute: () => {} };
this.inputSetter = { hook: { trigger: this.trigger } };
@ -147,26 +151,26 @@ describe('InputSetter', function () {
InputSetter.setInput.call(this.inputSetter, this.config, this.selectedItem);
});
it('should set the value of the hook.trigger', function () {
it('should set the value of the hook.trigger', function() {
expect(this.trigger.value).toBe(this.newValue);
});
});
describe('if the input tag is not INPUT', function () {
beforeEach(function () {
describe('if the input tag is not INPUT', function() {
beforeEach(function() {
this.input = { textContent: 'oldValue', tagName: 'SPAN', hasAttribute: () => {} };
this.config = { valueAttribute: {}, input: this.input };
InputSetter.setInput.call(this.inputSetter, this.config, this.selectedItem);
});
it('should set the textContent of the input', function () {
it('should set the textContent of the input', function() {
expect(this.input.textContent).toBe(this.newValue);
});
});
describe('if there is an inputAttribute', function () {
beforeEach(function () {
describe('if there is an inputAttribute', function() {
beforeEach(function() {
this.selectedItem = { getAttribute: () => {} };
this.input = { id: 'oldValue', hasAttribute: () => {}, setAttribute: () => {} };
this.inputSetter = { hook: { trigger: {} } };
@ -185,25 +189,25 @@ describe('InputSetter', function () {
InputSetter.setInput.call(this.inputSetter, this.config, this.selectedItem);
});
it('should call setAttribute', function () {
it('should call setAttribute', function() {
expect(this.input.setAttribute).toHaveBeenCalledWith(this.inputAttribute, this.newValue);
});
it('should not set the value or textContent of the input', function () {
it('should not set the value or textContent of the input', function() {
expect(this.input.value).not.toBe('newValue');
expect(this.input.textContent).not.toBe('newValue');
});
});
});
describe('destroy', function () {
beforeEach(function () {
describe('destroy', function() {
beforeEach(function() {
this.inputSetter = jasmine.createSpyObj('inputSetter', ['removeEvents']);
InputSetter.destroy.call(this.inputSetter);
});
it('should call .removeEvents', function () {
it('should call .removeEvents', function() {
expect(this.inputSetter.removeEvents).toHaveBeenCalled();
});
});

View File

@ -7,12 +7,10 @@ const TEST_FILE = {
};
const TEST_UPLOAD_PATH = `${TEST_HOST}/upload/file`;
const TEST_ERROR_MESSAGE = 'A big error occurred!';
const TEMPLATE = (
`<form class="gfm-form" data-uploads-path="${TEST_UPLOAD_PATH}">
const TEMPLATE = `<form class="gfm-form" data-uploads-path="${TEST_UPLOAD_PATH}">
<textarea class="js-gfm-input"></textarea>
<div class="uploading-error-message"></div>
</form>`
);
</form>`;
describe('dropzone_input', () => {
let form;

View File

@ -235,11 +235,11 @@ describe('gl_emoji', () => {
expect(isRainbowFlagEmoji('🏳🌈')).toBeTruthy();
});
it('should not detect flag_white on its\' own', () => {
it("should not detect flag_white on its' own", () => {
expect(isRainbowFlagEmoji('🏳')).toBeFalsy();
});
it('should not detect rainbow on its\' own', () => {
it("should not detect rainbow on its' own", () => {
expect(isRainbowFlagEmoji('🌈')).toBeFalsy();
});
@ -370,21 +370,13 @@ describe('gl_emoji', () => {
describe('isEmojiUnicodeSupported', () => {
it('should gracefully handle empty string with unicode support', () => {
const isSupported = isEmojiUnicodeSupported(
{ '1.0': true },
'',
'1.0',
);
const isSupported = isEmojiUnicodeSupported({ '1.0': true }, '', '1.0');
expect(isSupported).toBeTruthy();
});
it('should gracefully handle empty string without unicode support', () => {
const isSupported = isEmojiUnicodeSupported(
{},
'',
'1.0',
);
const isSupported = isEmojiUnicodeSupported({}, '', '1.0');
expect(isSupported).toBeFalsy();
});

View File

@ -40,23 +40,27 @@ describe('Actions Component', () => {
it('should render a dropdown button with icon and title attribute', () => {
expect(component.$el.querySelector('.fa-caret-down')).toBeDefined();
expect(component.$el.querySelector('.dropdown-new').getAttribute('data-original-title')).toEqual('Deploy to...');
expect(component.$el.querySelector('.dropdown-new').getAttribute('aria-label')).toEqual('Deploy to...');
expect(
component.$el.querySelector('.dropdown-new').getAttribute('data-original-title'),
).toEqual('Deploy to...');
expect(component.$el.querySelector('.dropdown-new').getAttribute('aria-label')).toEqual(
'Deploy to...',
);
});
it('should render a dropdown with the provided list of actions', () => {
expect(
component.$el.querySelectorAll('.dropdown-menu li').length,
).toEqual(actionsMock.length);
expect(component.$el.querySelectorAll('.dropdown-menu li').length).toEqual(actionsMock.length);
});
it('should render a disabled action when it\'s not playable', () => {
it("should render a disabled action when it's not playable", () => {
expect(
component.$el.querySelector('.dropdown-menu li:last-child button').getAttribute('disabled'),
).toEqual('disabled');
expect(
component.$el.querySelector('.dropdown-menu li:last-child button').classList.contains('disabled'),
component.$el
.querySelector('.dropdown-menu li:last-child button')
.classList.contains('disabled'),
).toEqual(true);
});
});

View File

@ -1,11 +1,7 @@
import $ from 'jquery';
import MockAdapter from 'axios-mock-adapter';
import axios from '~/lib/utils/axios_utils';
import {
getSelector,
dismiss,
inserted,
} from '~/feature_highlight/feature_highlight_helper';
import { getSelector, dismiss, inserted } from '~/feature_highlight/feature_highlight_helper';
import { togglePopover } from '~/shared/popover';
import getSetTimeoutPromise from 'spec/helpers/set_timeout_promise_helper';
@ -15,7 +11,9 @@ describe('feature highlight helper', () => {
it('returns js-feature-highlight selector', () => {
const highlightId = 'highlightId';
expect(getSelector(highlightId)).toEqual(`.js-feature-highlight[data-highlight=${highlightId}]`);
expect(getSelector(highlightId)).toEqual(
`.js-feature-highlight[data-highlight=${highlightId}]`,
);
});
});
@ -38,7 +36,7 @@ describe('feature highlight helper', () => {
mock.restore();
});
it('calls persistent dismissal endpoint', (done) => {
it('calls persistent dismissal endpoint', done => {
const spy = jasmine.createSpy('dismiss-endpoint-hit');
mock.onPost('/-/callouts/dismiss').reply(spy);
@ -60,7 +58,7 @@ describe('feature highlight helper', () => {
});
describe('inserted', () => {
it('registers click event callback', (done) => {
it('registers click event callback', done => {
const context = {
getAttribute: () => 'popoverId',
dataset: {
@ -68,7 +66,7 @@ describe('feature highlight helper', () => {
},
};
spyOn($.fn, 'on').and.callFake((event) => {
spyOn($.fn, 'on').and.callFake(event => {
expect(event).toEqual('click');
done();
});

View File

@ -50,7 +50,7 @@ describe('feature highlight', () => {
expect(toggleSpy).toHaveBeenCalledWith(jasmine.any(Object), true);
});
it('setup debounced mouseleave', (done) => {
it('setup debounced mouseleave', done => {
const toggleSpy = spyOn(popover.togglePopover, 'call');
$(selector).trigger('mouseleave');
@ -64,7 +64,9 @@ describe('feature highlight', () => {
it('setup show.bs.popover', () => {
$(selector).trigger('show.bs.popover');
expect(window.addEventListener).toHaveBeenCalledWith('scroll', jasmine.any(Function), { once: true });
expect(window.addEventListener).toHaveBeenCalledWith('scroll', jasmine.any(Function), {
once: true,
});
});
it('removes disabled attribute', () => {

View File

@ -3,7 +3,7 @@ import eventHub from '~/filtered_search/event_hub';
import RecentSearchesDropdownContent from '~/filtered_search/components/recent_searches_dropdown_content.vue';
import IssuableFilteredSearchTokenKeys from '~/filtered_search/issuable_filtered_search_token_keys';
const createComponent = (propsData) => {
const createComponent = propsData => {
const Component = Vue.extend(RecentSearchesDropdownContent);
return new Component({
@ -21,10 +21,7 @@ describe('RecentSearchesDropdownContent', () => {
allowedKeys: IssuableFilteredSearchTokenKeys.getKeys(),
};
const propsDataWithItems = {
items: [
'foo',
'author:@root label:~foo bar',
],
items: ['foo', 'author:@root label:~foo bar'],
allowedKeys: IssuableFilteredSearchTokenKeys.getKeys(),
};
@ -69,7 +66,11 @@ describe('RecentSearchesDropdownContent', () => {
expect(items.length).toEqual(propsDataWithItems.items.length);
expect(trimMarkupWhitespace(items[0].querySelector('.filtered-search-history-dropdown-search-token').textContent)).toEqual('foo');
expect(
trimMarkupWhitespace(
items[0].querySelector('.filtered-search-history-dropdown-search-token').textContent,
),
).toEqual('foo');
const item1Tokens = items[1].querySelectorAll('.filtered-search-history-dropdown-token');
@ -78,7 +79,11 @@ describe('RecentSearchesDropdownContent', () => {
expect(item1Tokens[0].querySelector('.value').textContent).toEqual('@root');
expect(item1Tokens[1].querySelector('.name').textContent).toEqual('label:');
expect(item1Tokens[1].querySelector('.value').textContent).toEqual('~foo');
expect(trimMarkupWhitespace(items[1].querySelector('.filtered-search-history-dropdown-search-token').textContent)).toEqual('bar');
expect(
trimMarkupWhitespace(
items[1].querySelector('.filtered-search-history-dropdown-search-token').textContent,
),
).toEqual('bar');
});
});

View File

@ -28,14 +28,14 @@ describe('Dropdown User', () => {
it('should not return the single quote found in value', () => {
spyOn(FilteredSearchTokenizer, 'processTokens').and.returnValue({
lastToken: '\'larry boy',
lastToken: "'larry boy",
});
expect(dropdownUser.getSearchInput()).toBe('larry boy');
});
});
describe('config AjaxFilter\'s endpoint', () => {
describe("config AjaxFilter's endpoint", () => {
beforeEach(() => {
spyOn(DropdownUser.prototype, 'bindEvents').and.callFake(() => {});
spyOn(DropdownUser.prototype, 'getProjectId').and.callFake(() => {});
@ -88,7 +88,8 @@ describe('Dropdown User', () => {
});
});
const findCurrentUserElement = () => authorFilterDropdownElement.querySelector('.js-current-user');
const findCurrentUserElement = () =>
authorFilterDropdownElement.querySelector('.js-current-user');
it('hides the current user from dropdown', () => {
const currentUserElement = findCurrentUserElement();

View File

@ -19,7 +19,7 @@ describe('Dropdown Utils', () => {
expect(escaped).toBe('"text with space"');
escaped = DropdownUtils.getEscapedText('won\'t fix');
escaped = DropdownUtils.getEscapedText("won't fix");
expect(escaped).toBe('"won\'t fix"');
});
@ -27,13 +27,13 @@ describe('Dropdown Utils', () => {
it('should escape with single quotes', () => {
const escaped = DropdownUtils.getEscapedText('won"t fix');
expect(escaped).toBe('\'won"t fix\'');
expect(escaped).toBe("'won\"t fix'");
});
it('should escape with single quotes by default', () => {
const escaped = DropdownUtils.getEscapedText('won"t\' fix');
expect(escaped).toBe('\'won"t\' fix\'');
expect(escaped).toBe("'won\"t' fix'");
});
});
@ -105,7 +105,7 @@ describe('Dropdown Utils', () => {
});
it('should filter with single quote', () => {
input.value = '\'';
input.value = "'";
const updatedItem = DropdownUtils.filterWithSymbol('~', input, multipleWordItem);
@ -113,7 +113,7 @@ describe('Dropdown Utils', () => {
});
it('should filter with single quote and symbol', () => {
input.value = '~\'';
input.value = "~'";
const updatedItem = DropdownUtils.filterWithSymbol('~', input, multipleWordItem);
@ -121,7 +121,7 @@ describe('Dropdown Utils', () => {
});
it('should filter with single quote and multiple words', () => {
input.value = '\'community con';
input.value = "'community con";
const updatedItem = DropdownUtils.filterWithSymbol('~', input, multipleWordItem);
@ -129,7 +129,7 @@ describe('Dropdown Utils', () => {
});
it('should filter with single quote, symbol and multiple words', () => {
input.value = '~\'community con';
input.value = "~'community con";
const updatedItem = DropdownUtils.filterWithSymbol('~', input, multipleWordItem);
@ -246,23 +246,40 @@ describe('Dropdown Utils', () => {
it('should linear-gradient 2 colors', () => {
const gradient = DropdownUtils.duplicateLabelColor(['#FFFFFF', '#000000']);
expect(gradient).toEqual('linear-gradient(#FFFFFF 0%, #FFFFFF 50%, #000000 50%, #000000 100%)');
expect(gradient).toEqual(
'linear-gradient(#FFFFFF 0%, #FFFFFF 50%, #000000 50%, #000000 100%)',
);
});
it('should linear-gradient 3 colors', () => {
const gradient = DropdownUtils.duplicateLabelColor(['#FFFFFF', '#000000', '#333333']);
expect(gradient).toEqual('linear-gradient(#FFFFFF 0%, #FFFFFF 33%, #000000 33%, #000000 66%, #333333 66%, #333333 100%)');
expect(gradient).toEqual(
'linear-gradient(#FFFFFF 0%, #FFFFFF 33%, #000000 33%, #000000 66%, #333333 66%, #333333 100%)',
);
});
it('should linear-gradient 4 colors', () => {
const gradient = DropdownUtils.duplicateLabelColor(['#FFFFFF', '#000000', '#333333', '#DDDDDD']);
const gradient = DropdownUtils.duplicateLabelColor([
'#FFFFFF',
'#000000',
'#333333',
'#DDDDDD',
]);
expect(gradient).toEqual('linear-gradient(#FFFFFF 0%, #FFFFFF 25%, #000000 25%, #000000 50%, #333333 50%, #333333 75%, #DDDDDD 75%, #DDDDDD 100%)');
expect(gradient).toEqual(
'linear-gradient(#FFFFFF 0%, #FFFFFF 25%, #000000 25%, #000000 50%, #333333 50%, #333333 75%, #DDDDDD 75%, #DDDDDD 100%)',
);
});
it('should not linear-gradient more than 4 colors', () => {
const gradient = DropdownUtils.duplicateLabelColor(['#FFFFFF', '#000000', '#333333', '#DDDDDD', '#EEEEEE']);
const gradient = DropdownUtils.duplicateLabelColor([
'#FFFFFF',
'#000000',
'#333333',
'#DDDDDD',
'#EEEEEE',
]);
expect(gradient.indexOf('#EEEEEE')).toBe(-1);
});
@ -276,13 +293,16 @@ describe('Dropdown Utils', () => {
});
it('should not mutate existing data if there are no duplicates', () => {
const data = [{
title: 'label1',
color: '#FFFFFF',
}, {
title: 'label2',
color: '#000000',
}];
const data = [
{
title: 'label1',
color: '#FFFFFF',
},
{
title: 'label2',
color: '#000000',
},
];
const results = DropdownUtils.duplicateLabelPreprocessing(data);
expect(results.length).toEqual(2);
@ -291,13 +311,16 @@ describe('Dropdown Utils', () => {
});
describe('duplicate labels', () => {
const data = [{
title: 'label',
color: '#FFFFFF',
}, {
title: 'label',
color: '#000000',
}];
const data = [
{
title: 'label',
color: '#FFFFFF',
},
{
title: 'label',
color: '#000000',
},
];
const results = DropdownUtils.duplicateLabelPreprocessing(data);
it('should merge duplicate labels', () => {

View File

@ -9,7 +9,7 @@ import FilteredSearchDropdownManager from '~/filtered_search/filtered_search_dro
import FilteredSearchManager from '~/filtered_search/filtered_search_manager';
import FilteredSearchSpecHelper from '../helpers/filtered_search_spec_helper';
describe('Filtered Search Manager', function () {
describe('Filtered Search Manager', function() {
let input;
let manager;
let tokensContainer;
@ -97,7 +97,9 @@ describe('Filtered Search Manager', function () {
});
it('should not instantiate Flash if an RecentSearchesServiceError is caught', () => {
spyOn(RecentSearchesService.prototype, 'fetch').and.callFake(() => Promise.reject(new RecentSearchesServiceError()));
spyOn(RecentSearchesService.prototype, 'fetch').and.callFake(() =>
Promise.reject(new RecentSearchesServiceError()),
);
spyOn(window, 'Flash');
manager.setup();
@ -162,10 +164,10 @@ describe('Filtered Search Manager', function () {
initializeManager();
});
it('should search with a single word', (done) => {
it('should search with a single word', done => {
input.value = 'searchTerm';
spyOnDependency(FilteredSearchManager, 'visitUrl').and.callFake((url) => {
spyOnDependency(FilteredSearchManager, 'visitUrl').and.callFake(url => {
expect(url).toEqual(`${defaultParams}&search=searchTerm`);
done();
});
@ -173,10 +175,10 @@ describe('Filtered Search Manager', function () {
manager.search();
});
it('should search with multiple words', (done) => {
it('should search with multiple words', done => {
input.value = 'awesome search terms';
spyOnDependency(FilteredSearchManager, 'visitUrl').and.callFake((url) => {
spyOnDependency(FilteredSearchManager, 'visitUrl').and.callFake(url => {
expect(url).toEqual(`${defaultParams}&search=awesome+search+terms`);
done();
});
@ -184,24 +186,26 @@ describe('Filtered Search Manager', function () {
manager.search();
});
it('should search with special characters', (done) => {
it('should search with special characters', done => {
input.value = '~!@#$%^&*()_+{}:<>,.?/';
spyOnDependency(FilteredSearchManager, 'visitUrl').and.callFake((url) => {
expect(url).toEqual(`${defaultParams}&search=~!%40%23%24%25%5E%26*()_%2B%7B%7D%3A%3C%3E%2C.%3F%2F`);
spyOnDependency(FilteredSearchManager, 'visitUrl').and.callFake(url => {
expect(url).toEqual(
`${defaultParams}&search=~!%40%23%24%25%5E%26*()_%2B%7B%7D%3A%3C%3E%2C.%3F%2F`,
);
done();
});
manager.search();
});
it('removes duplicated tokens', (done) => {
it('removes duplicated tokens', done => {
tokensContainer.innerHTML = FilteredSearchSpecHelper.createTokensContainerHTML(`
${FilteredSearchSpecHelper.createFilterVisualTokenHTML('label', '~bug')}
${FilteredSearchSpecHelper.createFilterVisualTokenHTML('label', '~bug')}
`);
spyOnDependency(FilteredSearchManager, 'visitUrl').and.callFake((url) => {
spyOnDependency(FilteredSearchManager, 'visitUrl').and.callFake(url => {
expect(url).toEqual(`${defaultParams}&label_name[]=bug`);
done();
});
@ -441,13 +445,17 @@ describe('Filtered Search Manager', function () {
it('toggles on focus', () => {
input.focus();
expect(document.querySelector('.filtered-search-box').classList.contains('focus')).toEqual(true);
expect(document.querySelector('.filtered-search-box').classList.contains('focus')).toEqual(
true,
);
});
it('toggles on blur', () => {
input.blur();
expect(document.querySelector('.filtered-search-box').classList.contains('focus')).toEqual(false);
expect(document.querySelector('.filtered-search-box').classList.contains('focus')).toEqual(
false,
);
});
});
@ -459,9 +467,12 @@ describe('Filtered Search Manager', function () {
});
it('correctly modifies params when custom modifier is passed', () => {
const modifedParams = manager.getAllParams.call({
modifyUrlParams: paramsArr => paramsArr.reverse(),
}, [].concat(this.paramsArr));
const modifedParams = manager.getAllParams.call(
{
modifyUrlParams: paramsArr => paramsArr.reverse(),
},
[].concat(this.paramsArr),
);
expect(modifedParams[0]).toBe(this.paramsArr[1]);
});

View File

@ -1,23 +1,26 @@
import FilteredSearchTokenKeys from '~/filtered_search/filtered_search_token_keys';
describe('Filtered Search Token Keys', () => {
const tokenKeys = [{
key: 'author',
type: 'string',
param: 'username',
symbol: '@',
icon: 'pencil',
tag: '@author',
}];
const tokenKeys = [
{
key: 'author',
type: 'string',
param: 'username',
symbol: '@',
icon: 'pencil',
tag: '@author',
},
];
const conditions = [{
url: 'assignee_id=0',
tokenKey: 'assignee',
value: 'none',
}];
const conditions = [
{
url: 'assignee_id=0',
tokenKey: 'assignee',
value: 'none',
},
];
describe('get', () => {
it('should return tokenKeys', () => {
expect(new FilteredSearchTokenKeys().get()).not.toBeNull();
});
@ -84,13 +87,17 @@ describe('Filtered Search Token Keys', () => {
});
it('should return tokenKey when found by key param', () => {
const result = new FilteredSearchTokenKeys(tokenKeys).searchByKeyParam(`${tokenKeys[0].key}_${tokenKeys[0].param}`);
const result = new FilteredSearchTokenKeys(tokenKeys).searchByKeyParam(
`${tokenKeys[0].key}_${tokenKeys[0].param}`,
);
expect(result).toEqual(tokenKeys[0]);
});
it('should return alternative tokenKey when found by key param', () => {
const result = new FilteredSearchTokenKeys(tokenKeys).searchByKeyParam(`${tokenKeys[0].key}_${tokenKeys[0].param}`);
const result = new FilteredSearchTokenKeys(tokenKeys).searchByKeyParam(
`${tokenKeys[0].key}_${tokenKeys[0].param}`,
);
expect(result).toEqual(tokenKeys[0]);
});
@ -104,8 +111,9 @@ describe('Filtered Search Token Keys', () => {
});
it('should return condition when found by url', () => {
const result = new FilteredSearchTokenKeys([], [], conditions)
.searchByConditionUrl(conditions[0].url);
const result = new FilteredSearchTokenKeys([], [], conditions).searchByConditionUrl(
conditions[0].url,
);
expect(result).toBe(conditions[0]);
});
@ -113,15 +121,19 @@ describe('Filtered Search Token Keys', () => {
describe('searchByConditionKeyValue', () => {
it('should return null when condition tokenKey and value not found', () => {
const condition = new FilteredSearchTokenKeys([], [], conditions)
.searchByConditionKeyValue(null, null);
const condition = new FilteredSearchTokenKeys([], [], conditions).searchByConditionKeyValue(
null,
null,
);
expect(condition).toBeNull();
});
it('should return condition when found by tokenKey and value', () => {
const result = new FilteredSearchTokenKeys([], [], conditions)
.searchByConditionKeyValue(conditions[0].tokenKey, conditions[0].value);
const result = new FilteredSearchTokenKeys([], [], conditions).searchByConditionKeyValue(
conditions[0].tokenKey,
conditions[0].value,
);
expect(result).toEqual(conditions[0]);
});

View File

@ -14,8 +14,10 @@ describe('Filtered Search Tokenizer', () => {
});
it('returns for input containing only tokens', () => {
const results = FilteredSearchTokenizer
.processTokens('author:@root label:~"Very Important" milestone:%v1.0 assignee:none', allowedKeys);
const results = FilteredSearchTokenizer.processTokens(
'author:@root label:~"Very Important" milestone:%v1.0 assignee:none',
allowedKeys,
);
expect(results.searchToken).toBe('');
expect(results.tokens.length).toBe(4);
@ -39,8 +41,10 @@ describe('Filtered Search Tokenizer', () => {
});
it('returns for input starting with search value and ending with tokens', () => {
const results = FilteredSearchTokenizer
.processTokens('searchTerm anotherSearchTerm milestone:none', allowedKeys);
const results = FilteredSearchTokenizer.processTokens(
'searchTerm anotherSearchTerm milestone:none',
allowedKeys,
);
expect(results.searchToken).toBe('searchTerm anotherSearchTerm');
expect(results.tokens.length).toBe(1);
@ -51,8 +55,10 @@ describe('Filtered Search Tokenizer', () => {
});
it('returns for input starting with tokens and ending with search value', () => {
const results = FilteredSearchTokenizer
.processTokens('assignee:@user searchTerm', allowedKeys);
const results = FilteredSearchTokenizer.processTokens(
'assignee:@user searchTerm',
allowedKeys,
);
expect(results.searchToken).toBe('searchTerm');
expect(results.tokens.length).toBe(1);
@ -63,8 +69,10 @@ describe('Filtered Search Tokenizer', () => {
});
it('returns for input containing search value wrapped between tokens', () => {
const results = FilteredSearchTokenizer
.processTokens('author:@root label:~"Won\'t fix" searchTerm anotherSearchTerm milestone:none', allowedKeys);
const results = FilteredSearchTokenizer.processTokens(
'author:@root label:~"Won\'t fix" searchTerm anotherSearchTerm milestone:none',
allowedKeys,
);
expect(results.searchToken).toBe('searchTerm anotherSearchTerm');
expect(results.tokens.length).toBe(3);
@ -84,8 +92,10 @@ describe('Filtered Search Tokenizer', () => {
});
it('returns for input containing search value in between tokens', () => {
const results = FilteredSearchTokenizer
.processTokens('author:@root searchTerm assignee:none anotherSearchTerm label:~Doing', allowedKeys);
const results = FilteredSearchTokenizer.processTokens(
'author:@root searchTerm assignee:none anotherSearchTerm label:~Doing',
allowedKeys,
);
expect(results.searchToken).toBe('searchTerm anotherSearchTerm');
expect(results.tokens.length).toBe(3);

View File

@ -9,7 +9,7 @@ import FilteredSearchSpecHelper from '../helpers/filtered_search_spec_helper';
describe('Filtered Search Visual Tokens', () => {
const subject = FilteredSearchVisualTokens;
const findElements = (tokenElement) => {
const findElements = tokenElement => {
const tokenNameElement = tokenElement.querySelector('.name');
const tokenValueContainer = tokenElement.querySelector('.value-container');
const tokenValueElement = tokenValueContainer.querySelector('.value');
@ -34,8 +34,7 @@ describe('Filtered Search Visual Tokens', () => {
describe('getLastVisualTokenBeforeInput', () => {
it('returns when there are no visual tokens', () => {
const { lastVisualToken, isLastVisualTokenValid }
= subject.getLastVisualTokenBeforeInput();
const { lastVisualToken, isLastVisualTokenValid } = subject.getLastVisualTokenBeforeInput();
expect(lastVisualToken).toEqual(null);
expect(isLastVisualTokenValid).toEqual(true);
@ -47,8 +46,7 @@ describe('Filtered Search Visual Tokens', () => {
bugLabelToken.outerHTML,
);
const { lastVisualToken, isLastVisualTokenValid }
= subject.getLastVisualTokenBeforeInput();
const { lastVisualToken, isLastVisualTokenValid } = subject.getLastVisualTokenBeforeInput();
expect(lastVisualToken).toEqual(document.querySelector('.filtered-search-token'));
expect(isLastVisualTokenValid).toEqual(true);
@ -59,8 +57,7 @@ describe('Filtered Search Visual Tokens', () => {
FilteredSearchSpecHelper.createNameFilterVisualTokenHTML('Author'),
);
const { lastVisualToken, isLastVisualTokenValid }
= subject.getLastVisualTokenBeforeInput();
const { lastVisualToken, isLastVisualTokenValid } = subject.getLastVisualTokenBeforeInput();
expect(lastVisualToken).toEqual(document.querySelector('.filtered-search-token'));
expect(isLastVisualTokenValid).toEqual(false);
@ -73,8 +70,7 @@ describe('Filtered Search Visual Tokens', () => {
${FilteredSearchSpecHelper.createFilterVisualTokenHTML('author', '@root')}
`);
const { lastVisualToken, isLastVisualTokenValid }
= subject.getLastVisualTokenBeforeInput();
const { lastVisualToken, isLastVisualTokenValid } = subject.getLastVisualTokenBeforeInput();
const items = document.querySelectorAll('.tokens-container .js-visual-token');
expect(lastVisualToken.isEqualNode(items[items.length - 1])).toEqual(true);
@ -88,8 +84,7 @@ describe('Filtered Search Visual Tokens', () => {
${FilteredSearchSpecHelper.createNameFilterVisualTokenHTML('assignee')}
`);
const { lastVisualToken, isLastVisualTokenValid }
= subject.getLastVisualTokenBeforeInput();
const { lastVisualToken, isLastVisualTokenValid } = subject.getLastVisualTokenBeforeInput();
const items = document.querySelectorAll('.tokens-container .js-visual-token');
expect(lastVisualToken.isEqualNode(items[items.length - 1])).toEqual(true);
@ -105,8 +100,7 @@ describe('Filtered Search Visual Tokens', () => {
${FilteredSearchSpecHelper.createFilterVisualTokenHTML('author', '@root')}
`);
const { lastVisualToken, isLastVisualTokenValid }
= subject.getLastVisualTokenBeforeInput();
const { lastVisualToken, isLastVisualTokenValid } = subject.getLastVisualTokenBeforeInput();
expect(lastVisualToken).toEqual(document.querySelector('.filtered-search-token'));
expect(isLastVisualTokenValid).toEqual(true);
@ -119,8 +113,7 @@ describe('Filtered Search Visual Tokens', () => {
${FilteredSearchSpecHelper.createFilterVisualTokenHTML('author', '@root')}
`);
const { lastVisualToken, isLastVisualTokenValid }
= subject.getLastVisualTokenBeforeInput();
const { lastVisualToken, isLastVisualTokenValid } = subject.getLastVisualTokenBeforeInput();
expect(lastVisualToken).toEqual(document.querySelector('.filtered-search-token'));
expect(isLastVisualTokenValid).toEqual(false);
@ -142,8 +135,12 @@ describe('Filtered Search Visual Tokens', () => {
const singleQueryParams = '{"foo":"true"}';
const multipleQueryParams = '{"foo":"true","bar":"true"}';
expect(subject.getEndpointWithQueryParams(endpoint, singleQueryParams)).toBe(`${endpoint}?foo=true`);
expect(subject.getEndpointWithQueryParams(endpoint, multipleQueryParams)).toBe(`${endpoint}?foo=true&bar=true`);
expect(subject.getEndpointWithQueryParams(endpoint, singleQueryParams)).toBe(
`${endpoint}?foo=true`,
);
expect(subject.getEndpointWithQueryParams(endpoint, multipleQueryParams)).toBe(
`${endpoint}?foo=true&bar=true`,
);
});
});
@ -275,7 +272,9 @@ describe('Filtered Search Visual Tokens', () => {
describe('remove token', () => {
it('contains remove-token button', () => {
expect(tokenElement.querySelector('.value-container .remove-token')).toEqual(jasmine.anything());
expect(tokenElement.querySelector('.value-container .remove-token')).toEqual(
jasmine.anything(),
);
});
it('contains fa-close icon', () => {
@ -313,7 +312,9 @@ describe('Filtered Search Visual Tokens', () => {
});
it('inserts visual token before input', () => {
tokensContainer.appendChild(FilteredSearchSpecHelper.createFilterVisualToken('assignee', '@root'));
tokensContainer.appendChild(
FilteredSearchSpecHelper.createFilterVisualToken('assignee', '@root'),
);
subject.addVisualTokenElement('label', 'Frontend');
const tokens = tokensContainer.querySelectorAll('.js-visual-token');
@ -552,7 +553,7 @@ describe('Filtered Search Visual Tokens', () => {
token = document.querySelector('.js-visual-token');
});
it('tokenize\'s existing input', () => {
it("tokenize's existing input", () => {
input.value = 'some text';
spyOn(subject, 'tokenizeInput').and.callThrough();
@ -625,7 +626,7 @@ describe('Filtered Search Visual Tokens', () => {
expect(subject.getLastVisualTokenBeforeInput).not.toHaveBeenCalled();
});
it('tokenize\'s input', () => {
it("tokenize's input", () => {
tokensContainer.innerHTML = `
${FilteredSearchSpecHelper.createNameFilterVisualTokenHTML('label')}
${FilteredSearchSpecHelper.createInputHTML()}
@ -684,7 +685,10 @@ describe('Filtered Search Visual Tokens', () => {
describe('renderVisualTokenValue', () => {
const keywordToken = FilteredSearchSpecHelper.createFilterVisualToken('search');
const milestoneToken = FilteredSearchSpecHelper.createFilterVisualToken('milestone', 'upcoming');
const milestoneToken = FilteredSearchSpecHelper.createFilterVisualToken(
'milestone',
'upcoming',
);
let updateLabelTokenColorSpy;
let updateUserTokenAppearanceSpy;
@ -705,8 +709,9 @@ describe('Filtered Search Visual Tokens', () => {
});
it('renders a author token value element', () => {
const { tokenNameElement, tokenValueContainer, tokenValueElement } =
findElements(authorToken);
const { tokenNameElement, tokenValueContainer, tokenValueElement } = findElements(
authorToken,
);
const tokenName = tokenNameElement.innerText;
const tokenValue = 'new value';
@ -721,8 +726,9 @@ describe('Filtered Search Visual Tokens', () => {
});
it('renders a label token value element', () => {
const { tokenNameElement, tokenValueContainer, tokenValueElement } =
findElements(bugLabelToken);
const { tokenNameElement, tokenValueContainer, tokenValueElement } = findElements(
bugLabelToken,
);
const tokenName = tokenNameElement.innerText;
const tokenValue = 'new value';
@ -756,98 +762,103 @@ describe('Filtered Search Visual Tokens', () => {
spyOn(UsersCache, 'retrieve').and.callFake(username => usersCacheSpy(username));
});
it('ignores special value "none"', (done) => {
usersCacheSpy = (username) => {
it('ignores special value "none"', done => {
usersCacheSpy = username => {
expect(username).toBe('none');
done.fail('Should not resolve "none"!');
};
const { tokenValueContainer, tokenValueElement } = findElements(authorToken);
subject.updateUserTokenAppearance(tokenValueContainer, tokenValueElement, 'none')
.then(done)
.catch(done.fail);
subject
.updateUserTokenAppearance(tokenValueContainer, tokenValueElement, 'none')
.then(done)
.catch(done.fail);
});
it('ignores error if UsersCache throws', (done) => {
it('ignores error if UsersCache throws', done => {
spyOn(window, 'Flash');
const dummyError = new Error('Earth rotated backwards');
const { tokenValueContainer, tokenValueElement } = findElements(authorToken);
const tokenValue = tokenValueElement.innerText;
usersCacheSpy = (username) => {
usersCacheSpy = username => {
expect(`@${username}`).toBe(tokenValue);
return Promise.reject(dummyError);
};
subject.updateUserTokenAppearance(tokenValueContainer, tokenValueElement, tokenValue)
.then(() => {
expect(window.Flash.calls.count()).toBe(0);
})
.then(done)
.catch(done.fail);
subject
.updateUserTokenAppearance(tokenValueContainer, tokenValueElement, tokenValue)
.then(() => {
expect(window.Flash.calls.count()).toBe(0);
})
.then(done)
.catch(done.fail);
});
it('does nothing if user cannot be found', (done) => {
it('does nothing if user cannot be found', done => {
const { tokenValueContainer, tokenValueElement } = findElements(authorToken);
const tokenValue = tokenValueElement.innerText;
usersCacheSpy = (username) => {
usersCacheSpy = username => {
expect(`@${username}`).toBe(tokenValue);
return Promise.resolve(undefined);
};
subject.updateUserTokenAppearance(tokenValueContainer, tokenValueElement, tokenValue)
.then(() => {
expect(tokenValueElement.innerText).toBe(tokenValue);
})
.then(done)
.catch(done.fail);
subject
.updateUserTokenAppearance(tokenValueContainer, tokenValueElement, tokenValue)
.then(() => {
expect(tokenValueElement.innerText).toBe(tokenValue);
})
.then(done)
.catch(done.fail);
});
it('replaces author token with avatar and display name', (done) => {
it('replaces author token with avatar and display name', done => {
const dummyUser = {
name: 'Important Person',
avatar_url: 'https://host.invalid/mypics/avatar.png',
};
const { tokenValueContainer, tokenValueElement } = findElements(authorToken);
const tokenValue = tokenValueElement.innerText;
usersCacheSpy = (username) => {
usersCacheSpy = username => {
expect(`@${username}`).toBe(tokenValue);
return Promise.resolve(dummyUser);
};
subject.updateUserTokenAppearance(tokenValueContainer, tokenValueElement, tokenValue)
.then(() => {
expect(tokenValueContainer.dataset.originalValue).toBe(tokenValue);
expect(tokenValueElement.innerText.trim()).toBe(dummyUser.name);
const avatar = tokenValueElement.querySelector('img.avatar');
subject
.updateUserTokenAppearance(tokenValueContainer, tokenValueElement, tokenValue)
.then(() => {
expect(tokenValueContainer.dataset.originalValue).toBe(tokenValue);
expect(tokenValueElement.innerText.trim()).toBe(dummyUser.name);
const avatar = tokenValueElement.querySelector('img.avatar');
expect(avatar.src).toBe(dummyUser.avatar_url);
expect(avatar.alt).toBe('');
})
.then(done)
.catch(done.fail);
expect(avatar.src).toBe(dummyUser.avatar_url);
expect(avatar.alt).toBe('');
})
.then(done)
.catch(done.fail);
});
it('escapes user name when creating token', (done) => {
it('escapes user name when creating token', done => {
const dummyUser = {
name: '<script>',
avatar_url: `${gl.TEST_HOST}/mypics/avatar.png`,
};
const { tokenValueContainer, tokenValueElement } = findElements(authorToken);
const tokenValue = tokenValueElement.innerText;
usersCacheSpy = (username) => {
usersCacheSpy = username => {
expect(`@${username}`).toBe(tokenValue);
return Promise.resolve(dummyUser);
};
subject.updateUserTokenAppearance(tokenValueContainer, tokenValueElement, tokenValue)
.then(() => {
expect(tokenValueElement.innerText.trim()).toBe(dummyUser.name);
tokenValueElement.querySelector('.avatar').remove();
subject
.updateUserTokenAppearance(tokenValueContainer, tokenValueElement, tokenValue)
.then(() => {
expect(tokenValueElement.innerText.trim()).toBe(dummyUser.name);
tokenValueElement.querySelector('.avatar').remove();
expect(tokenValueElement.innerHTML.trim()).toBe(_.escape(dummyUser.name));
})
.then(done)
.catch(done.fail);
expect(tokenValueElement.innerHTML.trim()).toBe(_.escape(dummyUser.name));
})
.then(done)
.catch(done.fail);
});
});
@ -867,7 +878,11 @@ describe('Filtered Search Visual Tokens', () => {
});
it('should not set backgroundColor when it is a linear-gradient', () => {
const token = subject.setTokenStyle(bugLabelToken, 'linear-gradient(135deg, red, blue)', 'white');
const token = subject.setTokenStyle(
bugLabelToken,
'linear-gradient(135deg, red, blue)',
'white',
);
expect(token.style.backgroundColor).toEqual(bugLabelToken.style.backgroundColor);
});
@ -933,8 +948,14 @@ describe('Filtered Search Visual Tokens', () => {
labelData = getJSONFixture(jsonFixtureName);
});
const missingLabelToken = FilteredSearchSpecHelper.createFilterVisualToken('label', '~doesnotexist');
const spaceLabelToken = FilteredSearchSpecHelper.createFilterVisualToken('label', '~"some space"');
const missingLabelToken = FilteredSearchSpecHelper.createFilterVisualToken(
'label',
'~doesnotexist',
);
const spaceLabelToken = FilteredSearchSpecHelper.createFilterVisualToken(
'label',
'~"some space"',
);
beforeEach(() => {
tokensContainer.innerHTML = FilteredSearchSpecHelper.createTokensContainerHTML(`
@ -946,11 +967,11 @@ describe('Filtered Search Visual Tokens', () => {
const filteredSearchInput = document.querySelector('.filtered-search');
filteredSearchInput.dataset.baseEndpoint = dummyEndpoint;
AjaxCache.internalStorage = { };
AjaxCache.internalStorage = {};
AjaxCache.internalStorage[`${dummyEndpoint}/labels.json`] = labelData;
});
const parseColor = (color) => {
const parseColor = color => {
const dummyElement = document.createElement('div');
dummyElement.style.color = color;
return dummyElement.style.color;
@ -962,16 +983,16 @@ describe('Filtered Search Visual Tokens', () => {
expect(tokenValueContainer.style.color).toBe(parseColor(label.text_color));
};
const findLabel = tokenValue => labelData.find(
label => tokenValue === `~${DropdownUtils.getEscapedText(label.title)}`,
);
const findLabel = tokenValue =>
labelData.find(label => tokenValue === `~${DropdownUtils.getEscapedText(label.title)}`);
it('updates the color of a label token', (done) => {
it('updates the color of a label token', done => {
const { tokenValueContainer, tokenValueElement } = findElements(bugLabelToken);
const tokenValue = tokenValueElement.innerText;
const matchingLabel = findLabel(tokenValue);
subject.updateLabelTokenColor(tokenValueContainer, tokenValue)
subject
.updateLabelTokenColor(tokenValueContainer, tokenValue)
.then(() => {
expectValueContainerStyle(tokenValueContainer, matchingLabel);
})
@ -979,12 +1000,13 @@ describe('Filtered Search Visual Tokens', () => {
.catch(done.fail);
});
it('updates the color of a label token with spaces', (done) => {
it('updates the color of a label token with spaces', done => {
const { tokenValueContainer, tokenValueElement } = findElements(spaceLabelToken);
const tokenValue = tokenValueElement.innerText;
const matchingLabel = findLabel(tokenValue);
subject.updateLabelTokenColor(tokenValueContainer, tokenValue)
subject
.updateLabelTokenColor(tokenValueContainer, tokenValue)
.then(() => {
expectValueContainerStyle(tokenValueContainer, matchingLabel);
})
@ -992,14 +1014,15 @@ describe('Filtered Search Visual Tokens', () => {
.catch(done.fail);
});
it('does not change color of a missing label', (done) => {
it('does not change color of a missing label', done => {
const { tokenValueContainer, tokenValueElement } = findElements(missingLabelToken);
const tokenValue = tokenValueElement.innerText;
const matchingLabel = findLabel(tokenValue);
expect(matchingLabel).toBe(undefined);
subject.updateLabelTokenColor(tokenValueContainer, tokenValue)
subject
.updateLabelTokenColor(tokenValueContainer, tokenValue)
.then(() => {
expect(tokenValueContainer.getAttribute('style')).toBe(null);
})

View File

@ -14,7 +14,7 @@ describe('RecentSearchesRoot', () => {
},
};
VueSpy = spyOnDependency(RecentSearchesRoot, 'Vue').and.callFake((options) => {
VueSpy = spyOnDependency(RecentSearchesRoot, 'Vue').and.callFake(options => {
({ data, template } = options);
});

View File

@ -15,48 +15,49 @@ describe('RecentSearchesService', () => {
spyOn(RecentSearchesService, 'isAvailable').and.returnValue(true);
});
it('should default to empty array', (done) => {
it('should default to empty array', done => {
const fetchItemsPromise = service.fetch();
fetchItemsPromise
.then((items) => {
.then(items => {
expect(items).toEqual([]);
})
.then(done)
.catch(done.fail);
});
it('should reject when unable to parse', (done) => {
it('should reject when unable to parse', done => {
window.localStorage.setItem(service.localStorageKey, 'fail');
const fetchItemsPromise = service.fetch();
fetchItemsPromise
.then(done.fail)
.catch((error) => {
.catch(error => {
expect(error).toEqual(jasmine.any(SyntaxError));
})
.then(done)
.catch(done.fail);
});
it('should reject when service is unavailable', (done) => {
it('should reject when service is unavailable', done => {
RecentSearchesService.isAvailable.and.returnValue(false);
service.fetch()
service
.fetch()
.then(done.fail)
.catch((error) => {
.catch(error => {
expect(error).toEqual(jasmine.any(Error));
})
.then(done)
.catch(done.fail);
});
it('should return items from localStorage', (done) => {
it('should return items from localStorage', done => {
window.localStorage.setItem(service.localStorageKey, '["foo", "bar"]');
const fetchItemsPromise = service.fetch();
fetchItemsPromise
.then((items) => {
.then(items => {
expect(items).toEqual(['foo', 'bar']);
})
.then(done)
@ -70,10 +71,11 @@ describe('RecentSearchesService', () => {
spyOn(window.localStorage, 'getItem');
});
it('should not call .getItem', (done) => {
RecentSearchesService.prototype.fetch()
it('should not call .getItem', done => {
RecentSearchesService.prototype
.fetch()
.then(done.fail)
.catch((err) => {
.catch(err => {
expect(err).toEqual(new RecentSearchesServiceError());
expect(window.localStorage.getItem).not.toHaveBeenCalled();
})

View File

@ -38,14 +38,8 @@ describe('RecentSearchesStore', () => {
describe('setRecentSearches', () => {
it('should override list', () => {
store.setRecentSearches([
'foo',
'bar',
]);
store.setRecentSearches([
'baz',
'qux',
]);
store.setRecentSearches(['foo', 'bar']);
store.setRecentSearches(['baz', 'qux']);
expect(store.state.recentSearches).toEqual(['baz', 'qux']);
});

View File

@ -1,9 +1,4 @@
import flash, {
createFlashEl,
createAction,
hideFlash,
removeFlashClickListener,
} from '~/flash';
import flash, { createFlashEl, createAction, hideFlash, removeFlashClickListener } from '~/flash';
describe('Flash', () => {
describe('createFlashEl', () => {
@ -20,29 +15,23 @@ describe('Flash', () => {
it('creates flash element with type', () => {
el.innerHTML = createFlashEl('testing', 'alert');
expect(
el.querySelector('.flash-alert'),
).not.toBeNull();
expect(el.querySelector('.flash-alert')).not.toBeNull();
});
it('escapes text', () => {
el.innerHTML = createFlashEl('<script>alert("a");</script>', 'alert');
expect(
el.querySelector('.flash-text').textContent.trim(),
).toBe('<script>alert("a");</script>');
expect(el.querySelector('.flash-text').textContent.trim()).toBe(
'<script>alert("a");</script>',
);
});
it('adds container classes when inside content wrapper', () => {
el.innerHTML = createFlashEl('testing', 'alert', true);
expect(
el.querySelector('.flash-text').classList.contains('container-fluid'),
).toBeTruthy();
expect(el.querySelector('.flash-text').classList.contains('container-fluid')).toBeTruthy();
expect(
el.querySelector('.flash-text').classList.contains('container-limited'),
).toBeTruthy();
expect(el.querySelector('.flash-text').classList.contains('container-limited')).toBeTruthy();
});
});
@ -57,33 +46,23 @@ describe('Flash', () => {
it('sets transition style', () => {
hideFlash(el);
expect(
el.style['transition-property'],
).toBe('opacity');
expect(el.style['transition-property']).toBe('opacity');
expect(
el.style['transition-duration'],
).toBe('0.3s');
expect(el.style['transition-duration']).toBe('0.3s');
});
it('sets opacity style', () => {
hideFlash(el);
expect(
el.style.opacity,
).toBe('0');
expect(el.style.opacity).toBe('0');
});
it('does not set styles when fadeTransition is false', () => {
hideFlash(el, false);
expect(
el.style.opacity,
).toBe('');
expect(el.style.opacity).toBe('');
expect(
el.style.transition,
).toBe('');
expect(el.style.transition).toBe('');
});
it('removes element after transitionend', () => {
@ -92,9 +71,7 @@ describe('Flash', () => {
hideFlash(el);
el.dispatchEvent(new Event('transitionend'));
expect(
document.querySelector('.js-testing'),
).toBeNull();
expect(document.querySelector('.js-testing')).toBeNull();
});
it('calls event listener callback once', () => {
@ -106,9 +83,7 @@ describe('Flash', () => {
el.dispatchEvent(new Event('transitionend'));
el.dispatchEvent(new Event('transitionend'));
expect(
el.remove.calls.count(),
).toBe(1);
expect(el.remove.calls.count()).toBe(1);
});
});
@ -125,9 +100,7 @@ describe('Flash', () => {
title: 'test',
});
expect(
el.querySelector('.flash-action').href,
).toContain('testing');
expect(el.querySelector('.flash-action').href).toContain('testing');
});
it('uses hash as href when no href is present', () => {
@ -135,9 +108,7 @@ describe('Flash', () => {
title: 'test',
});
expect(
el.querySelector('.flash-action').href,
).toContain('#');
expect(el.querySelector('.flash-action').href).toContain('#');
});
it('adds role when no href is present', () => {
@ -145,9 +116,7 @@ describe('Flash', () => {
title: 'test',
});
expect(
el.querySelector('.flash-action').getAttribute('role'),
).toBe('button');
expect(el.querySelector('.flash-action').getAttribute('role')).toBe('button');
});
it('escapes the title text', () => {
@ -155,9 +124,9 @@ describe('Flash', () => {
title: '<script>alert("a")</script>',
});
expect(
el.querySelector('.flash-action').textContent.trim(),
).toBe('<script>alert("a")</script>');
expect(el.querySelector('.flash-action').textContent.trim()).toBe(
'<script>alert("a")</script>',
);
});
});
@ -166,13 +135,9 @@ describe('Flash', () => {
it('does not add to the DOM', () => {
const flashEl = flash('testing');
expect(
flashEl,
).toBeNull();
expect(flashEl).toBeNull();
expect(
document.querySelector('.flash-alert'),
).toBeNull();
expect(document.querySelector('.flash-alert')).toBeNull();
});
});
@ -192,42 +157,30 @@ describe('Flash', () => {
it('adds flash element into container', () => {
flash('test', 'alert', document, null, false, true);
expect(
document.querySelector('.flash-alert'),
).not.toBeNull();
expect(document.querySelector('.flash-alert')).not.toBeNull();
expect(
document.body.className,
).toContain('flash-shown');
expect(document.body.className).toContain('flash-shown');
});
it('adds flash into specified parent', () => {
flash(
'test',
'alert',
document.querySelector('.content-wrapper'),
);
flash('test', 'alert', document.querySelector('.content-wrapper'));
expect(
document.querySelector('.content-wrapper .flash-alert'),
).not.toBeNull();
expect(document.querySelector('.content-wrapper .flash-alert')).not.toBeNull();
});
it('adds container classes when inside content-wrapper', () => {
flash('test');
expect(
document.querySelector('.flash-text').className,
).toBe('flash-text container-fluid container-limited');
expect(document.querySelector('.flash-text').className).toBe(
'flash-text container-fluid container-limited',
);
});
it('does not add container when outside of content-wrapper', () => {
document.querySelector('.content-wrapper').className = 'js-content-wrapper';
flash('test');
expect(
document.querySelector('.flash-text').className.trim(),
).toBe('flash-text');
expect(document.querySelector('.flash-text').className.trim()).toBe('flash-text');
});
it('removes element after clicking', () => {
@ -235,29 +188,18 @@ describe('Flash', () => {
document.querySelector('.flash-alert').click();
expect(
document.querySelector('.flash-alert'),
).toBeNull();
expect(document.querySelector('.flash-alert')).toBeNull();
expect(
document.body.className,
).not.toContain('flash-shown');
expect(document.body.className).not.toContain('flash-shown');
});
describe('with actionConfig', () => {
it('adds action link', () => {
flash(
'test',
'alert',
document,
{
title: 'test',
},
);
flash('test', 'alert', document, {
title: 'test',
});
expect(
document.querySelector('.flash-action'),
).not.toBeNull();
expect(document.querySelector('.flash-action')).not.toBeNull();
});
it('calls actionConfig clickHandler on click', () => {
@ -266,18 +208,11 @@ describe('Flash', () => {
clickHandler: jasmine.createSpy('actionConfig'),
};
flash(
'test',
'alert',
document,
actionConfig,
);
flash('test', 'alert', document, actionConfig);
document.querySelector('.flash-action').click();
expect(
actionConfig.clickHandler,
).toHaveBeenCalled();
expect(actionConfig.clickHandler).toHaveBeenCalled();
});
});
});
@ -288,7 +223,7 @@ describe('Flash', () => {
document.body.innerHTML += '<div class="flash-container"><div class="flash"></div></div>';
});
it('removes global flash on click', (done) => {
it('removes global flash on click', done => {
const flashEl = document.querySelector('.flash');
removeFlashClickListener(flashEl, false);

View File

@ -45,9 +45,7 @@ describe('Fly out sidebar navigation', () => {
height: 100,
};
expect(
calculateTop(boundingRect, 100),
).toBe(100);
expect(calculateTop(boundingRect, 100)).toBe(100);
});
it('returns boundingRect - bottomOverflow', () => {
@ -56,27 +54,22 @@ describe('Fly out sidebar navigation', () => {
height: 100,
};
expect(
calculateTop(boundingRect, 100),
).toBe(window.innerHeight - 50);
expect(calculateTop(boundingRect, 100)).toBe(window.innerHeight - 50);
});
});
describe('getHideSubItemsInterval', () => {
beforeEach(() => {
el.innerHTML = '<div class="sidebar-sub-level-items" style="position: fixed; top: 0; left: 100px; height: 150px;"></div>';
el.innerHTML =
'<div class="sidebar-sub-level-items" style="position: fixed; top: 0; left: 100px; height: 150px;"></div>';
});
it('returns 0 if currentOpenMenu is nil', () => {
expect(
getHideSubItemsInterval(),
).toBe(0);
expect(getHideSubItemsInterval()).toBe(0);
});
it('returns 0 if mousePos is empty', () => {
expect(
getHideSubItemsInterval(),
).toBe(0);
expect(getHideSubItemsInterval()).toBe(0);
});
it('returns 0 when mouse above sub-items', () => {
@ -90,9 +83,7 @@ describe('Fly out sidebar navigation', () => {
clientY: el.getBoundingClientRect().top - 50,
});
expect(
getHideSubItemsInterval(),
).toBe(0);
expect(getHideSubItemsInterval()).toBe(0);
});
it('returns 0 when mouse is below sub-items', () => {
@ -105,12 +96,10 @@ describe('Fly out sidebar navigation', () => {
});
documentMouseMove({
clientX: el.getBoundingClientRect().left,
clientY: (el.getBoundingClientRect().top - subItems.getBoundingClientRect().height) + 50,
clientY: el.getBoundingClientRect().top - subItems.getBoundingClientRect().height + 50,
});
expect(
getHideSubItemsInterval(),
).toBe(0);
expect(getHideSubItemsInterval()).toBe(0);
});
it('returns 300 when mouse is moved towards sub-items', () => {
@ -124,9 +113,7 @@ describe('Fly out sidebar navigation', () => {
clientY: el.getBoundingClientRect().top + 10,
});
expect(
getHideSubItemsInterval(),
).toBe(300);
expect(getHideSubItemsInterval()).toBe(300);
});
});
@ -138,9 +125,7 @@ describe('Fly out sidebar navigation', () => {
it('removes is-over class if currentOpenMenu is null', () => {
mouseLeaveTopItem(el);
expect(
el.classList.remove,
).toHaveBeenCalledWith('is-over');
expect(el.classList.remove).toHaveBeenCalledWith('is-over');
});
it('removes is-over class if currentOpenMenu is null & there are sub-items', () => {
@ -148,9 +133,7 @@ describe('Fly out sidebar navigation', () => {
mouseLeaveTopItem(el);
expect(
el.classList.remove,
).toHaveBeenCalledWith('is-over');
expect(el.classList.remove).toHaveBeenCalledWith('is-over');
});
it('does not remove is-over class if currentOpenMenu is the passed in sub-items', () => {
@ -159,34 +142,29 @@ describe('Fly out sidebar navigation', () => {
setOpenMenu(el.querySelector('.sidebar-sub-level-items'));
mouseLeaveTopItem(el);
expect(
el.classList.remove,
).not.toHaveBeenCalled();
expect(el.classList.remove).not.toHaveBeenCalled();
});
});
describe('mouseEnterTopItems', () => {
beforeEach(() => {
el.innerHTML = '<div class="sidebar-sub-level-items" style="position: absolute; top: 0; left: 100px; height: 200px;"></div>';
el.innerHTML =
'<div class="sidebar-sub-level-items" style="position: absolute; top: 0; left: 100px; height: 200px;"></div>';
});
it('shows sub-items after 0ms if no menu is open', (done) => {
it('shows sub-items after 0ms if no menu is open', done => {
mouseEnterTopItems(el);
expect(
getHideSubItemsInterval(),
).toBe(0);
expect(getHideSubItemsInterval()).toBe(0);
setTimeout(() => {
expect(
el.querySelector('.sidebar-sub-level-items').style.display,
).toBe('block');
expect(el.querySelector('.sidebar-sub-level-items').style.display).toBe('block');
done();
});
});
it('shows sub-items after 300ms if a menu is currently open', (done) => {
it('shows sub-items after 300ms if a menu is currently open', done => {
documentMouseMove({
clientX: el.getBoundingClientRect().left,
clientY: el.getBoundingClientRect().top,
@ -201,14 +179,10 @@ describe('Fly out sidebar navigation', () => {
mouseEnterTopItems(el, 0);
expect(
getHideSubItemsInterval(),
).toBe(300);
expect(getHideSubItemsInterval()).toBe(300);
setTimeout(() => {
expect(
el.querySelector('.sidebar-sub-level-items').style.display,
).toBe('block');
expect(el.querySelector('.sidebar-sub-level-items').style.display).toBe('block');
done();
});
@ -225,9 +199,7 @@ describe('Fly out sidebar navigation', () => {
showSubLevelItems(el);
expect(
el.classList.add,
).toHaveBeenCalledWith('is-over');
expect(el.classList.add).toHaveBeenCalledWith('is-over');
});
it('does not show sub-items on mobile', () => {
@ -235,17 +207,13 @@ describe('Fly out sidebar navigation', () => {
showSubLevelItems(el);
expect(
el.querySelector('.sidebar-sub-level-items').style.display,
).not.toBe('block');
expect(el.querySelector('.sidebar-sub-level-items').style.display).not.toBe('block');
});
it('shows sub-items', () => {
showSubLevelItems(el);
expect(
el.querySelector('.sidebar-sub-level-items').style.display,
).toBe('block');
expect(el.querySelector('.sidebar-sub-level-items').style.display).toBe('block');
});
it('shows collapsed only sub-items if icon only sidebar', () => {
@ -258,9 +226,7 @@ describe('Fly out sidebar navigation', () => {
showSubLevelItems(el);
expect(
el.querySelector('.sidebar-sub-level-items').style.display,
).toBe('block');
expect(el.querySelector('.sidebar-sub-level-items').style.display).toBe('block');
});
it('does not show collapsed only sub-items if icon only sidebar', () => {
@ -269,9 +235,7 @@ describe('Fly out sidebar navigation', () => {
showSubLevelItems(el);
expect(
subItems.style.display,
).not.toBe('block');
expect(subItems.style.display).not.toBe('block');
});
it('sets transform of sub-items', () => {
@ -285,9 +249,10 @@ describe('Fly out sidebar navigation', () => {
setSidebar(sidebar);
showSubLevelItems(el);
expect(
subItems.style.transform,
).toBe(`translate3d(200px, ${Math.floor(el.getBoundingClientRect().top) - getHeaderHeight()}px, 0px)`);
expect(subItems.style.transform).toBe(
`translate3d(200px, ${Math.floor(el.getBoundingClientRect().top) -
getHeaderHeight()}px, 0px)`,
);
});
it('sets is-above when element is above', () => {
@ -299,33 +264,25 @@ describe('Fly out sidebar navigation', () => {
showSubLevelItems(el);
expect(
subItems.classList.add,
).toHaveBeenCalledWith('is-above');
expect(subItems.classList.add).toHaveBeenCalledWith('is-above');
});
});
describe('canShowSubItems', () => {
it('returns true if on desktop size', () => {
expect(
canShowSubItems(),
).toBeTruthy();
expect(canShowSubItems()).toBeTruthy();
});
it('returns false if on mobile size', () => {
breakpointSize = 'xs';
expect(
canShowSubItems(),
).toBeFalsy();
expect(canShowSubItems()).toBeFalsy();
});
});
describe('canShowActiveSubItems', () => {
it('returns true by default', () => {
expect(
canShowActiveSubItems(el),
).toBeTruthy();
expect(canShowActiveSubItems(el)).toBeTruthy();
});
it('returns false when active & expanded sidebar', () => {
@ -334,9 +291,7 @@ describe('Fly out sidebar navigation', () => {
setSidebar(sidebar);
expect(
canShowActiveSubItems(el),
).toBeFalsy();
expect(canShowActiveSubItems(el)).toBeFalsy();
});
it('returns true when active & collapsed sidebar', () => {
@ -346,9 +301,7 @@ describe('Fly out sidebar navigation', () => {
setSidebar(sidebar);
expect(
canShowActiveSubItems(el),
).toBeTruthy();
expect(canShowActiveSubItems(el)).toBeTruthy();
});
});
@ -362,18 +315,14 @@ describe('Fly out sidebar navigation', () => {
it('hides subMenu if element is not hovered', () => {
subItemsMouseLeave(el);
expect(
getOpenMenu(),
).toBeNull();
expect(getOpenMenu()).toBeNull();
});
it('does not hide subMenu if element is hovered', () => {
el.classList.add('is-over');
subItemsMouseLeave(el);
expect(
getOpenMenu(),
).not.toBeNull();
expect(getOpenMenu()).not.toBeNull();
});
});
});

View File

@ -232,8 +232,7 @@ describe('Frequent Items App Component', () => {
expect(vm.$el.querySelectorAll('.frequent-items-list-container li').length).toBe(1);
vm.$store.dispatch('setSearchQuery', 'gitlab');
vm
.$nextTick()
vm.$nextTick()
.then(() => {
expect(vm.$el.querySelector('.loading-animation')).toBeDefined();
})

View File

@ -6,39 +6,38 @@ import GfmAutoComplete from '~/gfm_auto_complete';
import 'vendor/jquery.caret';
import 'vendor/jquery.atwho';
describe('GfmAutoComplete', function () {
describe('GfmAutoComplete', function() {
const gfmAutoCompleteCallbacks = GfmAutoComplete.prototype.getDefaultCallbacks.call({
fetchData: () => {},
});
describe('DefaultOptions.sorter', function () {
describe('assets loading', function () {
beforeEach(function () {
describe('DefaultOptions.sorter', function() {
describe('assets loading', function() {
beforeEach(function() {
spyOn(GfmAutoComplete, 'isLoading').and.returnValue(true);
this.atwhoInstance = { setting: {} };
this.items = [];
this.sorterValue = gfmAutoCompleteCallbacks.sorter
.call(this.atwhoInstance, '', this.items);
this.sorterValue = gfmAutoCompleteCallbacks.sorter.call(this.atwhoInstance, '', this.items);
});
it('should disable highlightFirst', function () {
it('should disable highlightFirst', function() {
expect(this.atwhoInstance.setting.highlightFirst).toBe(false);
});
it('should return the passed unfiltered items', function () {
it('should return the passed unfiltered items', function() {
expect(this.sorterValue).toEqual(this.items);
});
});
describe('assets finished loading', function () {
beforeEach(function () {
describe('assets finished loading', function() {
beforeEach(function() {
spyOn(GfmAutoComplete, 'isLoading').and.returnValue(false);
spyOn($.fn.atwho.default.callbacks, 'sorter');
});
it('should enable highlightFirst if alwaysHighlightFirst is set', function () {
it('should enable highlightFirst if alwaysHighlightFirst is set', function() {
const atwhoInstance = { setting: { alwaysHighlightFirst: true } };
gfmAutoCompleteCallbacks.sorter.call(atwhoInstance);
@ -46,7 +45,7 @@ describe('GfmAutoComplete', function () {
expect(atwhoInstance.setting.highlightFirst).toBe(true);
});
it('should enable highlightFirst if a query is present', function () {
it('should enable highlightFirst if a query is present', function() {
const atwhoInstance = { setting: {} };
gfmAutoCompleteCallbacks.sorter.call(atwhoInstance, 'query');
@ -54,7 +53,7 @@ describe('GfmAutoComplete', function () {
expect(atwhoInstance.setting.highlightFirst).toBe(true);
});
it('should call the default atwho sorter', function () {
it('should call the default atwho sorter', function() {
const atwhoInstance = { setting: {} };
const query = 'query';
@ -69,9 +68,8 @@ describe('GfmAutoComplete', function () {
});
describe('DefaultOptions.beforeInsert', () => {
const beforeInsert = (context, value) => (
gfmAutoCompleteCallbacks.beforeInsert.call(context, value)
);
const beforeInsert = (context, value) =>
gfmAutoCompleteCallbacks.beforeInsert.call(context, value);
const atwhoInstance = { setting: { skipSpecialCharacterTest: false } };
@ -98,29 +96,51 @@ describe('GfmAutoComplete', function () {
});
});
describe('DefaultOptions.matcher', function () {
const defaultMatcher = (context, flag, subtext) => (
gfmAutoCompleteCallbacks.matcher.call(context, flag, subtext)
);
describe('DefaultOptions.matcher', function() {
const defaultMatcher = (context, flag, subtext) =>
gfmAutoCompleteCallbacks.matcher.call(context, flag, subtext);
const flagsUseDefaultMatcher = ['@', '#', '!', '~', '%', '$'];
const otherFlags = ['/', ':'];
const flags = flagsUseDefaultMatcher.concat(otherFlags);
const flagsHash = flags.reduce((hash, el) => { hash[el] = null; return hash; }, {});
const flagsHash = flags.reduce((hash, el) => {
hash[el] = null;
return hash;
}, {});
const atwhoInstance = { setting: {}, app: { controllers: flagsHash } };
const minLen = 1;
const maxLen = 20;
const argumentSize = [minLen, maxLen / 2, maxLen];
const allowedSymbols = ['', 'a', 'n', 'z', 'A', 'Z', 'N', '0', '5', '9', 'А', 'а', 'Я', 'я', '.', '\'', '+', '-', '_'];
const allowedSymbols = [
'',
'a',
'n',
'z',
'A',
'Z',
'N',
'0',
'5',
'9',
'А',
'а',
'Я',
'я',
'.',
"'",
'+',
'-',
'_',
];
const jointAllowedSymbols = allowedSymbols.join('');
describe('should match regular symbols', () => {
flagsUseDefaultMatcher.forEach((flag) => {
allowedSymbols.forEach((symbol) => {
argumentSize.forEach((size) => {
flagsUseDefaultMatcher.forEach(flag => {
allowedSymbols.forEach(symbol => {
argumentSize.forEach(size => {
const query = new Array(size + 1).join(symbol);
const subtext = flag + query;
@ -142,8 +162,8 @@ describe('GfmAutoComplete', function () {
const shouldNotBeFollowedBy = flags.concat(['\x00', '\x10', '\x3f', '\n', ' ']);
const shouldNotBePrependedBy = ['`'];
flagsUseDefaultMatcher.forEach((atSign) => {
shouldNotBeFollowedBy.forEach((followedSymbol) => {
flagsUseDefaultMatcher.forEach(atSign => {
shouldNotBeFollowedBy.forEach(followedSymbol => {
const seq = atSign + followedSymbol;
it(`should not match ${JSON.stringify(seq)}`, () => {
@ -151,7 +171,7 @@ describe('GfmAutoComplete', function () {
});
});
shouldNotBePrependedBy.forEach((prependedSymbol) => {
shouldNotBePrependedBy.forEach(prependedSymbol => {
const seq = prependedSymbol + atSign;
it(`should not match "${seq}"`, () => {
@ -162,28 +182,26 @@ describe('GfmAutoComplete', function () {
});
});
describe('isLoading', function () {
it('should be true with loading data object item', function () {
describe('isLoading', function() {
it('should be true with loading data object item', function() {
expect(GfmAutoComplete.isLoading({ name: 'loading' })).toBe(true);
});
it('should be true with loading data array', function () {
it('should be true with loading data array', function() {
expect(GfmAutoComplete.isLoading(['loading'])).toBe(true);
});
it('should be true with loading data object array', function () {
it('should be true with loading data object array', function() {
expect(GfmAutoComplete.isLoading([{ name: 'loading' }])).toBe(true);
});
it('should be false with actual array data', function () {
expect(GfmAutoComplete.isLoading([
{ title: 'Foo' },
{ title: 'Bar' },
{ title: 'Qux' },
])).toBe(false);
it('should be false with actual array data', function() {
expect(
GfmAutoComplete.isLoading([{ title: 'Foo' }, { title: 'Bar' }, { title: 'Qux' }]),
).toBe(false);
});
it('should be false with actual data item', function () {
it('should be false with actual data item', function() {
expect(GfmAutoComplete.isLoading({ title: 'Foo' })).toBe(false);
});
});

View File

@ -8,7 +8,8 @@ describe('glDropdown', function describeDropdown() {
preloadFixtures('static/gl_dropdown.html.raw');
loadJSONFixtures('projects.json');
const NON_SELECTABLE_CLASSES = '.divider, .separator, .dropdown-header, .dropdown-menu-empty-item';
const NON_SELECTABLE_CLASSES =
'.divider, .separator, .dropdown-header, .dropdown-menu-empty-item';
const SEARCH_INPUT_SELECTOR = '.dropdown-input-field';
const ITEM_SELECTOR = `.dropdown-content li:not(${NON_SELECTABLE_CLASSES})`;
const FOCUSED_ITEM_SELECTOR = `${ITEM_SELECTOR} a.is-focused`;
@ -17,7 +18,7 @@ describe('glDropdown', function describeDropdown() {
DOWN: 40,
UP: 38,
ENTER: 13,
ESC: 27
ESC: 27,
};
let remoteCallback;
@ -28,7 +29,7 @@ describe('glDropdown', function describeDropdown() {
$('body').trigger({
type: 'keydown',
which: ARROW_KEYS[direction],
keyCode: ARROW_KEYS[direction]
keyCode: ARROW_KEYS[direction],
});
i += 1;
if (i <= steps) {
@ -43,17 +44,23 @@ describe('glDropdown', function describeDropdown() {
};
function initDropDown(hasRemote, isFilterable, extraOpts = {}) {
const options = Object.assign({
selectable: true,
filterable: isFilterable,
data: hasRemote ? remoteMock.bind({}, this.projectsData) : this.projectsData,
search: {
fields: ['name']
const options = Object.assign(
{
selectable: true,
filterable: isFilterable,
data: hasRemote ? remoteMock.bind({}, this.projectsData) : this.projectsData,
search: {
fields: ['name'],
},
text: project => project.name_with_namespace || project.name,
id: project => project.id,
},
text: project => (project.name_with_namespace || project.name),
id: project => project.id,
}, extraOpts);
this.dropdownButtonElement = $('#js-project-dropdown', this.dropdownContainerElement).glDropdown(options);
extraOpts,
);
this.dropdownButtonElement = $(
'#js-project-dropdown',
this.dropdownContainerElement,
).glDropdown(options);
}
beforeEach(() => {
@ -84,9 +91,7 @@ describe('glDropdown', function describeDropdown() {
this.dropdownButtonElement.click();
expect(
$('.dropdown-content li:first-child').text(),
).toBe('<script>alert("testing");</script>');
expect($('.dropdown-content li:first-child').text()).toBe('<script>alert("testing");</script>');
});
it('should output HTML when highlighting', () => {
@ -99,13 +104,11 @@ describe('glDropdown', function describeDropdown() {
this.dropdownButtonElement.click();
expect(
$('.dropdown-content li:first-child').text(),
).toBe('testing');
expect($('.dropdown-content li:first-child').text()).toBe('testing');
expect(
$('.dropdown-content li:first-child a').html(),
).toBe('<b>t</b><b>e</b><b>s</b><b>t</b>ing');
expect($('.dropdown-content li:first-child a').html()).toBe(
'<b>t</b><b>e</b><b>s</b><b>t</b>ing',
);
});
describe('that is open', () => {
@ -116,21 +119,28 @@ describe('glDropdown', function describeDropdown() {
it('should select a following item on DOWN keypress', () => {
expect($(FOCUSED_ITEM_SELECTOR, this.$dropdownMenuElement).length).toBe(0);
const randomIndex = (Math.floor(Math.random() * (this.projectsData.length - 1)) + 0);
const randomIndex = Math.floor(Math.random() * (this.projectsData.length - 1)) + 0;
navigateWithKeys('down', randomIndex, () => {
expect($(FOCUSED_ITEM_SELECTOR, this.$dropdownMenuElement).length).toBe(1);
expect($(`${ITEM_SELECTOR}:eq(${randomIndex}) a`, this.$dropdownMenuElement)).toHaveClass('is-focused');
expect($(`${ITEM_SELECTOR}:eq(${randomIndex}) a`, this.$dropdownMenuElement)).toHaveClass(
'is-focused',
);
});
});
it('should select a previous item on UP keypress', () => {
expect($(FOCUSED_ITEM_SELECTOR, this.$dropdownMenuElement).length).toBe(0);
navigateWithKeys('down', (this.projectsData.length - 1), () => {
navigateWithKeys('down', this.projectsData.length - 1, () => {
expect($(FOCUSED_ITEM_SELECTOR, this.$dropdownMenuElement).length).toBe(1);
const randomIndex = (Math.floor(Math.random() * (this.projectsData.length - 2)) + 0);
const randomIndex = Math.floor(Math.random() * (this.projectsData.length - 2)) + 0;
navigateWithKeys('up', randomIndex, () => {
expect($(FOCUSED_ITEM_SELECTOR, this.$dropdownMenuElement).length).toBe(1);
expect($(`${ITEM_SELECTOR}:eq(${((this.projectsData.length - 2) - randomIndex)}) a`, this.$dropdownMenuElement)).toHaveClass('is-focused');
expect(
$(
`${ITEM_SELECTOR}:eq(${this.projectsData.length - 2 - randomIndex}) a`,
this.$dropdownMenuElement,
),
).toHaveClass('is-focused');
});
});
});
@ -147,7 +157,7 @@ describe('glDropdown', function describeDropdown() {
expect(link).toHaveClass('is-active');
const linkedLocation = link.attr('href');
if (linkedLocation && linkedLocation !== '#') {
expect(visitUrl).toHaveBeenCalledWith(linkedLocation);
expect(visitUrl).toHaveBeenCalledWith(linkedLocation);
}
});
});
@ -158,7 +168,7 @@ describe('glDropdown', function describeDropdown() {
this.dropdownContainerElement.trigger({
type: 'keyup',
which: ARROW_KEYS.ESC,
keyCode: ARROW_KEYS.ESC
keyCode: ARROW_KEYS.ESC,
});
expect(this.dropdownContainerElement).not.toHaveClass('show');
@ -198,7 +208,7 @@ describe('glDropdown', function describeDropdown() {
this.dropdownContainerElement.trigger({
type: 'keyup',
which: ARROW_KEYS.ESC,
keyCode: ARROW_KEYS.ESC
keyCode: ARROW_KEYS.ESC,
});
this.dropdownButtonElement.click();
this.dropdownContainerElement.trigger('transitionend');
@ -227,9 +237,7 @@ describe('glDropdown', function describeDropdown() {
expect($searchInput.val()).toEqual('g');
this.dropdownButtonElement.trigger('hidden.bs.dropdown');
$searchInput
.trigger('blur')
.trigger('focus');
$searchInput.trigger('blur').trigger('focus');
expect($searchInput.val()).toEqual('g');
});
@ -239,16 +247,14 @@ describe('glDropdown', function describeDropdown() {
let dropdown;
beforeEach(() => {
const dropdownOptions = {
};
const dropdownOptions = {};
const $dropdownDiv = $('<div />');
$dropdownDiv.glDropdown(dropdownOptions);
dropdown = $dropdownDiv.data('glDropdown');
});
it('marks items without ID as active', () => {
const dummyData = { };
const dummyData = {};
const html = dropdown.renderItem(dummyData, null, null);
@ -259,7 +265,7 @@ describe('glDropdown', function describeDropdown() {
it('does not mark items with ID as active', () => {
const dummyData = {
id: 'ea'
id: 'ea',
};
const html = dropdown.renderItem(dummyData, null, null);
@ -297,4 +303,3 @@ describe('glDropdown', function describeDropdown() {
expect($('.dropdown-toggle-text')).toHaveText(this.projectsData[0].id.toString());
});
});

View File

@ -29,7 +29,7 @@ describe('GL Style Field Errors', function() {
expect(customErrorElem.length).toBe(1);
const customErrors = this.fieldErrors.state.inputs.filter((input) => {
const customErrors = this.fieldErrors.state.inputs.filter(input => {
return input.inputElement.hasClass(customErrorFlag);
});
@ -37,9 +37,18 @@ describe('GL Style Field Errors', function() {
});
it('should not show any errors before submit attempt', function() {
this.$form.find('.email').val('not-a-valid-email').keyup();
this.$form.find('.text-required').val('').keyup();
this.$form.find('.alphanumberic').val('?---*').keyup();
this.$form
.find('.email')
.val('not-a-valid-email')
.keyup();
this.$form
.find('.text-required')
.val('')
.keyup();
this.$form
.find('.alphanumberic')
.val('?---*')
.keyup();
const errorsShown = this.$form.find('.gl-field-error-outline');
@ -47,9 +56,18 @@ describe('GL Style Field Errors', function() {
});
it('should show errors when input valid is submitted', function() {
this.$form.find('.email').val('not-a-valid-email').keyup();
this.$form.find('.text-required').val('').keyup();
this.$form.find('.alphanumberic').val('?---*').keyup();
this.$form
.find('.email')
.val('not-a-valid-email')
.keyup();
this.$form
.find('.text-required')
.val('')
.keyup();
this.$form
.find('.alphanumberic')
.val('?---*')
.keyup();
this.$form.submit();

View File

@ -5,8 +5,8 @@ import '~/lib/utils/text_utility';
import '~/lib/utils/common_utils';
describe('GLForm', () => {
describe('when instantiated', function () {
beforeEach((done) => {
describe('when instantiated', function() {
beforeEach(done => {
this.form = $('<form class="gfm-form"><textarea class="js-gfm-input"></form>');
this.textarea = this.form.find('textarea');
spyOn($.prototype, 'off').and.returnValue(this.textarea);
@ -23,7 +23,7 @@ describe('GLForm', () => {
});
describe('setupAutosize', () => {
beforeEach((done) => {
beforeEach(done => {
this.glForm.setupAutosize();
setTimeout(() => {
done();

View File

@ -2,47 +2,50 @@
import { scaleLinear, scaleTime } from 'd3-scale';
import { timeParse } from 'd3-time-format';
import { ContributorsGraph, ContributorsMasterGraph } from '~/pages/projects/graphs/show/stat_graph_contributors_graph';
import {
ContributorsGraph,
ContributorsMasterGraph,
} from '~/pages/projects/graphs/show/stat_graph_contributors_graph';
const d3 = { scaleLinear, scaleTime, timeParse };
describe("ContributorsGraph", function () {
describe("#set_x_domain", function () {
it("set the x_domain", function () {
describe('ContributorsGraph', function() {
describe('#set_x_domain', function() {
it('set the x_domain', function() {
ContributorsGraph.set_x_domain(20);
expect(ContributorsGraph.prototype.x_domain).toEqual(20);
});
});
describe("#set_y_domain", function () {
it("sets the y_domain", function () {
describe('#set_y_domain', function() {
it('sets the y_domain', function() {
ContributorsGraph.set_y_domain([{ commits: 30 }]);
expect(ContributorsGraph.prototype.y_domain).toEqual([0, 30]);
});
});
describe("#init_x_domain", function () {
it("sets the initial x_domain", function () {
ContributorsGraph.init_x_domain([{ date: "2013-01-31" }, { date: "2012-01-31" }]);
describe('#init_x_domain', function() {
it('sets the initial x_domain', function() {
ContributorsGraph.init_x_domain([{ date: '2013-01-31' }, { date: '2012-01-31' }]);
expect(ContributorsGraph.prototype.x_domain).toEqual(["2012-01-31", "2013-01-31"]);
expect(ContributorsGraph.prototype.x_domain).toEqual(['2012-01-31', '2013-01-31']);
});
});
describe("#init_y_domain", function () {
it("sets the initial y_domain", function () {
describe('#init_y_domain', function() {
it('sets the initial y_domain', function() {
ContributorsGraph.init_y_domain([{ commits: 30 }]);
expect(ContributorsGraph.prototype.y_domain).toEqual([0, 30]);
});
});
describe("#init_domain", function () {
it("calls init_x_domain and init_y_domain", function () {
spyOn(ContributorsGraph, "init_x_domain");
spyOn(ContributorsGraph, "init_y_domain");
describe('#init_domain', function() {
it('calls init_x_domain and init_y_domain', function() {
spyOn(ContributorsGraph, 'init_x_domain');
spyOn(ContributorsGraph, 'init_y_domain');
ContributorsGraph.init_domain();
expect(ContributorsGraph.init_x_domain).toHaveBeenCalled();
@ -50,19 +53,22 @@ describe("ContributorsGraph", function () {
});
});
describe("#set_dates", function () {
it("sets the dates", function () {
ContributorsGraph.set_dates("2013-12-01");
describe('#set_dates', function() {
it('sets the dates', function() {
ContributorsGraph.set_dates('2013-12-01');
expect(ContributorsGraph.prototype.dates).toEqual("2013-12-01");
expect(ContributorsGraph.prototype.dates).toEqual('2013-12-01');
});
});
describe("#set_x_domain", function () {
it("sets the instance's x domain using the prototype's x_domain", function () {
describe('#set_x_domain', function() {
it("sets the instance's x domain using the prototype's x_domain", function() {
ContributorsGraph.prototype.x_domain = 20;
var instance = new ContributorsGraph();
instance.x = d3.scaleTime().range([0, 100]).clamp(true);
instance.x = d3
.scaleTime()
.range([0, 100])
.clamp(true);
spyOn(instance.x, 'domain');
instance.set_x_domain();
@ -70,11 +76,14 @@ describe("ContributorsGraph", function () {
});
});
describe("#set_y_domain", function () {
it("sets the instance's y domain using the prototype's y_domain", function () {
describe('#set_y_domain', function() {
it("sets the instance's y domain using the prototype's y_domain", function() {
ContributorsGraph.prototype.y_domain = 30;
var instance = new ContributorsGraph();
instance.y = d3.scaleLinear().range([100, 0]).nice();
instance.y = d3
.scaleLinear()
.range([100, 0])
.nice();
spyOn(instance.y, 'domain');
instance.set_y_domain();
@ -82,8 +91,8 @@ describe("ContributorsGraph", function () {
});
});
describe("#set_domain", function () {
it("calls set_x_domain and set_y_domain", function () {
describe('#set_domain', function() {
it('calls set_x_domain and set_y_domain', function() {
var instance = new ContributorsGraph();
spyOn(instance, 'set_x_domain');
spyOn(instance, 'set_y_domain');
@ -94,17 +103,17 @@ describe("ContributorsGraph", function () {
});
});
describe("#set_data", function () {
it("sets the data", function () {
describe('#set_data', function() {
it('sets the data', function() {
var instance = new ContributorsGraph();
instance.set_data("20");
instance.set_data('20');
expect(instance.data).toEqual("20");
expect(instance.data).toEqual('20');
});
});
});
describe("ContributorsMasterGraph", function () {
describe('ContributorsMasterGraph', function() {
// TODO: fix or remove
// describe("#process_dates", function () {
// it("gets and parses dates", function () {
@ -120,20 +129,20 @@ describe("ContributorsMasterGraph", function () {
// });
// });
describe("#get_dates", function () {
it("plucks the date field from data collection", function () {
describe('#get_dates', function() {
it('plucks the date field from data collection', function() {
var graph = new ContributorsMasterGraph();
var data = [{ date: "2013-01-01" }, { date: "2012-12-15" }];
var data = [{ date: '2013-01-01' }, { date: '2012-12-15' }];
expect(graph.get_dates(data)).toEqual(["2013-01-01", "2012-12-15"]);
expect(graph.get_dates(data)).toEqual(['2013-01-01', '2012-12-15']);
});
});
describe("#parse_dates", function () {
it("parses the dates", function () {
describe('#parse_dates', function() {
it('parses the dates', function() {
var graph = new ContributorsMasterGraph();
var parseDate = d3.timeParse("%Y-%m-%d");
var data = [{ date: "2013-01-01" }, { date: "2012-12-15" }];
var parseDate = d3.timeParse('%Y-%m-%d');
var data = [{ date: '2013-01-01' }, { date: '2012-12-15' }];
var correct = [{ date: parseDate(data[0].date) }, { date: parseDate(data[1].date) }];
graph.parse_dates(data);

View File

@ -20,7 +20,9 @@ describe('ContributorsStatGraph', () => {
graph.change_date_header();
expect(document.getElementById('date_header').innerText).toBe('31. Januar 2012 31. Januar 2013');
expect(document.getElementById('date_header').innerText).toBe(
'31. Januar 2012 31. Januar 2013',
);
});
});
});

View File

@ -2,57 +2,82 @@
import ContributorsStatGraphUtil from '~/pages/projects/graphs/show/stat_graph_contributors_util';
describe("ContributorsStatGraphUtil", function () {
describe("#parse_log", function () {
it("returns a correctly parsed log", function () {
describe('ContributorsStatGraphUtil', function() {
describe('#parse_log', function() {
it('returns a correctly parsed log', function() {
var fake_log = [
{ author_email: "karlo@email.com", author_name: "Karlo Soriano", date: "2013-05-09", additions: 471 },
{ author_email: "dzaporozhets@email.com", author_name: "Dmitriy Zaporozhets", date: "2013-05-08", additions: 6, deletions: 1 },
{ author_email: "dzaporozhets@email.com", author_name: "Dmitriy Zaporozhets", date: "2013-05-08", additions: 19, deletions: 3 },
{ author_email: "dzaporozhets@email.com", author_name: "Dmitriy Zaporozhets", date: "2013-05-08", additions: 29, deletions: 3 }
{
author_email: 'karlo@email.com',
author_name: 'Karlo Soriano',
date: '2013-05-09',
additions: 471,
},
{
author_email: 'dzaporozhets@email.com',
author_name: 'Dmitriy Zaporozhets',
date: '2013-05-08',
additions: 6,
deletions: 1,
},
{
author_email: 'dzaporozhets@email.com',
author_name: 'Dmitriy Zaporozhets',
date: '2013-05-08',
additions: 19,
deletions: 3,
},
{
author_email: 'dzaporozhets@email.com',
author_name: 'Dmitriy Zaporozhets',
date: '2013-05-08',
additions: 29,
deletions: 3,
},
];
var correct_parsed_log = {
total: [
{ date: "2013-05-09", additions: 471, deletions: 0, commits: 1 },
{ date: "2013-05-08", additions: 54, deletions: 7, commits: 3 }
{ date: '2013-05-09', additions: 471, deletions: 0, commits: 1 },
{ date: '2013-05-08', additions: 54, deletions: 7, commits: 3 },
],
by_author: [
{
author_name: "Karlo Soriano", author_email: "karlo@email.com",
"2013-05-09": { date: "2013-05-09", additions: 471, deletions: 0, commits: 1 }
author_name: 'Karlo Soriano',
author_email: 'karlo@email.com',
'2013-05-09': { date: '2013-05-09', additions: 471, deletions: 0, commits: 1 },
},
{
author_name: "Dmitriy Zaporozhets", author_email: "dzaporozhets@email.com",
"2013-05-08": { date: "2013-05-08", additions: 54, deletions: 7, commits: 3 }
}
]
author_name: 'Dmitriy Zaporozhets',
author_email: 'dzaporozhets@email.com',
'2013-05-08': { date: '2013-05-08', additions: 54, deletions: 7, commits: 3 },
},
],
};
expect(ContributorsStatGraphUtil.parse_log(fake_log)).toEqual(correct_parsed_log);
});
});
describe("#store_data", function () {
var fake_entry = { author: "Karlo Soriano", date: "2013-05-09", additions: 471 };
describe('#store_data', function() {
var fake_entry = { author: 'Karlo Soriano', date: '2013-05-09', additions: 471 };
var fake_total = {};
var fake_by_author = {};
it("calls #store_commits", function () {
it('calls #store_commits', function() {
spyOn(ContributorsStatGraphUtil, 'store_commits');
ContributorsStatGraphUtil.store_data(fake_entry, fake_total, fake_by_author);
expect(ContributorsStatGraphUtil.store_commits).toHaveBeenCalled();
});
it("calls #store_additions", function () {
it('calls #store_additions', function() {
spyOn(ContributorsStatGraphUtil, 'store_additions');
ContributorsStatGraphUtil.store_data(fake_entry, fake_total, fake_by_author);
expect(ContributorsStatGraphUtil.store_additions).toHaveBeenCalled();
});
it("calls #store_deletions", function () {
it('calls #store_deletions', function() {
spyOn(ContributorsStatGraphUtil, 'store_deletions');
ContributorsStatGraphUtil.store_data(fake_entry, fake_total, fake_by_author);
@ -72,17 +97,17 @@ describe("ContributorsStatGraphUtil", function () {
// });
// });
describe("#add", function () {
it("adds 1 to current test_field in collection", function () {
describe('#add', function() {
it('adds 1 to current test_field in collection', function() {
var fake_collection = { test_field: 10 };
ContributorsStatGraphUtil.add(fake_collection, "test_field", 1);
ContributorsStatGraphUtil.add(fake_collection, 'test_field', 1);
expect(fake_collection.test_field).toEqual(11);
});
it("inits and adds 1 if test_field in collection is not defined", function () {
it('inits and adds 1 if test_field in collection is not defined', function() {
var fake_collection = {};
ContributorsStatGraphUtil.add(fake_collection, "test_field", 1);
ContributorsStatGraphUtil.add(fake_collection, 'test_field', 1);
expect(fake_collection.test_field).toEqual(1);
});
@ -112,120 +137,160 @@ describe("ContributorsStatGraphUtil", function () {
// });
// });
describe("#add_date", function () {
it("adds a date field to the collection", function () {
var fake_date = "2013-10-02";
describe('#add_date', function() {
it('adds a date field to the collection', function() {
var fake_date = '2013-10-02';
var fake_collection = {};
ContributorsStatGraphUtil.add_date(fake_date, fake_collection);
expect(fake_collection[fake_date].date).toEqual("2013-10-02");
expect(fake_collection[fake_date].date).toEqual('2013-10-02');
});
});
describe("#add_author", function () {
it("adds an author field to the collection", function () {
var fake_author = { author_name: "Author", author_email: 'fake@email.com' };
describe('#add_author', function() {
it('adds an author field to the collection', function() {
var fake_author = { author_name: 'Author', author_email: 'fake@email.com' };
var fake_author_collection = {};
var fake_email_collection = {};
ContributorsStatGraphUtil.add_author(fake_author, fake_author_collection, fake_email_collection);
ContributorsStatGraphUtil.add_author(
fake_author,
fake_author_collection,
fake_email_collection,
);
expect(fake_author_collection[fake_author.author_name].author_name).toEqual("Author");
expect(fake_email_collection[fake_author.author_email].author_name).toEqual("Author");
expect(fake_author_collection[fake_author.author_name].author_name).toEqual('Author');
expect(fake_email_collection[fake_author.author_email].author_name).toEqual('Author');
});
});
describe("#get_total_data", function () {
it("returns the collection sorted via specified field", function () {
describe('#get_total_data', function() {
it('returns the collection sorted via specified field', function() {
var fake_parsed_log = {
total: [
{ date: "2013-05-09", additions: 471, deletions: 0, commits: 1 },
{ date: "2013-05-08", additions: 54, deletions: 7, commits: 3 }
{ date: '2013-05-09', additions: 471, deletions: 0, commits: 1 },
{ date: '2013-05-08', additions: 54, deletions: 7, commits: 3 },
],
by_author: [
{
author: "Karlo Soriano",
"2013-05-09": { date: "2013-05-09", additions: 471, deletions: 0, commits: 1 }
author: 'Karlo Soriano',
'2013-05-09': { date: '2013-05-09', additions: 471, deletions: 0, commits: 1 },
},
{
author: "Dmitriy Zaporozhets",
"2013-05-08": { date: "2013-05-08", additions: 54, deletions: 7, commits: 3 }
}
]
author: 'Dmitriy Zaporozhets',
'2013-05-08': { date: '2013-05-08', additions: 54, deletions: 7, commits: 3 },
},
],
};
var correct_total_data = [
{ date: "2013-05-08", commits: 3 },
{ date: "2013-05-09", commits: 1 }
{ date: '2013-05-08', commits: 3 },
{ date: '2013-05-09', commits: 1 },
];
expect(ContributorsStatGraphUtil.get_total_data(fake_parsed_log, "commits")).toEqual(correct_total_data);
expect(ContributorsStatGraphUtil.get_total_data(fake_parsed_log, 'commits')).toEqual(
correct_total_data,
);
});
});
describe("#pick_field", function () {
it("returns the collection with only the specified field and date", function () {
describe('#pick_field', function() {
it('returns the collection with only the specified field and date', function() {
var fake_parsed_log_total = [
{ date: "2013-05-09", additions: 471, deletions: 0, commits: 1 },
{ date: "2013-05-08", additions: 54, deletions: 7, commits: 3 }
{ date: '2013-05-09', additions: 471, deletions: 0, commits: 1 },
{ date: '2013-05-08', additions: 54, deletions: 7, commits: 3 },
];
ContributorsStatGraphUtil.pick_field(fake_parsed_log_total, 'commits');
var correct_pick_field_data = [
{ date: '2013-05-09', commits: 1 },
{ date: '2013-05-08', commits: 3 },
];
ContributorsStatGraphUtil.pick_field(fake_parsed_log_total, "commits");
var correct_pick_field_data = [{ date: "2013-05-09", commits: 1 }, { date: "2013-05-08", commits: 3 }];
expect(ContributorsStatGraphUtil.pick_field(fake_parsed_log_total, "commits")).toEqual(correct_pick_field_data);
expect(ContributorsStatGraphUtil.pick_field(fake_parsed_log_total, 'commits')).toEqual(
correct_pick_field_data,
);
});
});
describe("#get_author_data", function () {
it("returns the log by author sorted by specified field", function () {
describe('#get_author_data', function() {
it('returns the log by author sorted by specified field', function() {
var fake_parsed_log = {
total: [
{ date: "2013-05-09", additions: 471, deletions: 0, commits: 1 },
{ date: "2013-05-08", additions: 54, deletions: 7, commits: 3 }
{ date: '2013-05-09', additions: 471, deletions: 0, commits: 1 },
{ date: '2013-05-08', additions: 54, deletions: 7, commits: 3 },
],
by_author: [
{
author_name: "Karlo Soriano", author_email: "karlo@email.com",
"2013-05-09": { date: "2013-05-09", additions: 471, deletions: 0, commits: 1 }
author_name: 'Karlo Soriano',
author_email: 'karlo@email.com',
'2013-05-09': { date: '2013-05-09', additions: 471, deletions: 0, commits: 1 },
},
{
author_name: "Dmitriy Zaporozhets", author_email: "dzaporozhets@email.com",
"2013-05-08": { date: "2013-05-08", additions: 54, deletions: 7, commits: 3 }
}
]
author_name: 'Dmitriy Zaporozhets',
author_email: 'dzaporozhets@email.com',
'2013-05-08': { date: '2013-05-08', additions: 54, deletions: 7, commits: 3 },
},
],
};
var correct_author_data = [
{ author_name: "Dmitriy Zaporozhets", author_email: "dzaporozhets@email.com", dates: { "2013-05-08": 3 }, deletions: 7, additions: 54, "commits": 3 },
{ author_name: "Karlo Soriano", author_email: "karlo@email.com", dates: { "2013-05-09": 1 }, deletions: 0, additions: 471, commits: 1 }
{
author_name: 'Dmitriy Zaporozhets',
author_email: 'dzaporozhets@email.com',
dates: { '2013-05-08': 3 },
deletions: 7,
additions: 54,
commits: 3,
},
{
author_name: 'Karlo Soriano',
author_email: 'karlo@email.com',
dates: { '2013-05-09': 1 },
deletions: 0,
additions: 471,
commits: 1,
},
];
expect(ContributorsStatGraphUtil.get_author_data(fake_parsed_log, "commits")).toEqual(correct_author_data);
expect(ContributorsStatGraphUtil.get_author_data(fake_parsed_log, 'commits')).toEqual(
correct_author_data,
);
});
});
describe("#parse_log_entry", function () {
it("adds the corresponding info from the log entry to the author", function () {
var fake_log_entry = { author_name: "Karlo Soriano", author_email: "karlo@email.com",
"2013-05-09": { date: "2013-05-09", additions: 471, deletions: 0, commits: 1 }
describe('#parse_log_entry', function() {
it('adds the corresponding info from the log entry to the author', function() {
var fake_log_entry = {
author_name: 'Karlo Soriano',
author_email: 'karlo@email.com',
'2013-05-09': { date: '2013-05-09', additions: 471, deletions: 0, commits: 1 },
};
var correct_parsed_log = {
author_name: 'Karlo Soriano',
author_email: 'karlo@email.com',
dates: { '2013-05-09': 1 },
deletions: 0,
additions: 471,
commits: 1,
};
var correct_parsed_log = { author_name: "Karlo Soriano", author_email: "karlo@email.com", dates: { "2013-05-09": 1 }, deletions: 0, additions: 471, commits: 1 };
expect(ContributorsStatGraphUtil.parse_log_entry(fake_log_entry, 'commits', null)).toEqual(correct_parsed_log);
expect(ContributorsStatGraphUtil.parse_log_entry(fake_log_entry, 'commits', null)).toEqual(
correct_parsed_log,
);
});
});
describe("#in_range", function () {
var date = "2013-05-09";
it("returns true if date_range is null", function () {
describe('#in_range', function() {
var date = '2013-05-09';
it('returns true if date_range is null', function() {
expect(ContributorsStatGraphUtil.in_range(date, null)).toEqual(true);
});
it("returns true if date is in range", function () {
var date_range = [new Date("2013-01-01"), new Date("2013-12-12")];
it('returns true if date is in range', function() {
var date_range = [new Date('2013-01-01'), new Date('2013-12-12')];
expect(ContributorsStatGraphUtil.in_range(date, date_range)).toEqual(true);
});
it("returns false if date is not in range", function () {
var date_range = [new Date("1999-12-01"), new Date("2000-12-01")];
it('returns false if date is not in range', function() {
var date_range = [new Date('1999-12-01'), new Date('2000-12-01')];
expect(ContributorsStatGraphUtil.in_range(date, date_range)).toEqual(false);
});

View File

@ -18,7 +18,7 @@ const createComponent = (groups = mockGroups, parentGroup = mockParentGroupItem)
describe('GroupFolderComponent', () => {
let vm;
beforeEach((done) => {
beforeEach(done => {
Vue.component('group-item', groupItemComponent);
vm = createComponent();

View File

@ -17,7 +17,7 @@ const createComponent = (group = mockParentGroupItem, parentGroup = mockChildren
describe('GroupItemComponent', () => {
let vm;
beforeEach((done) => {
beforeEach(done => {
Vue.component('group-folder', groupFolderComponent);
vm = createComponent();
@ -44,7 +44,7 @@ describe('GroupItemComponent', () => {
const { rowClass } = vm;
expect(Object.keys(rowClass).length).toBe(classes.length);
Object.keys(rowClass).forEach((className) => {
Object.keys(rowClass).forEach(className => {
expect(classes.indexOf(className)).toBeGreaterThan(-1);
});
});
@ -137,7 +137,7 @@ describe('GroupItemComponent', () => {
expect(eventHub.$emit).toHaveBeenCalledWith('toggleChildren', vm.group);
});
it('should navigate page to group homepage if group does not have any children present', (done) => {
it('should navigate page to group homepage if group does not have any children present', done => {
const group = Object.assign({}, mockParentGroupItem);
group.childrenCount = 0;
const newVm = createComponent(group);

View File

@ -21,7 +21,7 @@ const createComponent = (searchEmpty = false) => {
describe('GroupsComponent', () => {
let vm;
beforeEach((done) => {
beforeEach(done => {
Vue.component('group-folder', groupFolderComponent);
Vue.component('group-item', groupItemComponent);
@ -43,13 +43,19 @@ describe('GroupsComponent', () => {
vm.change(2);
expect(eventHub.$emit).toHaveBeenCalledWith('fetchPage', 2, jasmine.any(Object), jasmine.any(Object), jasmine.any(Object));
expect(eventHub.$emit).toHaveBeenCalledWith(
'fetchPage',
2,
jasmine.any(Object),
jasmine.any(Object),
jasmine.any(Object),
);
});
});
});
describe('template', () => {
it('should render component template correctly', (done) => {
it('should render component template correctly', done => {
Vue.nextTick(() => {
expect(vm.$el.querySelector('.groups-list-tree-container')).toBeDefined();
expect(vm.$el.querySelector('.group-list-tree')).toBeDefined();
@ -59,7 +65,7 @@ describe('GroupsComponent', () => {
});
});
it('should render empty search message when `searchEmpty` is `true`', (done) => {
it('should render empty search message when `searchEmpty` is `true`', done => {
vm.searchEmpty = true;
Vue.nextTick(() => {
expect(vm.$el.querySelector('.has-no-search-results')).toBeDefined();

View File

@ -31,7 +31,11 @@ describe('ItemActionsComponent', () => {
spyOn(eventHub, '$emit');
vm.onLeaveGroup();
expect(eventHub.$emit).toHaveBeenCalledWith('showLeaveGroupModal', vm.group, vm.parentGroup);
expect(eventHub.$emit).toHaveBeenCalledWith(
'showLeaveGroupModal',
vm.group,
vm.parentGroup,
);
});
});
});

View File

@ -22,7 +22,7 @@ describe('ItemStatsComponent', () => {
describe('computed', () => {
describe('visibilityIcon', () => {
it('should return icon class based on `item.visibility` value', () => {
Object.keys(VISIBILITY_TYPE_ICON).forEach((visibility) => {
Object.keys(VISIBILITY_TYPE_ICON).forEach(visibility => {
const item = Object.assign({}, mockParentGroupItem, { visibility });
const vm = createComponent(item);
@ -34,7 +34,7 @@ describe('ItemStatsComponent', () => {
describe('visibilityTooltip', () => {
it('should return tooltip string for Group based on `item.visibility` value', () => {
Object.keys(GROUP_VISIBILITY_TYPE).forEach((visibility) => {
Object.keys(GROUP_VISIBILITY_TYPE).forEach(visibility => {
const item = Object.assign({}, mockParentGroupItem, {
visibility,
type: ITEM_TYPE.GROUP,
@ -47,7 +47,7 @@ describe('ItemStatsComponent', () => {
});
it('should return tooltip string for Project based on `item.visibility` value', () => {
Object.keys(PROJECT_VISIBILITY_TYPE).forEach((visibility) => {
Object.keys(PROJECT_VISIBILITY_TYPE).forEach(visibility => {
const item = Object.assign({}, mockParentGroupItem, {
visibility,
type: ITEM_TYPE.PROJECT,

View File

@ -340,7 +340,8 @@ export const mockSearchedGroups = [
{
id: 17,
name: 'v4.4',
description: 'Voluptatem qui ea error aperiam veritatis doloremque consequatur temporibus.',
description:
'Voluptatem qui ea error aperiam veritatis doloremque consequatur temporibus.',
visibility: 'public',
full_name: 'platform / hardware / bsp / kernel / common / v4.4',
relative_path: '/platform/hardware/bsp/kernel/common/v4.4',

View File

@ -1,7 +1,9 @@
import GroupsStore from '~/groups/store/groups_store';
import {
mockGroups, mockSearchedGroups,
mockParentGroupItem, mockRawChildren,
mockGroups,
mockSearchedGroups,
mockParentGroupItem,
mockRawChildren,
mockRawPageInfo,
} from '../mock_data';
@ -46,7 +48,9 @@ describe('ProjectsStore', () => {
expect(store.state.groups.length).toBe(mockSearchedGroups.length);
expect(store.formatGroupItem).toHaveBeenCalledWith(jasmine.any(Object));
expect(Object.keys(store.state.groups[0]).indexOf('fullName')).toBeGreaterThan(-1);
expect(Object.keys(store.state.groups[0].children[0]).indexOf('fullName')).toBeGreaterThan(-1);
expect(Object.keys(store.state.groups[0].children[0]).indexOf('fullName')).toBeGreaterThan(
-1,
);
});
});

View File

@ -1,7 +1,7 @@
import $ from 'jquery';
import initTodoToggle from '~/header';
describe('Header', function () {
describe('Header', function() {
const todosPendingCount = '.todos-count';
const fixtureTemplate = 'issues/open-issue.html.raw';

View File

@ -2,11 +2,13 @@
import './class_spec_helper';
describe('ClassSpecHelper', function () {
describe('ClassSpecHelper', function() {
describe('itShouldBeAStaticMethod', () => {
beforeEach(() => {
class TestClass {
instanceMethod() { this.prop = 'val'; }
instanceMethod() {
this.prop = 'val';
}
static staticMethod() {}
}

View File

@ -1,6 +1,6 @@
/* eslint-disable import/prefer-default-export */
export const setLanguage = (languageCode) => {
export const setLanguage = languageCode => {
const htmlElement = document.querySelector('html');
if (languageCode) {

View File

@ -1,3 +1,4 @@
export default (time = 0) => new Promise((resolve) => {
setTimeout(resolve, time);
});
export default (time = 0) =>
new Promise(resolve => {
setTimeout(resolve, time);
});

View File

@ -2,14 +2,12 @@ export default {
createNumberRandomUsers(numberUsers) {
const users = [];
for (let i = 0; i < numberUsers; i += 1) {
users.push(
{
avatar: 'https://gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80&d=identicon',
id: (i + 1),
name: `GitLab User ${i}`,
username: `gitlab${i}`,
},
);
users.push({
avatar: 'https://gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80&d=identicon',
id: i + 1,
name: `GitLab User ${i}`,
username: `gitlab${i}`,
});
}
return users;
},

View File

@ -1,6 +1,6 @@
// eslint-disable-next-line import/prefer-default-export
export const headersInterceptor = (request, next) => {
next((response) => {
next(response => {
const headers = {};
response.headers.forEach((value, key) => {
headers[key] = value;

View File

@ -36,7 +36,8 @@ describe('IDE branch item', () => {
});
it('renders link to branch', () => {
const expectedHref = router.resolve(`/project/${TEST_PROJECT_ID}/edit/${TEST_BRANCH.name}`).href;
const expectedHref = router.resolve(`/project/${TEST_PROJECT_ID}/edit/${TEST_BRANCH.name}`)
.href;
expect(vm.$el).toMatch('a');
expect(vm.$el).toHaveAttr('href', expectedHref);

View File

@ -62,8 +62,9 @@ describe('IDE branches search list', () => {
});
it('renders list', () => {
const elementText = Array.from(vm.$el.querySelectorAll('li strong'))
.map(x => x.textContent.trim());
const elementText = Array.from(vm.$el.querySelectorAll('li strong')).map(x =>
x.textContent.trim(),
);
expect(elementText).toEqual(testBranches.map(x => x.name));
});

View File

@ -36,8 +36,7 @@ describe('IDE commit message field', () => {
it('removed is-focused class on blur', done => {
vm.$el.querySelector('textarea').focus();
vm
.$nextTick()
vm.$nextTick()
.then(() => {
expect(vm.$el.querySelector('.is-focused')).not.toBeNull();
@ -70,8 +69,7 @@ describe('IDE commit message field', () => {
it('does not highlight less than 50 characters', done => {
vm.text = 'text less than 50 chars';
vm
.$nextTick()
vm.$nextTick()
.then(() => {
expect(vm.$el.querySelector('.highlights span').textContent).toContain(
'text less than 50 chars',
@ -87,8 +85,7 @@ describe('IDE commit message field', () => {
vm.text =
'text less than 50 chars that should not highlighted. text more than 50 should be highlighted';
vm
.$nextTick()
vm.$nextTick()
.then(() => {
expect(vm.$el.querySelector('.highlights span').textContent).toContain(
'text less than 50 chars that should not highlighte',
@ -108,8 +105,7 @@ describe('IDE commit message field', () => {
it('does not highlight body text less tan 72 characters', done => {
vm.text = 'subject line\nbody content';
vm
.$nextTick()
vm.$nextTick()
.then(() => {
expect(vm.$el.querySelectorAll('.highlights span').length).toBe(2);
expect(vm.$el.querySelectorAll('mark')[1].style.display).toBe('none');
@ -122,8 +118,7 @@ describe('IDE commit message field', () => {
vm.text =
'subject line\nbody content that will be highlighted when it is more than 72 characters in length';
vm
.$nextTick()
vm.$nextTick()
.then(() => {
expect(vm.$el.querySelectorAll('.highlights span').length).toBe(2);
expect(vm.$el.querySelectorAll('mark')[1].style.display).not.toBe('none');
@ -137,8 +132,7 @@ describe('IDE commit message field', () => {
vm.text =
'text less than 50 chars that should not highlighted\nbody content that will be highlighted when it is more than 72 characters in length';
vm
.$nextTick()
vm.$nextTick()
.then(() => {
expect(vm.$el.querySelectorAll('.highlights span').length).toBe(2);
expect(vm.$el.querySelectorAll('mark').length).toBe(2);
@ -156,8 +150,7 @@ describe('IDE commit message field', () => {
it('updates transform of highlights', done => {
vm.text = 'subject line\n\n\n\n\n\n\n\n\n\n\nbody content';
vm
.$nextTick()
vm.$nextTick()
.then(() => {
vm.$el.querySelector('textarea').scrollTo(0, 50);

View File

@ -85,8 +85,7 @@ describe('IDE File finder item spec', () => {
it('clear button resets searchText', done => {
vm.searchText = 'index';
vm
.$nextTick()
vm.$nextTick()
.then(() => {
vm.$el.querySelector('.dropdown-input-clear').click();
})
@ -102,8 +101,7 @@ describe('IDE File finder item spec', () => {
spyOn(vm.$refs.searchInput, 'focus');
vm.searchText = 'index';
vm
.$nextTick()
vm.$nextTick()
.then(() => {
vm.$el.querySelector('.dropdown-input-clear').click();
})
@ -178,8 +176,7 @@ describe('IDE File finder item spec', () => {
vm.searchText = 'test';
vm.$store.state.fileFindVisible = true;
vm
.$nextTick()
vm.$nextTick()
.then(() => {
vm.$store.state.fileFindVisible = false;
})

View File

@ -84,8 +84,7 @@ describe('ide component', () => {
it('calls toggleFileFinder on `t` key press', done => {
Mousetrap.trigger('t');
vm
.$nextTick()
vm.$nextTick()
.then(() => {
expect(vm.toggleFileFinder).toHaveBeenCalled();
})
@ -96,8 +95,7 @@ describe('ide component', () => {
it('calls toggleFileFinder on `command+p` key press', done => {
Mousetrap.trigger('command+p');
vm
.$nextTick()
vm.$nextTick()
.then(() => {
expect(vm.toggleFileFinder).toHaveBeenCalled();
})
@ -108,8 +106,7 @@ describe('ide component', () => {
it('calls toggleFileFinder on `ctrl+p` key press', done => {
Mousetrap.trigger('ctrl+p');
vm
.$nextTick()
vm.$nextTick()
.then(() => {
expect(vm.toggleFileFinder).toHaveBeenCalled();
})

View File

@ -78,8 +78,7 @@ describe('ideStatusBar', () => {
},
});
vm
.$nextTick()
vm.$nextTick()
.then(() => {
vm.$el.querySelector('.ide-status-pipeline button').click();

View File

@ -109,8 +109,7 @@ describe('IDE jobs detail view', () => {
vm.scrollPos = 1;
vm
.$nextTick()
vm.$nextTick()
.then(() => vm.$el.querySelector('.btn-scroll').click())
.then(() => vm.$nextTick())
.then(() => {

View File

@ -29,7 +29,9 @@ describe('IDE merge request item', () => {
});
it('renders link with href', () => {
const expectedHref = router.resolve(`/project/${vm.item.projectPathWithNamespace}/merge_requests/${vm.item.iid}`).href;
const expectedHref = router.resolve(
`/project/${vm.item.projectPathWithNamespace}/merge_requests/${vm.item.iid}`,
).href;
expect(vm.$el).toMatch('a');
expect(vm.$el).toHaveAttr('href', expectedHref);

View File

@ -118,8 +118,9 @@ describe('IDE merge requests list', () => {
vm.$nextTick()
.then(() => {
const expectedSearchTypes = vm.$options.searchTypes.map(x => x.label);
const renderedSearchTypes = Array.from(vm.$el.querySelectorAll('li'))
.map(x => x.textContent.trim());
const renderedSearchTypes = Array.from(vm.$el.querySelectorAll('li')).map(x =>
x.textContent.trim(),
);
expect(renderedSearchTypes).toEqual(expectedSearchTypes);
})

Some files were not shown because too many files have changed in this diff Show More