Commit df176fe7 authored by Filipa Lacerda's avatar Filipa Lacerda

Merge branch 'ph-axios-4' into 'master'

More conversions of $.ajax to axios

See merge request gitlab-org/gitlab-ce!16882
parents 1214d8de c5e59a97
import { __ } from './locale';
import axios from './lib/utils/axios_utils';
import flash from './flash';
export default class ProjectLabelSubscription { export default class ProjectLabelSubscription {
constructor(container) { constructor(container) {
this.$container = $(container); this.$container = $(container);
...@@ -17,10 +21,7 @@ export default class ProjectLabelSubscription { ...@@ -17,10 +21,7 @@ export default class ProjectLabelSubscription {
$btn.addClass('disabled'); $btn.addClass('disabled');
$span.toggleClass('hidden'); $span.toggleClass('hidden');
$.ajax({ axios.post(url).then(() => {
type: 'POST',
url,
}).done(() => {
let newStatus; let newStatus;
let newAction; let newAction;
...@@ -45,6 +46,6 @@ export default class ProjectLabelSubscription { ...@@ -45,6 +46,6 @@ export default class ProjectLabelSubscription {
return button; return button;
}); });
}); }).catch(() => flash(__('There was an error subscribing to this label.')));
} }
} }
import axios from '../lib/utils/axios_utils';
import PANEL_STATE from './constants'; import PANEL_STATE from './constants';
import { backOff } from '../lib/utils/common_utils'; import { backOff } from '../lib/utils/common_utils';
...@@ -81,24 +82,20 @@ export default class PrometheusMetrics { ...@@ -81,24 +82,20 @@ export default class PrometheusMetrics {
loadActiveMetrics() { loadActiveMetrics() {
this.showMonitoringMetricsPanelState(PANEL_STATE.LOADING); this.showMonitoringMetricsPanelState(PANEL_STATE.LOADING);
backOff((next, stop) => { backOff((next, stop) => {
$.ajax({ axios.get(this.activeMetricsEndpoint)
url: this.activeMetricsEndpoint, .then(({ data }) => {
dataType: 'json', if (data && data.success) {
global: false, stop(data);
})
.done((res) => {
if (res && res.success) {
stop(res);
} else { } else {
this.backOffRequestCounter = this.backOffRequestCounter += 1; this.backOffRequestCounter = this.backOffRequestCounter += 1;
if (this.backOffRequestCounter < 3) { if (this.backOffRequestCounter < 3) {
next(); next();
} else { } else {
stop(res); stop(data);
} }
} }
}) })
.fail(stop); .catch(stop);
}) })
.then((res) => { .then((res) => {
if (res && res.data && res.data.length) { if (res && res.data && res.data.length) {
......
/* eslint-disable no-new */ import flash from '../flash';
import Flash from '../flash'; import axios from '../lib/utils/axios_utils';
import ProtectedBranchAccessDropdown from './protected_branch_access_dropdown'; import ProtectedBranchAccessDropdown from './protected_branch_access_dropdown';
export default class ProtectedBranchEdit { export default class ProtectedBranchEdit {
...@@ -38,12 +38,7 @@ export default class ProtectedBranchEdit { ...@@ -38,12 +38,7 @@ export default class ProtectedBranchEdit {
this.$allowedToMergeDropdown.disable(); this.$allowedToMergeDropdown.disable();
this.$allowedToPushDropdown.disable(); this.$allowedToPushDropdown.disable();
$.ajax({ axios.patch(this.$wrap.data('url'), {
type: 'POST',
url: this.$wrap.data('url'),
dataType: 'json',
data: {
_method: 'PATCH',
protected_branch: { protected_branch: {
merge_access_levels_attributes: [{ merge_access_levels_attributes: [{
id: this.$allowedToMergeDropdown.data('access-level-id'), id: this.$allowedToMergeDropdown.data('access-level-id'),
...@@ -54,13 +49,14 @@ export default class ProtectedBranchEdit { ...@@ -54,13 +49,14 @@ export default class ProtectedBranchEdit {
access_level: $allowedToPushInput.val(), access_level: $allowedToPushInput.val(),
}], }],
}, },
}, }).then(() => {
error() {
new Flash('Failed to update branch!', 'alert', document.querySelector('.js-protected-branches-list'));
},
}).always(() => {
this.$allowedToMergeDropdown.enable(); this.$allowedToMergeDropdown.enable();
this.$allowedToPushDropdown.enable(); this.$allowedToPushDropdown.enable();
}).catch(() => {
this.$allowedToMergeDropdown.enable();
this.$allowedToPushDropdown.enable();
flash('Failed to update branch!', 'alert', document.querySelector('.js-protected-branches-list'));
}); });
} }
} }
/* eslint-disable no-new */ import flash from '../flash';
import Flash from '../flash'; import axios from '../lib/utils/axios_utils';
import ProtectedTagAccessDropdown from './protected_tag_access_dropdown'; import ProtectedTagAccessDropdown from './protected_tag_access_dropdown';
export default class ProtectedTagEdit { export default class ProtectedTagEdit {
...@@ -28,24 +28,19 @@ export default class ProtectedTagEdit { ...@@ -28,24 +28,19 @@ export default class ProtectedTagEdit {
this.$allowedToCreateDropdownButton.disable(); this.$allowedToCreateDropdownButton.disable();
$.ajax({ axios.patch(this.$wrap.data('url'), {
type: 'POST',
url: this.$wrap.data('url'),
dataType: 'json',
data: {
_method: 'PATCH',
protected_tag: { protected_tag: {
create_access_levels_attributes: [{ create_access_levels_attributes: [{
id: this.$allowedToCreateDropdownButton.data('access-level-id'), id: this.$allowedToCreateDropdownButton.data('access-level-id'),
access_level: $allowedToCreateInput.val(), access_level: $allowedToCreateInput.val(),
}], }],
}, },
}, }).then(() => {
error() {
new Flash('Failed to update tag!', 'alert', document.querySelector('.js-protected-tags-list'));
},
}).always(() => {
this.$allowedToCreateDropdownButton.enable(); this.$allowedToCreateDropdownButton.enable();
}).catch(() => {
this.$allowedToCreateDropdownButton.enable();
flash('Failed to update tag!', 'alert', document.querySelector('.js-protected-tags-list'));
}); });
} }
} }
...@@ -2,6 +2,8 @@ ...@@ -2,6 +2,8 @@
import _ from 'underscore'; import _ from 'underscore';
import Cookies from 'js-cookie'; import Cookies from 'js-cookie';
import flash from './flash';
import axios from './lib/utils/axios_utils';
function Sidebar(currentUser) { function Sidebar(currentUser) {
this.toggleTodo = this.toggleTodo.bind(this); this.toggleTodo = this.toggleTodo.bind(this);
...@@ -62,7 +64,7 @@ Sidebar.prototype.sidebarToggleClicked = function (e, triggered) { ...@@ -62,7 +64,7 @@ Sidebar.prototype.sidebarToggleClicked = function (e, triggered) {
Sidebar.prototype.toggleTodo = function(e) { Sidebar.prototype.toggleTodo = function(e) {
var $btnText, $this, $todoLoading, ajaxType, url; var $btnText, $this, $todoLoading, ajaxType, url;
$this = $(e.currentTarget); $this = $(e.currentTarget);
ajaxType = $this.attr('data-delete-path') ? 'DELETE' : 'POST'; ajaxType = $this.attr('data-delete-path') ? 'delete' : 'post';
if ($this.attr('data-delete-path')) { if ($this.attr('data-delete-path')) {
url = "" + ($this.attr('data-delete-path')); url = "" + ($this.attr('data-delete-path'));
} else { } else {
...@@ -71,25 +73,14 @@ Sidebar.prototype.toggleTodo = function(e) { ...@@ -71,25 +73,14 @@ Sidebar.prototype.toggleTodo = function(e) {
$this.tooltip('hide'); $this.tooltip('hide');
return $.ajax({ $('.js-issuable-todo').disable().addClass('is-loading');
url: url,
type: ajaxType, axios[ajaxType](url, {
dataType: 'json',
data: {
issuable_id: $this.data('issuable-id'), issuable_id: $this.data('issuable-id'),
issuable_type: $this.data('issuable-type') issuable_type: $this.data('issuable-type'),
}, }).then(({ data }) => {
beforeSend: (function(_this) { this.todoUpdateDone(data);
return function() { }).catch(() => flash(`There was an error ${ajaxType === 'post' ? 'adding a' : 'deleting the'} todo.`));
$('.js-issuable-todo').disable()
.addClass('is-loading');
};
})(this)
}).done((function(_this) {
return function(data) {
return _this.todoUpdateDone(data);
};
})(this));
}; };
Sidebar.prototype.todoUpdateDone = function(data) { Sidebar.prototype.todoUpdateDone = function(data) {
......
import Cookies from 'js-cookie'; import Cookies from 'js-cookie';
import Mousetrap from 'mousetrap'; import Mousetrap from 'mousetrap';
import axios from './lib/utils/axios_utils';
import { refreshCurrentPage, visitUrl } from './lib/utils/url_utility'; import { refreshCurrentPage, visitUrl } from './lib/utils/url_utility';
import findAndFollowLink from './shortcuts_dashboard_navigation'; import findAndFollowLink from './shortcuts_dashboard_navigation';
...@@ -85,10 +86,11 @@ export default class Shortcuts { ...@@ -85,10 +86,11 @@ export default class Shortcuts {
$modal.modal('toggle'); $modal.modal('toggle');
} }
$.ajax({ return axios.get(gon.shortcuts_path, {
url: gon.shortcuts_path, responseType: 'text',
dataType: 'script', }).then(({ data }) => {
success() { $.globalEval(data);
if (location && location.length > 0) { if (location && location.length > 0) {
const results = []; const results = [];
for (let i = 0, len = location.length; i < len; i += 1) { for (let i = 0, len = location.length; i < len; i += 1) {
...@@ -99,7 +101,6 @@ export default class Shortcuts { ...@@ -99,7 +101,6 @@ export default class Shortcuts {
$('.hidden-shortcut').show(); $('.hidden-shortcut').show();
return $('.js-more-help-button').remove(); return $('.js-more-help-button').remove();
},
}); });
} }
......
import 'deckar01-task_list'; import 'deckar01-task_list';
import axios from './lib/utils/axios_utils';
import Flash from './flash'; import Flash from './flash';
export default class TaskList { export default class TaskList {
...@@ -7,11 +8,11 @@ export default class TaskList { ...@@ -7,11 +8,11 @@ export default class TaskList {
this.dataType = options.dataType; this.dataType = options.dataType;
this.fieldName = options.fieldName; this.fieldName = options.fieldName;
this.onSuccess = options.onSuccess || (() => {}); this.onSuccess = options.onSuccess || (() => {});
this.onError = function showFlash(response) { this.onError = function showFlash(e) {
let errorMessages = ''; let errorMessages = '';
if (response.responseJSON) { if (e.response.data && typeof e.response.data === 'object') {
errorMessages = response.responseJSON.errors.join(' '); errorMessages = e.response.data.errors.join(' ');
} }
return new Flash(errorMessages || 'Update failed', 'alert'); return new Flash(errorMessages || 'Update failed', 'alert');
...@@ -38,12 +39,9 @@ export default class TaskList { ...@@ -38,12 +39,9 @@ export default class TaskList {
patchData[this.dataType] = { patchData[this.dataType] = {
[this.fieldName]: $target.val(), [this.fieldName]: $target.val(),
}; };
return $.ajax({
type: 'PATCH', return axios.patch($target.data('update-url') || $('form.js-issuable-update').attr('action'), patchData)
url: $target.data('update-url') || $('form.js-issuable-update').attr('action'), .then(({ data }) => this.onSuccess(data))
data: patchData, .catch(err => this.onError(err));
success: this.onSuccess,
error: this.onError,
});
} }
} }
import axios from '../lib/utils/axios_utils';
import Activities from '../activities'; import Activities from '../activities';
import ActivityCalendar from './activity_calendar'; import ActivityCalendar from './activity_calendar';
import { localTimeAgo } from '../lib/utils/datetime_utility'; import { localTimeAgo } from '../lib/utils/datetime_utility';
import { __ } from '../locale';
import flash from '../flash';
/** /**
* UserTabs * UserTabs
...@@ -131,17 +134,19 @@ export default class UserTabs { ...@@ -131,17 +134,19 @@ export default class UserTabs {
} }
loadTab(action, endpoint) { loadTab(action, endpoint) {
return $.ajax({ this.toggleLoading(true);
beforeSend: () => this.toggleLoading(true),
complete: () => this.toggleLoading(false), return axios.get(endpoint)
dataType: 'json', .then(({ data }) => {
url: endpoint,
success: (data) => {
const tabSelector = `div#${action}`; const tabSelector = `div#${action}`;
this.$parentEl.find(tabSelector).html(data.html); this.$parentEl.find(tabSelector).html(data.html);
this.loaded[action] = true; this.loaded[action] = true;
localTimeAgo($('.js-timeago', tabSelector)); localTimeAgo($('.js-timeago', tabSelector));
},
this.toggleLoading(false);
})
.catch(() => {
this.toggleLoading(false);
}); });
} }
...@@ -158,17 +163,15 @@ export default class UserTabs { ...@@ -158,17 +163,15 @@ export default class UserTabs {
utcFormatted = `UTC${utcOffset > 0 ? '+' : ''}${(utcOffset / 3600)}`; utcFormatted = `UTC${utcOffset > 0 ? '+' : ''}${(utcOffset / 3600)}`;
} }
$.ajax({ axios.get(calendarPath)
dataType: 'json', .then(({ data }) => {
url: calendarPath,
success: (activityData) => {
$calendarWrap.html(CALENDAR_TEMPLATE); $calendarWrap.html(CALENDAR_TEMPLATE);
$calendarWrap.find('.calendar-hint').append(`(Timezone: ${utcFormatted})`); $calendarWrap.find('.calendar-hint').append(`(Timezone: ${utcFormatted})`);
// eslint-disable-next-line no-new // eslint-disable-next-line no-new
new ActivityCalendar('.js-contrib-calendar', activityData, calendarActivitiesPath, utcOffset); new ActivityCalendar('.js-contrib-calendar', data, calendarActivitiesPath, utcOffset);
}, })
}); .catch(() => flash(__('There was an error loading users activity calendar.')));
// eslint-disable-next-line no-new // eslint-disable-next-line no-new
new Activities(); new Activities();
......
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
/* global Issuable */ /* global Issuable */
/* global emitSidebarEvent */ /* global emitSidebarEvent */
import _ from 'underscore'; import _ from 'underscore';
import axios from './lib/utils/axios_utils';
// TODO: remove eventHub hack after code splitting refactor // TODO: remove eventHub hack after code splitting refactor
window.emitSidebarEvent = window.emitSidebarEvent || $.noop; window.emitSidebarEvent = window.emitSidebarEvent || $.noop;
...@@ -177,12 +178,8 @@ function UsersSelect(currentUser, els, options = {}) { ...@@ -177,12 +178,8 @@ function UsersSelect(currentUser, els, options = {}) {
$loading.removeClass('hidden').fadeIn(); $loading.removeClass('hidden').fadeIn();
$dropdown.trigger('loading.gl.dropdown'); $dropdown.trigger('loading.gl.dropdown');
return $.ajax({ return axios.put(issueURL, data)
type: 'PUT', .then(({ data }) => {
dataType: 'json',
url: issueURL,
data: data
}).done(function(data) {
var user; var user;
$dropdown.trigger('loaded.gl.dropdown'); $dropdown.trigger('loaded.gl.dropdown');
$loading.fadeOut(); $loading.fadeOut();
...@@ -660,22 +657,17 @@ UsersSelect.prototype.user = function(user_id, callback) { ...@@ -660,22 +657,17 @@ UsersSelect.prototype.user = function(user_id, callback) {
var url; var url;
url = this.buildUrl(this.userPath); url = this.buildUrl(this.userPath);
url = url.replace(':id', user_id); url = url.replace(':id', user_id);
return $.ajax({ return axios.get(url)
url: url, .then(({ data }) => {
dataType: "json" callback(data);
}).done(function(user) {
return callback(user);
}); });
}; };
// Return users list. Filtered by query // Return users list. Filtered by query
// Only active users retrieved // Only active users retrieved
UsersSelect.prototype.users = function(query, options, callback) { UsersSelect.prototype.users = function(query, options, callback) {
var url; const url = this.buildUrl(this.usersPath);
url = this.buildUrl(this.usersPath); const params = {
return $.ajax({
url: url,
data: {
search: query, search: query,
per_page: options.perPage || 20, per_page: options.perPage || 20,
active: true, active: true,
...@@ -687,10 +679,10 @@ UsersSelect.prototype.users = function(query, options, callback) { ...@@ -687,10 +679,10 @@ UsersSelect.prototype.users = function(query, options, callback) {
current_user: options.showCurrentUser || null, current_user: options.showCurrentUser || null,
author_id: options.authorId || null, author_id: options.authorId || null,
skip_users: options.skipUsers || null skip_users: options.skipUsers || null
}, };
dataType: "json" return axios.get(url, { params })
}).done(function(users) { .then(({ data }) => {
return callback(users); callback(data);
}); });
}; };
......
/* eslint-disable no-new */ /* eslint-disable no-new */
import _ from 'underscore'; import _ from 'underscore';
import MockAdapter from 'axios-mock-adapter';
import axios from '~/lib/utils/axios_utils';
import Sidebar from '~/right_sidebar'; import Sidebar from '~/right_sidebar';
import timeoutPromise from './helpers/set_timeout_promise_helper';
describe('Issuable right sidebar collapsed todo toggle', () => { describe('Issuable right sidebar collapsed todo toggle', () => {
const fixtureName = 'issues/open-issue.html.raw'; const fixtureName = 'issues/open-issue.html.raw';
const jsonFixtureName = 'todos/todos.json'; const jsonFixtureName = 'todos/todos.json';
let mock;
preloadFixtures(fixtureName); preloadFixtures(fixtureName);
preloadFixtures(jsonFixtureName); preloadFixtures(jsonFixtureName);
...@@ -19,19 +23,26 @@ describe('Issuable right sidebar collapsed todo toggle', () => { ...@@ -19,19 +23,26 @@ describe('Issuable right sidebar collapsed todo toggle', () => {
document.querySelector('.js-right-sidebar') document.querySelector('.js-right-sidebar')
.classList.toggle('right-sidebar-collapsed'); .classList.toggle('right-sidebar-collapsed');
spyOn(jQuery, 'ajax').and.callFake((res) => { mock = new MockAdapter(axios);
const d = $.Deferred();
mock.onPost(`${gl.TEST_HOST}/frontend-fixtures/issues-project/todos`).reply(() => {
const response = _.clone(todoData); const response = _.clone(todoData);
if (res.type === 'DELETE') { return [200, response];
});
mock.onDelete(/(.*)\/dashboard\/todos\/\d+$/).reply(() => {
const response = _.clone(todoData);
delete response.delete_path; delete response.delete_path;
}
d.resolve(response); return [200, response];
return d.promise();
}); });
}); });
afterEach(() => {
mock.restore();
});
it('shows add todo button', () => { it('shows add todo button', () => {
expect( expect(
document.querySelector('.js-issuable-todo.sidebar-collapsed-icon'), document.querySelector('.js-issuable-todo.sidebar-collapsed-icon'),
...@@ -52,9 +63,10 @@ describe('Issuable right sidebar collapsed todo toggle', () => { ...@@ -52,9 +63,10 @@ describe('Issuable right sidebar collapsed todo toggle', () => {
).toBe('Add todo'); ).toBe('Add todo');
}); });
it('toggle todo state', () => { it('toggle todo state', (done) => {
document.querySelector('.js-issuable-todo.sidebar-collapsed-icon').click(); document.querySelector('.js-issuable-todo.sidebar-collapsed-icon').click();
setTimeout(() => {
expect( expect(
document.querySelector('.js-issuable-todo.sidebar-collapsed-icon .todo-undone'), document.querySelector('.js-issuable-todo.sidebar-collapsed-icon .todo-undone'),
).not.toBeNull(); ).not.toBeNull();
...@@ -62,33 +74,48 @@ describe('Issuable right sidebar collapsed todo toggle', () => { ...@@ -62,33 +74,48 @@ describe('Issuable right sidebar collapsed todo toggle', () => {
expect( expect(
document.querySelector('.js-issuable-todo.sidebar-collapsed-icon .fa-check-square'), document.querySelector('.js-issuable-todo.sidebar-collapsed-icon .fa-check-square'),
).not.toBeNull(); ).not.toBeNull();
done();
});
}); });
it('toggle todo state of expanded todo toggle', () => { it('toggle todo state of expanded todo toggle', (done) => {
document.querySelector('.js-issuable-todo.sidebar-collapsed-icon').click(); document.querySelector('.js-issuable-todo.sidebar-collapsed-icon').click();
setTimeout(() => {
expect( expect(
document.querySelector('.issuable-sidebar-header .js-issuable-todo').textContent.trim(), document.querySelector('.issuable-sidebar-header .js-issuable-todo').textContent.trim(),
).toBe('Mark done'); ).toBe('Mark done');
done();
});
}); });
it('toggles todo button tooltip', () => { it('toggles todo button tooltip', (done) => {
document.querySelector('.js-issuable-todo.sidebar-collapsed-icon').click(); document.querySelector('.js-issuable-todo.sidebar-collapsed-icon').click();
setTimeout(() => {
expect( 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 done'); ).toBe('Mark done');
done();
});
}); });
it('marks todo as done', () => { it('marks todo as done', (done) => {
document.querySelector('.js-issuable-todo.sidebar-collapsed-icon').click(); document.querySelector('.js-issuable-todo.sidebar-collapsed-icon').click();
timeoutPromise()
.then(() => {
expect( expect(
document.querySelector('.js-issuable-todo.sidebar-collapsed-icon .todo-undone'), document.querySelector('.js-issuable-todo.sidebar-collapsed-icon .todo-undone'),
).not.toBeNull(); ).not.toBeNull();
document.querySelector('.js-issuable-todo.sidebar-collapsed-icon').click(); document.querySelector('.js-issuable-todo.sidebar-collapsed-icon').click();
})
.then(timeoutPromise)
.then(() => {
expect( expect(
document.querySelector('.js-issuable-todo.sidebar-collapsed-icon .todo-undone'), document.querySelector('.js-issuable-todo.sidebar-collapsed-icon .todo-undone'),
).toBeNull(); ).toBeNull();
...@@ -96,27 +123,41 @@ describe('Issuable right sidebar collapsed todo toggle', () => { ...@@ -96,27 +123,41 @@ describe('Issuable right sidebar collapsed todo toggle', () => {
expect( expect(
document.querySelector('.issuable-sidebar-header .js-issuable-todo').textContent.trim(), document.querySelector('.issuable-sidebar-header .js-issuable-todo').textContent.trim(),
).toBe('Add todo'); ).toBe('Add todo');
})
.then(done)
.catch(done.fail);
}); });
it('updates aria-label to mark done', () => { it('updates aria-label to mark done', (done) => {
document.querySelector('.js-issuable-todo.sidebar-collapsed-icon').click(); document.querySelector('.js-issuable-todo.sidebar-collapsed-icon').click();
setTimeout(() => {
expect( 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 done'); ).toBe('Mark done');
done();
});
}); });
it('updates aria-label to add todo', () => { it('updates aria-label to add todo', (done) => {
document.querySelector('.js-issuable-todo.sidebar-collapsed-icon').click(); document.querySelector('.js-issuable-todo.sidebar-collapsed-icon').click();
timeoutPromise()
.then(() => {
expect( 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 done'); ).toBe('Mark done');
document.querySelector('.js-issuable-todo.sidebar-collapsed-icon').click(); document.querySelector('.js-issuable-todo.sidebar-collapsed-icon').click();
})
.then(timeoutPromise)
.then(() => {
expect( 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'); ).toBe('Add todo');
})
.then(done)
.catch(done.fail);
}); });
}); });
...@@ -70,23 +70,6 @@ describe('Issue', function() { ...@@ -70,23 +70,6 @@ describe('Issue', function() {
expect($btn).toHaveText(isIssueInitiallyOpen ? 'Close issue' : 'Reopen issue'); expect($btn).toHaveText(isIssueInitiallyOpen ? 'Close issue' : 'Reopen issue');
} }
describe('task lists', function() {
beforeEach(function() {
loadFixtures('issues/issue-with-task-list.html.raw');
this.issue = new Issue();
});
it('submits an ajax request on tasklist:changed', function() {
spyOn(jQuery, 'ajax').and.callFake(function(req) {
expect(req.type).toBe('PATCH');
expect(req.url).toBe(gl.TEST_HOST + '/frontend-fixtures/issues-project/issues/1.json'); // eslint-disable-line prefer-template
expect(req.data.issue.description).not.toBe(null);
});
$('.js-task-list-field').trigger('tasklist:changed');
});
});
[true, false].forEach((isIssueInitiallyOpen) => { [true, false].forEach((isIssueInitiallyOpen) => {
describe(`with ${isIssueInitiallyOpen ? 'open' : 'closed'} issue`, function() { describe(`with ${isIssueInitiallyOpen ? 'open' : 'closed'} issue`, function() {
const action = isIssueInitiallyOpen ? 'close' : 'reopen'; const action = isIssueInitiallyOpen ? 'close' : 'reopen';
......
/* eslint-disable space-before-function-paren, no-return-assign */ /* eslint-disable space-before-function-paren, no-return-assign */
import MockAdapter from 'axios-mock-adapter';
import axios from '~/lib/utils/axios_utils';
import MergeRequest from '~/merge_request'; import MergeRequest from '~/merge_request';
import CloseReopenReportToggle from '~/close_reopen_report_toggle'; import CloseReopenReportToggle from '~/close_reopen_report_toggle';
import IssuablesHelper from '~/helpers/issuables_helper'; import IssuablesHelper from '~/helpers/issuables_helper';
...@@ -7,11 +8,24 @@ import IssuablesHelper from '~/helpers/issuables_helper'; ...@@ -7,11 +8,24 @@ import IssuablesHelper from '~/helpers/issuables_helper';
(function() { (function() {
describe('MergeRequest', function() { describe('MergeRequest', function() {
describe('task lists', function() { describe('task lists', function() {
let mock;
preloadFixtures('merge_requests/merge_request_with_task_list.html.raw'); preloadFixtures('merge_requests/merge_request_with_task_list.html.raw');
beforeEach(function() { beforeEach(function() {
loadFixtures('merge_requests/merge_request_with_task_list.html.raw'); loadFixtures('merge_requests/merge_request_with_task_list.html.raw');
spyOn(axios, 'patch').and.callThrough();
mock = new MockAdapter(axios);
mock.onPatch(`${gl.TEST_HOST}/frontend-fixtures/merge-requests-project/merge_requests/1.json`).reply(200, {});
return this.merge = new MergeRequest(); return this.merge = new MergeRequest();
}); });
afterEach(() => {
mock.restore();
});
it('modifies the Markdown field', function() { it('modifies the Markdown field', function() {
spyOn(jQuery, 'ajax').and.stub(); spyOn(jQuery, 'ajax').and.stub();
const changeEvent = document.createEvent('HTMLEvents'); const changeEvent = document.createEvent('HTMLEvents');
...@@ -21,14 +35,14 @@ import IssuablesHelper from '~/helpers/issuables_helper'; ...@@ -21,14 +35,14 @@ import IssuablesHelper from '~/helpers/issuables_helper';
}); });
it('submits an ajax request on tasklist:changed', (done) => { it('submits an ajax request on tasklist:changed', (done) => {
spyOn(jQuery, 'ajax').and.callFake((req) => { $('.js-task-list-field').trigger('tasklist:changed');
expect(req.type).toBe('PATCH');
expect(req.url).toBe(`${gl.TEST_HOST}/frontend-fixtures/merge-requests-project/merge_requests/1.json`); setTimeout(() => {
expect(req.data.merge_request.description).not.toBe(null); expect(axios.patch).toHaveBeenCalledWith(`${gl.TEST_HOST}/frontend-fixtures/merge-requests-project/merge_requests/1.json`, {
merge_request: { description: '- [ ] Task List Item' },
});
done(); done();
}); });
$('.js-task-list-field').trigger('tasklist:changed');
}); });
}); });
......
...@@ -50,13 +50,24 @@ import timeoutPromise from './helpers/set_timeout_promise_helper'; ...@@ -50,13 +50,24 @@ import timeoutPromise from './helpers/set_timeout_promise_helper';
}); });
describe('task lists', function() { describe('task lists', function() {
let mock;
beforeEach(function() { beforeEach(function() {
spyOn(axios, 'patch').and.callThrough();
mock = new MockAdapter(axios);
mock.onPatch(`${gl.TEST_HOST}/frontend-fixtures/merge-requests-project/merge_requests/1.json`).reply(200, {});
$('.js-comment-button').on('click', function(e) { $('.js-comment-button').on('click', function(e) {
e.preventDefault(); e.preventDefault();
}); });
this.notes = new Notes('', []); this.notes = new Notes('', []);
}); });
afterEach(() => {
mock.restore();
});
it('modifies the Markdown field', function() { it('modifies the Markdown field', function() {
const changeEvent = document.createEvent('HTMLEvents'); const changeEvent = document.createEvent('HTMLEvents');
changeEvent.initEvent('change', true, true); changeEvent.initEvent('change', true, true);
...@@ -65,14 +76,15 @@ import timeoutPromise from './helpers/set_timeout_promise_helper'; ...@@ -65,14 +76,15 @@ import timeoutPromise from './helpers/set_timeout_promise_helper';
expect($('.js-task-list-field.original-task-list').val()).toBe('- [x] Task List Item'); expect($('.js-task-list-field.original-task-list').val()).toBe('- [x] Task List Item');
}); });
it('submits an ajax request on tasklist:changed', function() { it('submits an ajax request on tasklist:changed', function(done) {
spyOn(jQuery, 'ajax').and.callFake(function(req) { $('.js-task-list-container').trigger('tasklist:changed');
expect(req.type).toBe('PATCH');
expect(req.url).toBe('http://test.host/frontend-fixtures/merge-requests-project/merge_requests/1.json');
return expect(req.data.note).not.toBe(null);
});
$('.js-task-list-field.js-note-text').trigger('tasklist:changed'); setTimeout(() => {
expect(axios.patch).toHaveBeenCalledWith(`${gl.TEST_HOST}/frontend-fixtures/merge-requests-project/merge_requests/1.json`, {
note: { note: '' },
});
done();
});
}); });
}); });
......
import MockAdapter from 'axios-mock-adapter';
import axios from '~/lib/utils/axios_utils';
import PrometheusMetrics from '~/prometheus_metrics/prometheus_metrics'; import PrometheusMetrics from '~/prometheus_metrics/prometheus_metrics';
import PANEL_STATE from '~/prometheus_metrics/constants'; import PANEL_STATE from '~/prometheus_metrics/constants';
import { metrics, missingVarMetrics } from './mock_data'; import { metrics, missingVarMetrics } from './mock_data';
...@@ -102,25 +104,38 @@ describe('PrometheusMetrics', () => { ...@@ -102,25 +104,38 @@ describe('PrometheusMetrics', () => {
describe('loadActiveMetrics', () => { describe('loadActiveMetrics', () => {
let prometheusMetrics; let prometheusMetrics;
let mock;
function mockSuccess() {
mock.onGet(prometheusMetrics.activeMetricsEndpoint).reply(200, {
data: metrics,
success: true,
});
}
function mockError() {
mock.onGet(prometheusMetrics.activeMetricsEndpoint).networkError();
}
beforeEach(() => { beforeEach(() => {
spyOn(axios, 'get').and.callThrough();
prometheusMetrics = new PrometheusMetrics('.js-prometheus-metrics-monitoring'); prometheusMetrics = new PrometheusMetrics('.js-prometheus-metrics-monitoring');
mock = new MockAdapter(axios);
});
afterEach(() => {
mock.restore();
}); });
it('should show loader animation while response is being loaded and hide it when request is complete', (done) => { it('should show loader animation while response is being loaded and hide it when request is complete', (done) => {
const deferred = $.Deferred(); mockSuccess();
spyOn($, 'ajax').and.returnValue(deferred.promise());
prometheusMetrics.loadActiveMetrics(); prometheusMetrics.loadActiveMetrics();
expect(prometheusMetrics.$monitoredMetricsLoading.hasClass('hidden')).toBeFalsy(); expect(prometheusMetrics.$monitoredMetricsLoading.hasClass('hidden')).toBeFalsy();
expect($.ajax).toHaveBeenCalledWith({ expect(axios.get).toHaveBeenCalledWith(prometheusMetrics.activeMetricsEndpoint);
url: prometheusMetrics.activeMetricsEndpoint,
dataType: 'json',
global: false,
});
deferred.resolve({ data: metrics, success: true });
setTimeout(() => { setTimeout(() => {
expect(prometheusMetrics.$monitoredMetricsLoading.hasClass('hidden')).toBeTruthy(); expect(prometheusMetrics.$monitoredMetricsLoading.hasClass('hidden')).toBeTruthy();
...@@ -129,14 +144,10 @@ describe('PrometheusMetrics', () => { ...@@ -129,14 +144,10 @@ describe('PrometheusMetrics', () => {
}); });
it('should show empty state if response failed to load', (done) => { it('should show empty state if response failed to load', (done) => {
const deferred = $.Deferred(); mockError();
spyOn($, 'ajax').and.returnValue(deferred.promise());
spyOn(prometheusMetrics, 'populateActiveMetrics');
prometheusMetrics.loadActiveMetrics(); prometheusMetrics.loadActiveMetrics();
deferred.reject();
setTimeout(() => { setTimeout(() => {
expect(prometheusMetrics.$monitoredMetricsLoading.hasClass('hidden')).toBeTruthy(); expect(prometheusMetrics.$monitoredMetricsLoading.hasClass('hidden')).toBeTruthy();
expect(prometheusMetrics.$monitoredMetricsEmpty.hasClass('hidden')).toBeFalsy(); expect(prometheusMetrics.$monitoredMetricsEmpty.hasClass('hidden')).toBeFalsy();
...@@ -145,14 +156,11 @@ describe('PrometheusMetrics', () => { ...@@ -145,14 +156,11 @@ describe('PrometheusMetrics', () => {
}); });
it('should populate metrics list once response is loaded', (done) => { it('should populate metrics list once response is loaded', (done) => {
const deferred = $.Deferred();
spyOn($, 'ajax').and.returnValue(deferred.promise());
spyOn(prometheusMetrics, 'populateActiveMetrics'); spyOn(prometheusMetrics, 'populateActiveMetrics');
mockSuccess();
prometheusMetrics.loadActiveMetrics(); prometheusMetrics.loadActiveMetrics();
deferred.resolve({ data: metrics, success: true });
setTimeout(() => { setTimeout(() => {
expect(prometheusMetrics.populateActiveMetrics).toHaveBeenCalledWith(metrics); expect(prometheusMetrics.populateActiveMetrics).toHaveBeenCalledWith(metrics);
done(); done();
......
/* eslint-disable space-before-function-paren, no-var, one-var, one-var-declaration-per-line, new-parens, no-return-assign, new-cap, vars-on-top, max-len */ /* eslint-disable space-before-function-paren, no-var, one-var, one-var-declaration-per-line, new-parens, no-return-assign, new-cap, vars-on-top, max-len */
import MockAdapter from 'axios-mock-adapter';
import '~/commons/bootstrap'; import '~/commons/bootstrap';
import axios from '~/lib/utils/axios_utils';
import Sidebar from '~/right_sidebar'; import Sidebar from '~/right_sidebar';
(function() { (function() {
...@@ -35,16 +37,23 @@ import Sidebar from '~/right_sidebar'; ...@@ -35,16 +37,23 @@ import Sidebar from '~/right_sidebar';
var fixtureName = 'issues/open-issue.html.raw'; var fixtureName = 'issues/open-issue.html.raw';
preloadFixtures(fixtureName); preloadFixtures(fixtureName);
loadJSONFixtures('todos/todos.json'); loadJSONFixtures('todos/todos.json');
let mock;
beforeEach(function() { beforeEach(function() {
loadFixtures(fixtureName); loadFixtures(fixtureName);
this.sidebar = new Sidebar; mock = new MockAdapter(axios);
this.sidebar = new Sidebar();
$aside = $('.right-sidebar'); $aside = $('.right-sidebar');
$page = $('.layout-page'); $page = $('.layout-page');
$icon = $aside.find('i'); $icon = $aside.find('i');
$toggle = $aside.find('.js-sidebar-toggle'); $toggle = $aside.find('.js-sidebar-toggle');
return $labelsIcon = $aside.find('.sidebar-collapsed-icon'); return $labelsIcon = $aside.find('.sidebar-collapsed-icon');
}); });
afterEach(() => {
mock.restore();
});
it('should expand/collapse the sidebar when arrow is clicked', function() { it('should expand/collapse the sidebar when arrow is clicked', function() {
assertSidebarState('expanded'); assertSidebarState('expanded');
$toggle.click(); $toggle.click();
...@@ -63,20 +72,19 @@ import Sidebar from '~/right_sidebar'; ...@@ -63,20 +72,19 @@ import Sidebar from '~/right_sidebar';
return assertSidebarState('collapsed'); return assertSidebarState('collapsed');
}); });
it('should broadcast todo:toggle event when add todo clicked', function() { it('should broadcast todo:toggle event when add todo clicked', function(done) {
var todos = getJSONFixture('todos/todos.json'); var todos = getJSONFixture('todos/todos.json');
spyOn(jQuery, 'ajax').and.callFake(function() { mock.onPost(/(.*)\/todos$/).reply(200, todos);
var d = $.Deferred();
var response = todos;
d.resolve(response);
return d.promise();
});
var todoToggleSpy = spyOnEvent(document, 'todo:toggle'); var todoToggleSpy = spyOnEvent(document, 'todo:toggle');
$('.issuable-sidebar-header .js-issuable-todo').click(); $('.issuable-sidebar-header .js-issuable-todo').click();
setTimeout(() => {
expect(todoToggleSpy.calls.count()).toEqual(1); expect(todoToggleSpy.calls.count()).toEqual(1);
done();
});
}); });
it('should not hide collapsed icons', () => { it('should not hide collapsed icons', () => {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment