Commit 328e5e2e authored by Filipa Lacerda's avatar Filipa Lacerda

Merge branch 'ee-34534-switch-to-axios' into 'master'

Switch some bundles to use Axios --  EE merge edition

See merge request gitlab-org/gitlab-ee!3808
parents 81c6b660 b19db75a
/* eslint-disable no-new */ /* eslint-disable no-new */
import Vue from 'vue'; import Vue from 'vue';
import VueResource from 'vue-resource'; import axios from '../../lib/utils/axios_utils';
import notebookLab from '../../notebook/index.vue'; import notebookLab from '../../notebook/index.vue';
Vue.use(VueResource);
export default () => { export default () => {
const el = document.getElementById('js-notebook-viewer'); const el = document.getElementById('js-notebook-viewer');
...@@ -50,14 +48,14 @@ export default () => { ...@@ -50,14 +48,14 @@ export default () => {
`, `,
methods: { methods: {
loadFile() { loadFile() {
this.$http.get(el.dataset.endpoint) axios.get(el.dataset.endpoint)
.then(response => response.json()) .then(res => res.data)
.then((res) => { .then((data) => {
this.json = res; this.json = data;
this.loading = false; this.loading = false;
}) })
.catch((e) => { .catch((e) => {
if (e.status) { if (e.status !== 200) {
this.loadError = true; this.loadError = true;
} }
......
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
import _ from 'underscore'; import _ from 'underscore';
import Vue from 'vue'; import Vue from 'vue';
import VueResource from 'vue-resource';
import Flash from '../flash'; import Flash from '../flash';
import { __ } from '../locale'; import { __ } from '../locale';
import FilteredSearchBoards from './filtered_search_boards'; import FilteredSearchBoards from './filtered_search_boards';
...@@ -31,8 +30,6 @@ import collapseIcon from './icons/fullscreen_collapse.svg'; ...@@ -31,8 +30,6 @@ import collapseIcon from './icons/fullscreen_collapse.svg';
import expandIcon from './icons/fullscreen_expand.svg'; import expandIcon from './icons/fullscreen_expand.svg';
import tooltip from '../vue_shared/directives/tooltip'; import tooltip from '../vue_shared/directives/tooltip';
Vue.use(VueResource);
$(() => { $(() => {
const $boardApp = document.getElementById('board-app'); const $boardApp = document.getElementById('board-app');
const Store = gl.issueBoards.BoardsStore; const Store = gl.issueBoards.BoardsStore;
...@@ -104,9 +101,9 @@ $(() => { ...@@ -104,9 +101,9 @@ $(() => {
Store.disabled = this.disabled; Store.disabled = this.disabled;
gl.boardService.all() gl.boardService.all()
.then(response => response.json()) .then(res => res.data)
.then((resp) => { .then((data) => {
resp.forEach((board) => { data.forEach((board) => {
const list = Store.addList(board, this.defaultAvatar); const list = Store.addList(board, this.defaultAvatar);
if (list.type === 'closed') { if (list.type === 'closed') {
...@@ -123,7 +120,9 @@ $(() => { ...@@ -123,7 +120,9 @@ $(() => {
Store.addPromotionState(); Store.addPromotionState();
this.loading = false; this.loading = false;
}) })
.catch(() => new Flash('An error occurred. Please try again.')); .catch(() => {
Flash('An error occurred while fetching the board lists. Please try again.');
});
}, },
methods: { methods: {
updateTokens() { updateTokens() {
...@@ -135,7 +134,7 @@ $(() => { ...@@ -135,7 +134,7 @@ $(() => {
newIssue.setFetchingState('subscriptions', true); newIssue.setFetchingState('subscriptions', true);
newIssue.setFetchingState('weight', true); newIssue.setFetchingState('weight', true);
BoardService.getIssueInfo(sidebarInfoEndpoint) BoardService.getIssueInfo(sidebarInfoEndpoint)
.then(res => res.json()) .then(res => res.data)
.then((data) => { .then((data) => {
newIssue.setFetchingState('subscriptions', false); newIssue.setFetchingState('subscriptions', false);
newIssue.setFetchingState('weight', false); newIssue.setFetchingState('weight', false);
...@@ -178,7 +177,7 @@ $(() => { ...@@ -178,7 +177,7 @@ $(() => {
if (issue.id === id && issue.sidebarInfoEndpoint) { if (issue.id === id && issue.sidebarInfoEndpoint) {
issue.setLoadingState('weight', true); issue.setLoadingState('weight', true);
BoardService.updateWeight(issue.sidebarInfoEndpoint, newWeight) BoardService.updateWeight(issue.sidebarInfoEndpoint, newWeight)
.then(res => res.json()) .then(res => res.data)
.then((data) => { .then((data) => {
issue.setLoadingState('weight', false); issue.setLoadingState('weight', false);
issue.updateData({ issue.updateData({
......
...@@ -65,7 +65,7 @@ export default { ...@@ -65,7 +65,7 @@ export default {
// Save the labels // Save the labels
gl.boardService.generateDefaultLists() gl.boardService.generateDefaultLists()
.then(resp => resp.json()) .then(res => res.data)
.then((data) => { .then((data) => {
data.forEach((listObj) => { data.forEach((listObj) => {
const list = Store.findList('title', listObj.title); const list = Store.findList('title', listObj.title);
......
...@@ -147,7 +147,7 @@ export default { ...@@ -147,7 +147,7 @@ export default {
}); });
} else { } else {
gl.boardService.createBoard(this.board) gl.boardService.createBoard(this.board)
.then(resp => resp.json()) .then(resp => resp.data)
.then((data) => { .then((data) => {
visitUrl(data.board_path); visitUrl(data.board_path);
}) })
......
...@@ -92,7 +92,7 @@ import BoardForm from './board_form.vue'; ...@@ -92,7 +92,7 @@ import BoardForm from './board_form.vue';
if (this.open && !this.boards.length) { if (this.open && !this.boards.length) {
gl.boardService.allBoards() gl.boardService.allBoards()
.then(res => res.json()) .then(res => res.data)
.then((json) => { .then((json) => {
this.loading = false; this.loading = false;
this.boards = json; this.boards = json;
......
...@@ -89,7 +89,7 @@ gl.issueBoards.IssuesModal = Vue.extend({ ...@@ -89,7 +89,7 @@ gl.issueBoards.IssuesModal = Vue.extend({
page: this.page, page: this.page,
per: this.perPage, per: this.perPage,
})) }))
.then(resp => resp.json()) .then(res => res.data)
.then((data) => { .then((data) => {
if (clearIssues) { if (clearIssues) {
this.issues = []; this.issues = [];
......
...@@ -40,7 +40,7 @@ class List { ...@@ -40,7 +40,7 @@ class List {
save () { save () {
return gl.boardService.createList(this.label.id) return gl.boardService.createList(this.label.id)
.then(resp => resp.json()) .then(res => res.data)
.then((data) => { .then((data) => {
this.id = data.id; this.id = data.id;
this.type = data.list_type; this.type = data.list_type;
...@@ -90,7 +90,7 @@ class List { ...@@ -90,7 +90,7 @@ class List {
} }
return gl.boardService.getIssuesForList(this.id, data) return gl.boardService.getIssuesForList(this.id, data)
.then(resp => resp.json()) .then(res => res.data)
.then((data) => { .then((data) => {
this.loading = false; this.loading = false;
this.issuesSize = data.size; this.issuesSize = data.size;
...@@ -108,7 +108,7 @@ class List { ...@@ -108,7 +108,7 @@ class List {
this.issuesSize += 1; this.issuesSize += 1;
return gl.boardService.newIssue(this.id, issue) return gl.boardService.newIssue(this.id, issue)
.then(resp => resp.json()) .then(res => res.data)
.then((data) => { .then((data) => {
issue.id = data.id; issue.id = data.id;
issue.iid = data.iid; issue.iid = data.iid;
......
/* eslint-disable space-before-function-paren, comma-dangle, no-param-reassign, camelcase, max-len, no-unused-vars */ import axios from '../../lib/utils/axios_utils';
import { mergeUrlParams } from '../../lib/utils/url_utility';
import Vue from 'vue';
export default class BoardService { export default class BoardService {
constructor ({ boardsEndpoint, listsEndpoint, bulkUpdatePath, boardId }) { constructor({ boardsEndpoint, listsEndpoint, bulkUpdatePath, boardId }) {
this.boards = Vue.resource(`${boardsEndpoint}{/id}.json`, {}, { this.boardsEndpoint = boardsEndpoint;
issues: { this.boardId = boardId;
method: 'GET', this.listsEndpoint = listsEndpoint;
url: `${gon.relative_url_root}/-/boards/${boardId}/issues.json`, this.listsEndpointGenerate = `${listsEndpoint}/generate.json`;
this.bulkUpdatePath = bulkUpdatePath;
} }
});
this.lists = Vue.resource(`${listsEndpoint}{/id}`, {}, { generateBoardsPath(id) {
generate: { return `${this.boardsEndpoint}${id ? `/${id}` : ''}.json`;
method: 'POST',
url: `${listsEndpoint}/generate.json`
} }
});
this.issue = Vue.resource(`${gon.relative_url_root}/-/boards/${boardId}/issues{/id}`, {}); generateIssuesPath(id) {
this.issues = Vue.resource(`${listsEndpoint}{/id}/issues`, {}, { return `${this.listsEndpoint}${id ? `/${id}` : ''}/issues`;
bulkUpdate: {
method: 'POST',
url: bulkUpdatePath,
},
});
} }
allBoards () { static generateIssuePath(boardId, id) {
return this.boards.get(); return `${gon.relative_url_root}/-/boards/${boardId ? `/${boardId}` : ''}/issues${id ? `/${id}` : ''}`;
} }
createBoard (board) { allBoards() {
board.label_ids = (board.labels || []).map(b => b.id); return axios.get(this.generateBoardsPath());
}
createBoard(board) {
const boardPayload = { ...board };
boardPayload.label_ids = (board.labels || []).map(b => b.id);
if (board.label_ids.length === 0) { if (boardPayload.label_ids.length === 0) {
board.label_ids = ['']; boardPayload.label_ids = [''];
} }
if (board.assignee) { if (boardPayload.assignee) {
board.assignee_id = board.assignee.id; boardPayload.assignee_id = boardPayload.assignee.id;
} }
if (board.milestone) { if (boardPayload.milestone) {
board.milestone_id = board.milestone.id; boardPayload.milestone_id = boardPayload.milestone.id;
} }
if (board.id) { if (boardPayload.id) {
return this.boards.update({ id: board.id }, { board }); return axios.put(this.generateBoardsPath(boardPayload.id), { board: boardPayload });
} }
return this.boards.save({}, { board }); return axios.post(this.generateBoardsPath(), { board: boardPayload });
} }
deleteBoard ({ id }) { deleteBoard({ id }) {
return this.boards.delete({ id }); return axios.delete(this.generateBoardsPath(id));
} }
all () { all() {
return this.lists.get(); return axios.get(this.listsEndpoint);
} }
generateDefaultLists () { generateDefaultLists() {
return this.lists.generate({}); return axios.post(this.listsEndpointGenerate, {});
} }
createList (label_id) { createList(labelId) {
return this.lists.save({}, { return axios.post(this.listsEndpoint, {
list: { list: {
label_id label_id: labelId,
} },
}); });
} }
updateList (id, position) { updateList(id, position) {
return this.lists.update({ id }, { return axios.put(`${this.listsEndpoint}/${id}`, {
list: { list: {
position position,
} },
}); });
} }
destroyList (id) { destroyList(id) {
return this.lists.delete({ id }); return axios.delete(`${this.listsEndpoint}/${id}`);
} }
getIssuesForList (id, filter = {}) { getIssuesForList(id, filter = {}) {
const data = { id }; const data = { id };
Object.keys(filter).forEach((key) => { data[key] = filter[key]; }); Object.keys(filter).forEach((key) => { data[key] = filter[key]; });
return this.issues.get(data); return axios.get(mergeUrlParams(data, this.generateIssuesPath(id)));
} }
moveIssue (id, from_list_id = null, to_list_id = null, move_before_id = null, move_after_id = null) { moveIssue(id, fromListId = null, toListId = null, moveBeforeId = null, moveAfterId = null) {
return this.issue.update({ id }, { return axios.put(BoardService.generateIssuePath(this.boardId, id), {
from_list_id, from_list_id: fromListId,
to_list_id, to_list_id: toListId,
move_before_id, move_before_id: moveBeforeId,
move_after_id, move_after_id: moveAfterId,
}); });
} }
newIssue (id, issue) { newIssue(id, issue) {
return this.issues.save({ id }, { return axios.post(this.generateIssuesPath(id), {
issue issue,
}); });
} }
getBacklog(data) { getBacklog(data) {
return this.boards.issues(data); return axios.get(mergeUrlParams(data, `${gon.relative_url_root}/-/boards/${this.boardId}/issues.json`));
} }
bulkUpdate(issueIds, extraData = {}) { bulkUpdate(issueIds, extraData = {}) {
...@@ -115,23 +113,21 @@ export default class BoardService { ...@@ -115,23 +113,21 @@ export default class BoardService {
}), }),
}; };
return this.issues.bulkUpdate(data); return axios.post(this.bulkUpdatePath, data);
} }
static getIssueInfo(endpoint) { static getIssueInfo(endpoint) {
return Vue.http.get(endpoint); return axios.get(endpoint);
} }
static updateWeight(endpoint, weight = null) { static updateWeight(endpoint, weight = null) {
return Vue.http.put(endpoint, { return axios.put(endpoint, {
'issue[weight]': weight, weight,
}, {
emulateJSON: true,
}); });
} }
static toggleIssueSubscription(endpoint) { static toggleIssueSubscription(endpoint) {
return Vue.http.post(endpoint); return axios.post(endpoint);
} }
} }
......
...@@ -172,8 +172,8 @@ export default { ...@@ -172,8 +172,8 @@ export default {
}, },
updateIssuable() { updateIssuable() {
this.service.updateIssuable(this.store.formState) return this.service.updateIssuable(this.store.formState)
.then(res => res.json()) .then(res => res.data)
.then(data => this.checkForSpam(data)) .then(data => this.checkForSpam(data))
.then((data) => { .then((data) => {
if (location.pathname !== data.web_url) { if (location.pathname !== data.web_url) {
...@@ -182,7 +182,7 @@ export default { ...@@ -182,7 +182,7 @@ export default {
return this.service.getData(); return this.service.getData();
}) })
.then(res => res.json()) .then(res => res.data)
.then((data) => { .then((data) => {
this.store.updateState(data); this.store.updateState(data);
eventHub.$emit('close.form'); eventHub.$emit('close.form');
...@@ -207,7 +207,7 @@ export default { ...@@ -207,7 +207,7 @@ export default {
deleteIssuable() { deleteIssuable() {
this.service.deleteIssuable() this.service.deleteIssuable()
.then(res => res.json()) .then(res => res.data)
.then((data) => { .then((data) => {
// Stop the poll so we don't get 404's with the issuable not existing // Stop the poll so we don't get 404's with the issuable not existing
this.poll.stop(); this.poll.stop();
...@@ -225,7 +225,7 @@ export default { ...@@ -225,7 +225,7 @@ export default {
this.poll = new Poll({ this.poll = new Poll({
resource: this.service, resource: this.service,
method: 'getData', method: 'getData',
successCallback: res => res.json().then(data => this.store.updateState(data)), successCallback: res => this.store.updateState(res.data),
errorCallback(err) { errorCallback(err) {
throw new Error(err); throw new Error(err);
}, },
......
import Vue from 'vue'; import axios from '../../lib/utils/axios_utils';
import VueResource from 'vue-resource';
Vue.use(VueResource);
export default class Service { export default class Service {
constructor(endpoint) { constructor(endpoint) {
this.endpoint = endpoint; this.endpoint = `${endpoint}.json`;
this.realtimeEndpoint = `${endpoint}/realtime_changes`;
this.resource = Vue.resource(`${this.endpoint}.json`, {}, {
realtimeChanges: {
method: 'GET',
url: `${this.endpoint}/realtime_changes`,
},
});
} }
getData() { getData() {
return this.resource.realtimeChanges(); return axios.get(this.realtimeEndpoint);
} }
deleteIssuable() { deleteIssuable() {
return this.resource.delete(); return axios.delete(this.endpoint);
} }
updateIssuable(data) { updateIssuable(data) {
return this.resource.update(data); return axios.put(this.endpoint, data);
} }
} }
...@@ -232,7 +232,7 @@ export const nodeMatchesSelector = (node, selector) => { ...@@ -232,7 +232,7 @@ export const nodeMatchesSelector = (node, selector) => {
export const normalizeHeaders = (headers) => { export const normalizeHeaders = (headers) => {
const upperCaseHeaders = {}; const upperCaseHeaders = {};
Object.keys(headers).forEach((e) => { Object.keys(headers || {}).forEach((e) => {
upperCaseHeaders[e.toUpperCase()] = headers[e]; upperCaseHeaders[e.toUpperCase()] = headers[e];
}); });
......
...@@ -18,7 +18,7 @@ export function getParameterValues(sParam) { ...@@ -18,7 +18,7 @@ export function getParameterValues(sParam) {
// @param {String} url // @param {String} url
export function mergeUrlParams(params, url) { export function mergeUrlParams(params, url) {
let newUrl = Object.keys(params).reduce((acc, paramName) => { let newUrl = Object.keys(params).reduce((acc, paramName) => {
const paramValue = params[paramName]; const paramValue = encodeURIComponent(params[paramName]);
const pattern = new RegExp(`\\b(${paramName}=).*?(&|$)`); const pattern = new RegExp(`\\b(${paramName}=).*?(&|$)`);
if (paramValue === null) { if (paramValue === null) {
......
...@@ -34,10 +34,10 @@ export default { ...@@ -34,10 +34,10 @@ export default {
if (isConfirmed) { if (isConfirmed) {
MRWidgetService.stopEnvironment(deployment.stop_url) MRWidgetService.stopEnvironment(deployment.stop_url)
.then(res => res.json()) .then(res => res.data)
.then((res) => { .then((data) => {
if (res.redirect_url) { if (data.redirect_url) {
visitUrl(res.redirect_url); visitUrl(data.redirect_url);
} }
}) })
.catch(() => { .catch(() => {
......
...@@ -102,11 +102,11 @@ export default { ...@@ -102,11 +102,11 @@ export default {
return res; return res;
} }
return res.json(); return res.data;
}) })
.then((res) => { .then((data) => {
this.computeGraphData(res.metrics, res.deployment_time); this.computeGraphData(data.metrics, data.deployment_time);
return res; return data;
}) })
.catch(() => { .catch(() => {
this.loadFailed = true; this.loadFailed = true;
......
...@@ -31,9 +31,9 @@ export default { ...@@ -31,9 +31,9 @@ export default {
cancelAutomaticMerge() { cancelAutomaticMerge() {
this.isCancellingAutoMerge = true; this.isCancellingAutoMerge = true;
this.service.cancelAutomaticMerge() this.service.cancelAutomaticMerge()
.then(res => res.json()) .then(res => res.data)
.then((res) => { .then((data) => {
eventHub.$emit('UpdateWidgetData', res); eventHub.$emit('UpdateWidgetData', data);
}) })
.catch(() => { .catch(() => {
this.isCancellingAutoMerge = false; this.isCancellingAutoMerge = false;
...@@ -49,9 +49,9 @@ export default { ...@@ -49,9 +49,9 @@ export default {
this.isRemovingSourceBranch = true; this.isRemovingSourceBranch = true;
this.service.mergeResource.save(options) this.service.mergeResource.save(options)
.then(res => res.json()) .then(res => res.data)
.then((res) => { .then((data) => {
if (res.status === 'merge_when_pipeline_succeeds') { if (data.status === 'merge_when_pipeline_succeeds') {
eventHub.$emit('MRWidgetUpdateRequested'); eventHub.$emit('MRWidgetUpdateRequested');
} }
}) })
......
...@@ -47,9 +47,9 @@ export default { ...@@ -47,9 +47,9 @@ export default {
removeSourceBranch() { removeSourceBranch() {
this.isMakingRequest = true; this.isMakingRequest = true;
this.service.removeSourceBranch() this.service.removeSourceBranch()
.then(res => res.json()) .then(res => res.data)
.then((res) => { .then((data) => {
if (res.message === 'Branch was removed') { if (data.message === 'Branch was removed') {
eventHub.$emit('MRWidgetUpdateRequested', () => { eventHub.$emit('MRWidgetUpdateRequested', () => {
this.isMakingRequest = false; this.isMakingRequest = false;
}); });
......
...@@ -139,16 +139,16 @@ export default { ...@@ -139,16 +139,16 @@ export default {
this.isMakingRequest = true; this.isMakingRequest = true;
this.service.merge(options) this.service.merge(options)
.then(res => res.json()) .then(res => res.data)
.then((res) => { .then((data) => {
const hasError = res.status === 'failed' || res.status === 'hook_validation_error'; const hasError = data.status === 'failed' || data.status === 'hook_validation_error';
if (res.status === 'merge_when_pipeline_succeeds') { if (data.status === 'merge_when_pipeline_succeeds') {
eventHub.$emit('MRWidgetUpdateRequested'); eventHub.$emit('MRWidgetUpdateRequested');
} else if (res.status === 'success') { } else if (data.status === 'success') {
this.initiateMergePolling(); this.initiateMergePolling();
} else if (hasError) { } else if (hasError) {
eventHub.$emit('FailedToMerge', res.merge_error); eventHub.$emit('FailedToMerge', data.merge_error);
} }
}) })
.catch(() => { .catch(() => {
...@@ -163,9 +163,9 @@ export default { ...@@ -163,9 +163,9 @@ export default {
}, },
handleMergePolling(continuePolling, stopPolling) { handleMergePolling(continuePolling, stopPolling) {
this.service.poll() this.service.poll()
.then(res => res.json()) .then(res => res.data)
.then((res) => { .then((data) => {
if (res.state === 'merged') { if (data.state === 'merged') {
// If state is merged we should update the widget and stop the polling // If state is merged we should update the widget and stop the polling
eventHub.$emit('MRWidgetUpdateRequested'); eventHub.$emit('MRWidgetUpdateRequested');
eventHub.$emit('FetchActionsContent'); eventHub.$emit('FetchActionsContent');
...@@ -178,11 +178,11 @@ export default { ...@@ -178,11 +178,11 @@ export default {
// If user checked remove source branch and we didn't remove the branch yet // If user checked remove source branch and we didn't remove the branch yet
// we should start another polling for source branch remove process // we should start another polling for source branch remove process
if (this.removeSourceBranch && res.source_branch_exists) { if (this.removeSourceBranch && data.source_branch_exists) {
this.initiateRemoveSourceBranchPolling(); this.initiateRemoveSourceBranchPolling();
} }
} else if (res.merge_error) { } else if (data.merge_error) {
eventHub.$emit('FailedToMerge', res.merge_error); eventHub.$emit('FailedToMerge', data.merge_error);
stopPolling(); stopPolling();
} else { } else {
// MR is not merged yet, continue polling until the state becomes 'merged' // MR is not merged yet, continue polling until the state becomes 'merged'
...@@ -203,11 +203,11 @@ export default { ...@@ -203,11 +203,11 @@ export default {
}, },
handleRemoveBranchPolling(continuePolling, stopPolling) { handleRemoveBranchPolling(continuePolling, stopPolling) {
this.service.poll() this.service.poll()
.then(res => res.json()) .then(res => res.data)
.then((res) => { .then((data) => {
// If source branch exists then we should continue polling // If source branch exists then we should continue polling
// because removing a source branch is a background task and takes time // because removing a source branch is a background task and takes time
if (res.source_branch_exists) { if (data.source_branch_exists) {
continuePolling(); continuePolling();
} else { } else {
// Branch is removed. Update widget, stop polling and hide the spinner // Branch is removed. Update widget, stop polling and hide the spinner
......
...@@ -23,9 +23,9 @@ export default { ...@@ -23,9 +23,9 @@ export default {
removeWIP() { removeWIP() {
this.isMakingRequest = true; this.isMakingRequest = true;
this.service.removeWIP() this.service.removeWIP()
.then(res => res.json()) .then(res => res.data)
.then((res) => { .then((data) => {
eventHub.$emit('UpdateWidgetData', res); eventHub.$emit('UpdateWidgetData', data);
new window.Flash('The merge request can now be merged.', 'notice'); // eslint-disable-line new window.Flash('The merge request can now be merged.', 'notice'); // eslint-disable-line
$('.merge-request .detail-page-description .title').text(this.mr.title); $('.merge-request .detail-page-description .title').text(this.mr.title);
}) })
......
...@@ -86,14 +86,14 @@ export default { ...@@ -86,14 +86,14 @@ export default {
}, },
checkStatus(cb) { checkStatus(cb) {
return this.service.checkStatus() return this.service.checkStatus()
.then(res => res.json()) .then(res => res.data)
.then((res) => { .then((data) => {
this.handleNotification(res); this.handleNotification(data);
this.mr.setData(res); this.mr.setData(data);
this.setFaviconHelper(); this.setFaviconHelper();
if (cb) { if (cb) {
cb.call(null, res); cb.call(null, data);
} }
}) })
.catch(() => new Flash('Something went wrong. Please try again.')); .catch(() => new Flash('Something went wrong. Please try again.'));
...@@ -124,10 +124,10 @@ export default { ...@@ -124,10 +124,10 @@ export default {
}, },
fetchDeployments() { fetchDeployments() {
return this.service.fetchDeployments() return this.service.fetchDeployments()
.then(res => res.json()) .then(res => res.data)
.then((res) => { .then((data) => {
if (res.length) { if (data.length) {
this.mr.deployments = res; this.mr.deployments = data;
} }
}) })
.catch(() => { .catch(() => {
...@@ -137,9 +137,9 @@ export default { ...@@ -137,9 +137,9 @@ export default {
fetchActionsContent() { fetchActionsContent() {
this.service.fetchMergeActionsContent() this.service.fetchMergeActionsContent()
.then((res) => { .then((res) => {
if (res.body) { if (res.data) {
const el = document.createElement('div'); const el = document.createElement('div');
el.innerHTML = res.body; el.innerHTML = res.data;
document.body.appendChild(el); document.body.appendChild(el);
Project.initRefSwitcher(); Project.initRefSwitcher();
} }
......
import Vue from 'vue'; import axios from '../../lib/utils/axios_utils';
import VueResource from 'vue-resource';
Vue.use(VueResource);
export default class MRWidgetService { export default class MRWidgetService {
constructor(endpoints) { constructor(endpoints) {
this.mergeResource = Vue.resource(endpoints.mergePath); this.endpoints = endpoints;
this.mergeCheckResource = Vue.resource(`${endpoints.statusPath}?serializer=widget`);
this.cancelAutoMergeResource = Vue.resource(endpoints.cancelAutoMergePath);
this.removeWIPResource = Vue.resource(endpoints.removeWIPPath);
this.removeSourceBranchResource = Vue.resource(endpoints.sourceBranchPath);
this.deploymentsResource = Vue.resource(endpoints.ciEnvironmentsStatusPath);
this.pollResource = Vue.resource(`${endpoints.statusPath}?serializer=basic`);
this.mergeActionsContentResource = Vue.resource(endpoints.mergeActionsContentPath);
} }
merge(data) { merge(data) {
return this.mergeResource.save(data); return axios.post(this.endpoints.mergePath, data);
} }
cancelAutomaticMerge() { cancelAutomaticMerge() {
return this.cancelAutoMergeResource.save(); return axios.post(this.endpoints.cancelAutoMergePath);
} }
removeWIP() { removeWIP() {
return this.removeWIPResource.save(); return axios.post(this.endpoints.removeWIPPath);
} }
removeSourceBranch() { removeSourceBranch() {
return this.removeSourceBranchResource.delete(); return axios.delete(this.endpoints.sourceBranchPath);
} }
fetchDeployments() { fetchDeployments() {
return this.deploymentsResource.get(); return axios.get(this.endpoints.ciEnvironmentsStatusPath);
} }
poll() { poll() {
return this.pollResource.get(); return axios.get(`${this.endpoints.statusPath}?serializer=basic`);
} }
checkStatus() { checkStatus() {
return this.mergeCheckResource.get(); return axios.get(`${this.endpoints.statusPath}?serializer=widget`);
} }
fetchMergeActionsContent() { fetchMergeActionsContent() {
return this.mergeActionsContentResource.get(); return axios.get(this.endpoints.mergeActionsContentPath);
} }
static stopEnvironment(url) { static stopEnvironment(url) {
return Vue.http.post(url); return axios.post(url);
} }
static fetchMetrics(metricsUrl) { static fetchMetrics(metricsUrl) {
return Vue.http.get(`${metricsUrl}.json`); return axios.get(`${metricsUrl}.json`);
} }
} }
---
title: Fix some POST/DELETE requests in IE by switching some bundles to Axios for Ajax requests
merge_request: 15951
author:
type: fixed
import Vue from 'vue'; import MockAdapter from 'axios-mock-adapter';
import axios from '~/lib/utils/axios_utils';
import renderNotebook from '~/blob/notebook'; import renderNotebook from '~/blob/notebook';
describe('iPython notebook renderer', () => { describe('iPython notebook renderer', () => {
...@@ -17,8 +18,11 @@ describe('iPython notebook renderer', () => { ...@@ -17,8 +18,11 @@ describe('iPython notebook renderer', () => {
}); });
describe('successful response', () => { describe('successful response', () => {
const response = (request, next) => { let mock;
next(request.respondWith(JSON.stringify({
beforeEach((done) => {
mock = new MockAdapter(axios);
mock.onGet('/test').reply(200, {
cells: [{ cells: [{
cell_type: 'markdown', cell_type: 'markdown',
source: ['# test'], source: ['# test'],
...@@ -31,13 +35,7 @@ describe('iPython notebook renderer', () => { ...@@ -31,13 +35,7 @@ describe('iPython notebook renderer', () => {
], ],
outputs: [], outputs: [],
}], }],
}), { });
status: 200,
}));
};
beforeEach((done) => {
Vue.http.interceptors.push(response);
renderNotebook(); renderNotebook();
...@@ -47,9 +45,7 @@ describe('iPython notebook renderer', () => { ...@@ -47,9 +45,7 @@ describe('iPython notebook renderer', () => {
}); });
afterEach(() => { afterEach(() => {
Vue.http.interceptors = _.without( mock.reset();
Vue.http.interceptors, response,
);
}); });
it('does not show loading icon', () => { it('does not show loading icon', () => {
...@@ -86,14 +82,11 @@ describe('iPython notebook renderer', () => { ...@@ -86,14 +82,11 @@ describe('iPython notebook renderer', () => {
}); });
describe('error in JSON response', () => { describe('error in JSON response', () => {
const response = (request, next) => { let mock;
next(request.respondWith('{ "cells": [{"cell_type": "markdown"} }', {
status: 200,
}));
};
beforeEach((done) => { beforeEach((done) => {
Vue.http.interceptors.push(response); mock = new MockAdapter(axios);
mock.onGet('/test').reply(() => Promise.reject({ status: 200, data: '{ "cells": [{"cell_type": "markdown"} }' }));
renderNotebook(); renderNotebook();
...@@ -103,9 +96,7 @@ describe('iPython notebook renderer', () => { ...@@ -103,9 +96,7 @@ describe('iPython notebook renderer', () => {
}); });
afterEach(() => { afterEach(() => {
Vue.http.interceptors = _.without( mock.reset();
Vue.http.interceptors, response,
);
}); });
it('does not show loading icon', () => { it('does not show loading icon', () => {
...@@ -122,14 +113,11 @@ describe('iPython notebook renderer', () => { ...@@ -122,14 +113,11 @@ describe('iPython notebook renderer', () => {
}); });
describe('error getting file', () => { describe('error getting file', () => {
const response = (request, next) => { let mock;
next(request.respondWith('', {
status: 500,
}));
};
beforeEach((done) => { beforeEach((done) => {
Vue.http.interceptors.push(response); mock = new MockAdapter(axios);
mock.onGet('/test').reply(500, '');
renderNotebook(); renderNotebook();
...@@ -139,9 +127,7 @@ describe('iPython notebook renderer', () => { ...@@ -139,9 +127,7 @@ describe('iPython notebook renderer', () => {
}); });
afterEach(() => { afterEach(() => {
Vue.http.interceptors = _.without( mock.reset();
Vue.http.interceptors, response,
);
}); });
it('does not show loading icon', () => { it('does not show loading icon', () => {
......
/* global BoardService */ /* global BoardService */
/* global mockBoardService */
import Vue from 'vue'; import Vue from 'vue';
import '~/boards/stores/boards_store'; import '~/boards/stores/boards_store';
import boardBlankState from '~/boards/components/board_blank_state'; import boardBlankState from '~/boards/components/board_blank_state';
import './mock_data'; import { mockBoardService } from './mock_data';
describe('Boards blank state', () => { describe('Boards blank state', () => {
let vm; let vm;
...@@ -20,8 +19,7 @@ describe('Boards blank state', () => { ...@@ -20,8 +19,7 @@ describe('Boards blank state', () => {
reject(); reject();
} else { } else {
resolve({ resolve({
json() { data: [{
return [{
id: 1, id: 1,
title: 'To Do', title: 'To Do',
label: { id: 1 }, label: { id: 1 },
...@@ -29,8 +27,7 @@ describe('Boards blank state', () => { ...@@ -29,8 +27,7 @@ describe('Boards blank state', () => {
id: 2, id: 2,
title: 'Doing', title: 'Doing',
label: { id: 2 }, label: { id: 2 },
}]; }],
},
}); });
} }
})); }));
......
/* global List */ /* global List */
/* global ListAssignee */ /* global ListAssignee */
/* global ListLabel */ /* global ListLabel */
/* global listObj */
/* global boardsMockInterceptor */
/* global BoardService */ /* global BoardService */
/* global mockBoardService */
import Vue from 'vue'; import Vue from 'vue';
import MockAdapter from 'axios-mock-adapter';
import axios from '~/lib/utils/axios_utils';
import '~/boards/models/assignee'; import '~/boards/models/assignee';
import eventHub from '~/boards/eventhub'; import eventHub from '~/boards/eventhub';
...@@ -14,13 +13,15 @@ import '~/boards/models/list'; ...@@ -14,13 +13,15 @@ import '~/boards/models/list';
import '~/boards/models/label'; import '~/boards/models/label';
import '~/boards/stores/boards_store'; import '~/boards/stores/boards_store';
import boardCard from '~/boards/components/board_card.vue'; import boardCard from '~/boards/components/board_card.vue';
import './mock_data'; import { listObj, boardsMockInterceptor, mockBoardService } from './mock_data';
describe('Board card', () => { describe('Board card', () => {
let vm; let vm;
let mock;
beforeEach((done) => { beforeEach((done) => {
Vue.http.interceptors.push(boardsMockInterceptor); mock = new MockAdapter(axios);
mock.onAny().reply(boardsMockInterceptor);
gl.boardService = mockBoardService(); gl.boardService = mockBoardService();
gl.issueBoards.BoardsStore.create(); gl.issueBoards.BoardsStore.create();
...@@ -54,7 +55,7 @@ describe('Board card', () => { ...@@ -54,7 +55,7 @@ describe('Board card', () => {
}); });
afterEach(() => { afterEach(() => {
Vue.http.interceptors = _.without(Vue.http.interceptors, boardsMockInterceptor); mock.reset();
}); });
it('returns false when detailIssue is empty', () => { it('returns false when detailIssue is empty', () => {
......
/* global BoardService */ /* global BoardService */
/* global boardsMockInterceptor */
/* global List */ /* global List */
/* global listObj */
/* global ListIssue */ /* global ListIssue */
/* global mockBoardService */
import Vue from 'vue'; import Vue from 'vue';
import _ from 'underscore'; import MockAdapter from 'axios-mock-adapter';
import axios from '~/lib/utils/axios_utils';
import Sortable from 'vendor/Sortable'; import Sortable from 'vendor/Sortable';
import BoardList from '~/boards/components/board_list'; import BoardList from '~/boards/components/board_list';
import eventHub from '~/boards/eventhub'; import eventHub from '~/boards/eventhub';
...@@ -13,18 +11,20 @@ import '~/boards/mixins/sortable_default_options'; ...@@ -13,18 +11,20 @@ import '~/boards/mixins/sortable_default_options';
import '~/boards/models/issue'; import '~/boards/models/issue';
import '~/boards/models/list'; import '~/boards/models/list';
import '~/boards/stores/boards_store'; import '~/boards/stores/boards_store';
import './mock_data'; import { listObj, boardsMockInterceptor, mockBoardService } from './mock_data';
window.Sortable = Sortable; window.Sortable = Sortable;
describe('Board list component', () => { describe('Board list component', () => {
let mock;
let component; let component;
beforeEach((done) => { beforeEach((done) => {
const el = document.createElement('div'); const el = document.createElement('div');
document.body.appendChild(el); document.body.appendChild(el);
Vue.http.interceptors.push(boardsMockInterceptor); mock = new MockAdapter(axios);
mock.onAny().reply(boardsMockInterceptor);
gl.boardService = mockBoardService(); gl.boardService = mockBoardService();
gl.issueBoards.BoardsStore.create(); gl.issueBoards.BoardsStore.create();
gl.IssueBoardsApp = new Vue(); gl.IssueBoardsApp = new Vue();
...@@ -60,7 +60,7 @@ describe('Board list component', () => { ...@@ -60,7 +60,7 @@ describe('Board list component', () => {
}); });
afterEach(() => { afterEach(() => {
Vue.http.interceptors = _.without(Vue.http.interceptors, boardsMockInterceptor); mock.reset();
}); });
it('renders component', () => { it('renders component', () => {
......
/* global boardsMockInterceptor */
/* global BoardService */ /* global BoardService */
/* global mockBoardService */
/* global List */ /* global List */
/* global listObj */
/* global mockBoardService */
import Vue from 'vue'; import Vue from 'vue';
import MockAdapter from 'axios-mock-adapter';
import axios from '~/lib/utils/axios_utils';
import boardNewIssue from '~/boards/components/board_new_issue'; import boardNewIssue from '~/boards/components/board_new_issue';
import '~/boards/models/list'; import '~/boards/models/list';
import './mock_data'; import { listObj, boardsMockInterceptor, mockBoardService } from './mock_data';
describe('Issue boards new issue form', () => { describe('Issue boards new issue form', () => {
let vm; let vm;
let list; let list;
let mock;
let newIssueMock; let newIssueMock;
const promiseReturn = { const promiseReturn = {
json() { data: {
return {
iid: 100, iid: 100,
};
}, },
}; };
...@@ -36,7 +33,9 @@ describe('Issue boards new issue form', () => { ...@@ -36,7 +33,9 @@ describe('Issue boards new issue form', () => {
const BoardNewIssueComp = Vue.extend(boardNewIssue); const BoardNewIssueComp = Vue.extend(boardNewIssue);
Vue.http.interceptors.push(boardsMockInterceptor); mock = new MockAdapter(axios);
mock.onAny().reply(boardsMockInterceptor);
gl.boardService = mockBoardService(); gl.boardService = mockBoardService();
gl.issueBoards.BoardsStore.create(); gl.issueBoards.BoardsStore.create();
gl.IssueBoardsApp = new Vue(); gl.IssueBoardsApp = new Vue();
...@@ -57,7 +56,10 @@ describe('Issue boards new issue form', () => { ...@@ -57,7 +56,10 @@ describe('Issue boards new issue form', () => {
.catch(done.fail); .catch(done.fail);
}); });
afterEach(() => vm.$destroy()); afterEach(() => {
vm.$destroy();
mock.reset();
});
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()); spyOn(vm, 'submit').and.callFake(e => e.preventDefault());
......
/* eslint-disable comma-dangle, one-var, no-unused-vars */ /* eslint-disable comma-dangle, one-var, no-unused-vars */
/* global BoardService */ /* global BoardService */
/* global boardsMockInterceptor */
/* global listObj */
/* global listObjDuplicate */
/* global ListIssue */ /* global ListIssue */
/* global mockBoardService */
import Vue from 'vue'; import Vue from 'vue';
import MockAdapter from 'axios-mock-adapter';
import axios from '~/lib/utils/axios_utils';
import Cookies from 'js-cookie'; import Cookies from 'js-cookie';
import '~/boards/models/issue'; import '~/boards/models/issue';
import '~/boards/models/label'; import '~/boards/models/label';
...@@ -14,11 +12,14 @@ import '~/boards/models/list'; ...@@ -14,11 +12,14 @@ import '~/boards/models/list';
import '~/boards/models/assignee'; import '~/boards/models/assignee';
import '~/boards/services/board_service'; import '~/boards/services/board_service';
import '~/boards/stores/boards_store'; import '~/boards/stores/boards_store';
import './mock_data'; import { listObj, listObjDuplicate, boardsMockInterceptor, mockBoardService } from './mock_data';
describe('Store', () => { describe('Store', () => {
let mock;
beforeEach(() => { beforeEach(() => {
Vue.http.interceptors.push(boardsMockInterceptor); mock = new MockAdapter(axios);
mock.onAny().reply(boardsMockInterceptor);
gl.boardService = mockBoardService(); gl.boardService = mockBoardService();
gl.issueBoards.BoardsStore.create(); gl.issueBoards.BoardsStore.create();
...@@ -33,7 +34,7 @@ describe('Store', () => { ...@@ -33,7 +34,7 @@ describe('Store', () => {
}); });
afterEach(() => { afterEach(() => {
Vue.http.interceptors = _.without(Vue.http.interceptors, boardsMockInterceptor); mock.reset();
}); });
it('starts with a blank state', () => { it('starts with a blank state', () => {
......
/* global boardsMockInterceptor */
/* global boardObj */
/* global BoardService */ /* global BoardService */
/* global mockBoardService */
import Vue from 'vue'; import Vue from 'vue';
import AssigneeSelect from '~/boards/components/assignee_select.vue'; import AssigneeSelect from '~/boards/components/assignee_select.vue';
import '~/boards/services/board_service'; import '~/boards/services/board_service';
import '~/boards/stores/boards_store'; import '~/boards/stores/boards_store';
import IssuableContext from '~/issuable_context'; import IssuableContext from '~/issuable_context';
import { boardObj, mockBoardService } from '../mock_data';
let vm; let vm;
......
/* global mockBoardService */
import Vue from 'vue'; import Vue from 'vue';
import '~/boards/services/board_service'; import '~/boards/services/board_service';
import '~/boards/components/board'; import '~/boards/components/board';
import '~/boards/models/list'; import '~/boards/models/list';
import '../mock_data'; import { mockBoardService } from '../mock_data';
describe('Board component', () => { describe('Board component', () => {
let vm; let vm;
......
...@@ -42,9 +42,7 @@ describe('BoardsSelector', () => { ...@@ -42,9 +42,7 @@ describe('BoardsSelector', () => {
}); });
boardServiceResponse = Promise.resolve({ boardServiceResponse = Promise.resolve({
json() { data: boards,
return boards;
},
}); });
spyOn(BoardService.prototype, 'allBoards').and.returnValue(boardServiceResponse); spyOn(BoardService.prototype, 'allBoards').and.returnValue(boardServiceResponse);
......
/* global boardsMockInterceptor */
/* global BoardService */ /* global BoardService */
import Vue from 'vue'; import Vue from 'vue';
import '~/labels_select'; import '~/labels_select';
import LabelsSelect from '~/boards/components/labels_select.vue'; import LabelsSelect from '~/boards/components/labels_select.vue';
import IssuableContext from '~/issuable_context'; import IssuableContext from '~/issuable_context';
import '../mock_data';
let vm; let vm;
......
/* global ListAssignee */ /* global ListAssignee */
/* global ListLabel */ /* global ListLabel */
/* global listObj */
/* global ListIssue */ /* global ListIssue */
import Vue from 'vue'; import Vue from 'vue';
...@@ -11,7 +10,7 @@ import '~/boards/models/list'; ...@@ -11,7 +10,7 @@ import '~/boards/models/list';
import '~/boards/models/assignee'; import '~/boards/models/assignee';
import '~/boards/stores/boards_store'; import '~/boards/stores/boards_store';
import '~/boards/components/issue_card_inner'; import '~/boards/components/issue_card_inner';
import './mock_data'; import { listObj } from './mock_data';
describe('Issue card component', () => { describe('Issue card component', () => {
const user = new ListAssignee({ const user = new ListAssignee({
......
/* eslint-disable comma-dangle */ /* eslint-disable comma-dangle */
/* global BoardService */ /* global BoardService */
/* global ListIssue */ /* global ListIssue */
/* global mockBoardService */
import Vue from 'vue'; import Vue from 'vue';
import '~/boards/models/issue'; import '~/boards/models/issue';
...@@ -10,7 +9,7 @@ import '~/boards/models/list'; ...@@ -10,7 +9,7 @@ import '~/boards/models/list';
import '~/boards/models/assignee'; import '~/boards/models/assignee';
import '~/boards/services/board_service'; import '~/boards/services/board_service';
import '~/boards/stores/boards_store'; import '~/boards/stores/boards_store';
import './mock_data'; import { mockBoardService } from './mock_data';
describe('Issue model', () => { describe('Issue model', () => {
let issue; let issue;
......
/* eslint-disable comma-dangle */ /* eslint-disable comma-dangle */
/* global boardsMockInterceptor */
/* global BoardService */ /* global BoardService */
/* global mockBoardService */
/* global List */ /* global List */
/* global ListIssue */ /* global ListIssue */
/* global listObj */
/* global listObjDuplicate */
import Vue from 'vue'; import MockAdapter from 'axios-mock-adapter';
import axios from '~/lib/utils/axios_utils';
import '~/boards/models/issue'; import '~/boards/models/issue';
import '~/boards/models/label'; import '~/boards/models/label';
...@@ -15,13 +12,15 @@ import '~/boards/models/list'; ...@@ -15,13 +12,15 @@ import '~/boards/models/list';
import '~/boards/models/assignee'; import '~/boards/models/assignee';
import '~/boards/services/board_service'; import '~/boards/services/board_service';
import '~/boards/stores/boards_store'; import '~/boards/stores/boards_store';
import './mock_data'; import { listObj, listObjDuplicate, boardsMockInterceptor, mockBoardService } from './mock_data';
describe('List model', () => { describe('List model', () => {
let list; let list;
let mock;
beforeEach(() => { beforeEach(() => {
Vue.http.interceptors.push(boardsMockInterceptor); mock = new MockAdapter(axios);
mock.onAny().reply(boardsMockInterceptor);
gl.boardService = mockBoardService({ gl.boardService = mockBoardService({
bulkUpdatePath: '/test/issue-boards/board/1/lists', bulkUpdatePath: '/test/issue-boards/board/1/lists',
}); });
...@@ -31,7 +30,7 @@ describe('List model', () => { ...@@ -31,7 +30,7 @@ describe('List model', () => {
}); });
afterEach(() => { afterEach(() => {
Vue.http.interceptors = _.without(Vue.http.interceptors, boardsMockInterceptor); mock.reset();
}); });
it('gets issues when created', (done) => { it('gets issues when created', (done) => {
...@@ -158,10 +157,8 @@ describe('List model', () => { ...@@ -158,10 +157,8 @@ describe('List model', () => {
describe('newIssue', () => { describe('newIssue', () => {
beforeEach(() => { beforeEach(() => {
spyOn(gl.boardService, 'newIssue').and.returnValue(Promise.resolve({ spyOn(gl.boardService, 'newIssue').and.returnValue(Promise.resolve({
json() { data: {
return {
id: 42, id: 42,
};
}, },
})); }));
}); });
......
/* global boardsMockInterceptor */
/* global boardObj */
/* global BoardService */ /* global BoardService */
/* global mockBoardService */
import Vue from 'vue'; import Vue from 'vue';
import MilestoneSelect from '~/boards/components/milestone_select.vue'; import MilestoneSelect from '~/boards/components/milestone_select.vue';
import IssuableContext from '~/issuable_context'; import IssuableContext from '~/issuable_context';
import { boardObj } from './mock_data';
let vm; let vm;
......
/* global BoardService */ /* global BoardService */
/* eslint-disable comma-dangle, no-unused-vars, quote-props */ /* eslint-disable comma-dangle, no-unused-vars, quote-props */
const boardObj = { export const boardObj = {
id: 1, id: 1,
name: 'test', name: 'test',
milestone_id: null, milestone_id: null,
}; };
const listObj = { export const listObj = {
id: _.random(10000), id: 300,
position: 0, position: 0,
title: 'Test', title: 'Test',
list_type: 'label', list_type: 'label',
label: { label: {
id: _.random(10000), id: 5000,
title: 'Testing', title: 'Testing',
color: 'red', color: 'red',
description: 'testing;' description: 'testing;'
} }
}; };
const listObjDuplicate = { export const listObjDuplicate = {
id: listObj.id, id: listObj.id,
position: 1, position: 1,
title: 'Test', title: 'Test',
...@@ -32,9 +32,9 @@ const listObjDuplicate = { ...@@ -32,9 +32,9 @@ const listObjDuplicate = {
} }
}; };
const BoardsMockData = { export const BoardsMockData = {
'GET': { 'GET': {
'/test/boards/1{/id}/issues': { '/test/-/boards/1/lists/300/issues?id=300&page=1&=': {
issues: [{ issues: [{
title: 'Testing', title: 'Testing',
id: 1, id: 1,
...@@ -50,7 +50,7 @@ const BoardsMockData = { ...@@ -50,7 +50,7 @@ const BoardsMockData = {
}], }],
}, },
'POST': { 'POST': {
'/test/boards/1{/id}': listObj '/test/-/boards/1/lists': listObj
}, },
'PUT': { 'PUT': {
'/test/issue-boards/board/1/lists{/id}': {} '/test/issue-boards/board/1/lists{/id}': {}
...@@ -60,17 +60,14 @@ const BoardsMockData = { ...@@ -60,17 +60,14 @@ const BoardsMockData = {
} }
}; };
const boardsMockInterceptor = (request, next) => { export const boardsMockInterceptor = (config) => {
const body = BoardsMockData[request.method.toUpperCase()][request.url]; const body = BoardsMockData[config.method.toUpperCase()][config.url];
return [200, body];
next(request.respondWith(JSON.stringify(body), {
status: 200
}));
}; };
const mockBoardService = (opts = {}) => { export const mockBoardService = (opts = {}) => {
const boardsEndpoint = opts.boardsEndpoint || '/test/issue-boards/board'; const boardsEndpoint = opts.boardsEndpoint || '/test/issue-boards/boards.json';
const listsEndpoint = opts.listsEndpoint || '/test/boards/1'; const listsEndpoint = opts.listsEndpoint || '/test/-/boards/1/lists';
const bulkUpdatePath = opts.bulkUpdatePath || ''; const bulkUpdatePath = opts.bulkUpdatePath || '';
const boardId = opts.boardId || '1'; const boardId = opts.boardId || '1';
...@@ -81,10 +78,3 @@ const mockBoardService = (opts = {}) => { ...@@ -81,10 +78,3 @@ const mockBoardService = (opts = {}) => {
boardId, boardId,
}); });
}; };
window.boardObj = boardObj;
window.listObj = listObj;
window.listObjDuplicate = listObjDuplicate;
window.BoardsMockData = BoardsMockData;
window.boardsMockInterceptor = boardsMockInterceptor;
window.mockBoardService = mockBoardService;
import Vue from 'vue'; import Vue from 'vue';
import MockAdapter from 'axios-mock-adapter';
import axios from '~/lib/utils/axios_utils';
import epicShowApp from 'ee/epics/epic_show/components/epic_show_app.vue'; import epicShowApp from 'ee/epics/epic_show/components/epic_show_app.vue';
import epicHeader from 'ee/epics/epic_show/components/epic_header.vue'; import epicHeader from 'ee/epics/epic_show/components/epic_header.vue';
import epicSidebar from 'ee/epics/sidebar/components/sidebar_app.vue'; import epicSidebar from 'ee/epics/sidebar/components/sidebar_app.vue';
...@@ -10,25 +12,16 @@ import { props } from '../mock_data'; ...@@ -10,25 +12,16 @@ import { props } from '../mock_data';
import issueShowData from '../../../issue_show/mock_data'; import issueShowData from '../../../issue_show/mock_data';
describe('EpicShowApp', () => { describe('EpicShowApp', () => {
let mock;
let vm; let vm;
let headerVm; let headerVm;
let issuableAppVm; let issuableAppVm;
let sidebarVm; let sidebarVm;
const interceptor = (request, next) => { beforeEach((done) => {
if (request.url === '/realtime_changes') { mock = new MockAdapter(axios);
next(request.respondWith(JSON.stringify(issueShowData.initialRequest), { mock.onGet('/realtime_changes').reply(200, issueShowData.initialRequest);
status: 200, mock.onAny().reply(404, null);
}));
} else {
next(request.respondWith(null, {
status: 404,
}));
}
};
beforeEach(() => {
Vue.http.interceptors.push(interceptor);
const { const {
canUpdate, canUpdate,
...@@ -80,10 +73,12 @@ describe('EpicShowApp', () => { ...@@ -80,10 +73,12 @@ describe('EpicShowApp', () => {
initialStartDate: startDate, initialStartDate: startDate,
initialEndDate: endDate, initialEndDate: endDate,
}); });
setTimeout(done);
}); });
afterEach(() => { afterEach(() => {
Vue.http.interceptors = _.without(Vue.http.interceptors, interceptor); mock.reset();
}); });
it('should render epic-header', () => { it('should render epic-header', () => {
......
import Vue from 'vue'; import Vue from 'vue';
import MockAdapter from 'axios-mock-adapter';
import axios from '~/lib/utils/axios_utils';
import '~/render_math'; import '~/render_math';
import '~/render_gfm'; import '~/render_gfm';
import * as urlUtils from '~/lib/utils/url_utility'; import * as urlUtils from '~/lib/utils/url_utility';
...@@ -11,26 +13,29 @@ function formatText(text) { ...@@ -11,26 +13,29 @@ function formatText(text) {
return text.trim().replace(/\s\s+/g, ' '); return text.trim().replace(/\s\s+/g, ' ');
} }
const REALTIME_REQUEST_STACK = [
issueShowData.initialRequest,
issueShowData.secondRequest,
];
describe('Issuable output', () => { describe('Issuable output', () => {
let requestData = issueShowData.initialRequest; let mock;
let realtimeRequestCount = 0;
let vm;
document.body.innerHTML = '<span id="task_status"></span>'; document.body.innerHTML = '<span id="task_status"></span>';
const interceptor = (request, next) => {
next(request.respondWith(JSON.stringify(requestData), {
status: 200,
}));
};
let vm;
beforeEach((done) => { beforeEach((done) => {
spyOn(eventHub, '$emit'); spyOn(eventHub, '$emit');
const IssuableDescriptionComponent = Vue.extend(issuableApp); const IssuableDescriptionComponent = Vue.extend(issuableApp);
requestData = issueShowData.initialRequest; mock = new MockAdapter(axios);
Vue.http.interceptors.push(interceptor); mock.onGet('/gitlab-org/gitlab-shell/issues/9/realtime_changes/realtime_changes').reply(() => {
const res = Promise.resolve([200, REALTIME_REQUEST_STACK[realtimeRequestCount]]);
realtimeRequestCount += 1;
return res;
});
vm = new IssuableDescriptionComponent({ vm = new IssuableDescriptionComponent({
propsData: { propsData: {
...@@ -54,10 +59,10 @@ describe('Issuable output', () => { ...@@ -54,10 +59,10 @@ describe('Issuable output', () => {
}); });
afterEach(() => { afterEach(() => {
Vue.http.interceptors = _.without(Vue.http.interceptors, interceptor); mock.reset();
realtimeRequestCount = 0;
vm.poll.stop(); vm.poll.stop();
vm.$destroy(); vm.$destroy();
}); });
...@@ -77,7 +82,6 @@ describe('Issuable output', () => { ...@@ -77,7 +82,6 @@ describe('Issuable output', () => {
expect(editedText.querySelector('time')).toBeTruthy(); expect(editedText.querySelector('time')).toBeTruthy();
}) })
.then(() => { .then(() => {
requestData = issueShowData.secondRequest;
vm.poll.makeRequest(); vm.poll.makeRequest();
}) })
.then(() => new Promise(resolve => setTimeout(resolve))) .then(() => new Promise(resolve => setTimeout(resolve)))
...@@ -141,24 +145,19 @@ describe('Issuable output', () => { ...@@ -141,24 +145,19 @@ describe('Issuable output', () => {
spyOn(vm.service, 'getData').and.callThrough(); spyOn(vm.service, 'getData').and.callThrough();
spyOn(vm.service, 'updateIssuable').and.callFake(() => new Promise((resolve) => { spyOn(vm.service, 'updateIssuable').and.callFake(() => new Promise((resolve) => {
resolve({ resolve({
json() { data: {
return {
confidential: false, confidential: false,
web_url: location.pathname, web_url: location.pathname,
};
}, },
}); });
})); }));
vm.updateIssuable(); vm.updateIssuable()
.then(() => {
setTimeout(() => { expect(vm.service.getData).toHaveBeenCalled();
expect( })
vm.service.getData, .then(done)
).toHaveBeenCalled(); .catch(done.fail);
done();
});
}); });
it('correctly updates issuable data', (done) => { it('correctly updates issuable data', (done) => {
...@@ -166,29 +165,22 @@ describe('Issuable output', () => { ...@@ -166,29 +165,22 @@ describe('Issuable output', () => {
resolve(); resolve();
})); }));
vm.updateIssuable(); vm.updateIssuable()
.then(() => {
setTimeout(() => { expect(vm.service.updateIssuable).toHaveBeenCalledWith(vm.formState);
expect( expect(eventHub.$emit).toHaveBeenCalledWith('close.form');
vm.service.updateIssuable, })
).toHaveBeenCalledWith(vm.formState); .then(done)
expect( .catch(done.fail);
eventHub.$emit,
).toHaveBeenCalledWith('close.form');
done();
});
}); });
it('does not redirect if issue has not moved', (done) => { it('does not redirect if issue has not moved', (done) => {
spyOn(urlUtils, 'visitUrl'); spyOn(urlUtils, 'visitUrl');
spyOn(vm.service, 'updateIssuable').and.callFake(() => new Promise((resolve) => { spyOn(vm.service, 'updateIssuable').and.callFake(() => new Promise((resolve) => {
resolve({ resolve({
json() { data: {
return {
web_url: location.pathname, web_url: location.pathname,
confidential: vm.isConfidential, confidential: vm.isConfidential,
};
}, },
}); });
})); }));
...@@ -208,11 +200,9 @@ describe('Issuable output', () => { ...@@ -208,11 +200,9 @@ describe('Issuable output', () => {
spyOn(urlUtils, 'visitUrl'); spyOn(urlUtils, 'visitUrl');
spyOn(vm.service, 'updateIssuable').and.callFake(() => new Promise((resolve) => { spyOn(vm.service, 'updateIssuable').and.callFake(() => new Promise((resolve) => {
resolve({ resolve({
json() { data: {
return {
web_url: '/testing-issue-move', web_url: '/testing-issue-move',
confidential: vm.isConfidential, confidential: vm.isConfidential,
};
}, },
}); });
})); }));
...@@ -283,10 +273,8 @@ describe('Issuable output', () => { ...@@ -283,10 +273,8 @@ describe('Issuable output', () => {
let modal; let modal;
const promise = new Promise((resolve) => { const promise = new Promise((resolve) => {
resolve({ resolve({
json() { data: {
return {
recaptcha_html: '<div class="g-recaptcha">recaptcha_html</div>', recaptcha_html: '<div class="g-recaptcha">recaptcha_html</div>',
};
}, },
}); });
}); });
...@@ -323,8 +311,8 @@ describe('Issuable output', () => { ...@@ -323,8 +311,8 @@ describe('Issuable output', () => {
spyOn(urlUtils, 'visitUrl'); spyOn(urlUtils, 'visitUrl');
spyOn(vm.service, 'deleteIssuable').and.callFake(() => new Promise((resolve) => { spyOn(vm.service, 'deleteIssuable').and.callFake(() => new Promise((resolve) => {
resolve({ resolve({
json() { data: {
return { web_url: '/test' }; web_url: '/test',
}, },
}); });
})); }));
...@@ -345,8 +333,8 @@ describe('Issuable output', () => { ...@@ -345,8 +333,8 @@ describe('Issuable output', () => {
spyOn(vm.poll, 'stop').and.callThrough(); spyOn(vm.poll, 'stop').and.callThrough();
spyOn(vm.service, 'deleteIssuable').and.callFake(() => new Promise((resolve) => { spyOn(vm.service, 'deleteIssuable').and.callFake(() => new Promise((resolve) => {
resolve({ resolve({
json() { data: {
return { web_url: '/test' }; web_url: '/test',
}, },
}); });
})); }));
...@@ -385,22 +373,21 @@ describe('Issuable output', () => { ...@@ -385,22 +373,21 @@ describe('Issuable output', () => {
describe('open form', () => { describe('open form', () => {
it('shows locked warning if form is open & data is different', (done) => { it('shows locked warning if form is open & data is different', (done) => {
Vue.nextTick() vm.$nextTick()
.then(() => { .then(() => {
vm.openForm(); vm.openForm();
requestData = issueShowData.secondRequest;
vm.poll.makeRequest(); vm.poll.makeRequest();
}) })
.then(() => new Promise(resolve => setTimeout(resolve))) // Wait for the request
.then(vm.$nextTick)
// Wait for the successCallback to update the store state
.then(vm.$nextTick)
// Wait for the new state to flow to the Vue components
.then(vm.$nextTick)
.then(() => { .then(() => {
expect( expect(vm.formState.lockedWarningVisible).toEqual(true);
vm.formState.lockedWarningVisible, expect(vm.$el.querySelector('.alert')).not.toBeNull();
).toBeTruthy();
expect(
vm.$el.querySelector('.alert'),
).not.toBeNull();
}) })
.then(done) .then(done)
.catch(done.fail); .catch(done.fail);
......
...@@ -19,14 +19,4 @@ export default { ...@@ -19,14 +19,4 @@ export default {
updated_by_name: 'Other User', updated_by_name: 'Other User',
updated_by_path: '/other_user', updated_by_path: '/other_user',
}, },
issueSpecRequest: {
title: '<p>this is a title</p>',
title_text: 'this is a title',
description: '<li class="task-list-item enabled"><input type="checkbox" class="task-list-item-checkbox">Task List Item</li>',
description_text: '- [ ] Task List Item',
task_status: '0 of 1 completed',
updated_at: '2017-05-15T12:31:04.428Z',
updated_by_name: 'Last User',
updated_by_path: '/last_user',
},
}; };
...@@ -95,10 +95,8 @@ describe('MRWidgetDeployment', () => { ...@@ -95,10 +95,8 @@ describe('MRWidgetDeployment', () => {
const url = '/foo/bar'; const url = '/foo/bar';
const returnPromise = () => new Promise((resolve) => { const returnPromise = () => new Promise((resolve) => {
resolve({ resolve({
json() { data: {
return {
redirect_url: url, redirect_url: url,
};
}, },
}); });
}); });
......
...@@ -155,9 +155,7 @@ describe('MemoryUsage', () => { ...@@ -155,9 +155,7 @@ describe('MemoryUsage', () => {
describe('loadMetrics', () => { describe('loadMetrics', () => {
const returnServicePromise = () => new Promise((resolve) => { const returnServicePromise = () => new Promise((resolve) => {
resolve({ resolve({
json() { data: metricsMockData,
return metricsMockData;
},
}); });
}); });
......
...@@ -108,9 +108,7 @@ describe('MRWidgetMergeWhenPipelineSucceeds', () => { ...@@ -108,9 +108,7 @@ describe('MRWidgetMergeWhenPipelineSucceeds', () => {
spyOn(eventHub, '$emit'); spyOn(eventHub, '$emit');
spyOn(vm.service, 'cancelAutomaticMerge').and.returnValue(new Promise((resolve) => { spyOn(vm.service, 'cancelAutomaticMerge').and.returnValue(new Promise((resolve) => {
resolve({ resolve({
json() { data: mrObj,
return mrObj;
},
}); });
})); }));
...@@ -129,10 +127,8 @@ describe('MRWidgetMergeWhenPipelineSucceeds', () => { ...@@ -129,10 +127,8 @@ describe('MRWidgetMergeWhenPipelineSucceeds', () => {
spyOn(eventHub, '$emit'); spyOn(eventHub, '$emit');
spyOn(vm.service.mergeResource, 'save').and.returnValue(new Promise((resolve) => { spyOn(vm.service.mergeResource, 'save').and.returnValue(new Promise((resolve) => {
resolve({ resolve({
json() { data: {
return {
status: 'merge_when_pipeline_succeeds', status: 'merge_when_pipeline_succeeds',
};
}, },
}); });
})); }));
......
...@@ -111,10 +111,8 @@ describe('MRWidgetMerged', () => { ...@@ -111,10 +111,8 @@ describe('MRWidgetMerged', () => {
spyOn(eventHub, '$emit'); spyOn(eventHub, '$emit');
spyOn(vm.service, 'removeSourceBranch').and.returnValue(new Promise((resolve) => { spyOn(vm.service, 'removeSourceBranch').and.returnValue(new Promise((resolve) => {
resolve({ resolve({
json() { data: {
return {
message: 'Branch was removed', message: 'Branch was removed',
};
}, },
}); });
})); }));
......
...@@ -292,8 +292,8 @@ describe('MRWidgetReadyToMerge', () => { ...@@ -292,8 +292,8 @@ describe('MRWidgetReadyToMerge', () => {
describe('handleMergeButtonClick', () => { describe('handleMergeButtonClick', () => {
const returnPromise = status => new Promise((resolve) => { const returnPromise = status => new Promise((resolve) => {
resolve({ resolve({
json() { data: {
return { status }; status,
}, },
}); });
}); });
...@@ -364,8 +364,9 @@ describe('MRWidgetReadyToMerge', () => { ...@@ -364,8 +364,9 @@ describe('MRWidgetReadyToMerge', () => {
describe('handleMergePolling', () => { describe('handleMergePolling', () => {
const returnPromise = state => new Promise((resolve) => { const returnPromise = state => new Promise((resolve) => {
resolve({ resolve({
json() { data: {
return { state, source_branch_exists: true }; state,
source_branch_exists: true,
}, },
}); });
}); });
...@@ -422,8 +423,8 @@ describe('MRWidgetReadyToMerge', () => { ...@@ -422,8 +423,8 @@ describe('MRWidgetReadyToMerge', () => {
describe('handleRemoveBranchPolling', () => { describe('handleRemoveBranchPolling', () => {
const returnPromise = state => new Promise((resolve) => { const returnPromise = state => new Promise((resolve) => {
resolve({ resolve({
json() { data: {
return { source_branch_exists: state }; source_branch_exists: state,
}, },
}); });
}); });
......
...@@ -50,9 +50,7 @@ describe('MRWidgetWIP', () => { ...@@ -50,9 +50,7 @@ describe('MRWidgetWIP', () => {
spyOn(eventHub, '$emit'); spyOn(eventHub, '$emit');
spyOn(vm.service, 'removeWIP').and.returnValue(new Promise((resolve) => { spyOn(vm.service, 'removeWIP').and.returnValue(new Promise((resolve) => {
resolve({ resolve({
json() { data: mrObj,
return mrObj;
},
}); });
})); }));
......
...@@ -8,10 +8,7 @@ import mountComponent from '../helpers/vue_mount_component_helper'; ...@@ -8,10 +8,7 @@ import mountComponent from '../helpers/vue_mount_component_helper';
const returnPromise = data => new Promise((resolve) => { const returnPromise = data => new Promise((resolve) => {
resolve({ resolve({
json() { data,
return data;
},
body: data,
}); });
}); });
......
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