Commit 6bbe2127 authored by Nicolò Maria Mezzopera's avatar Nicolò Maria Mezzopera

Merge branch 'prettier-arrow-parens-1' into 'master'

Format files with prettier arrowParens [1/15]

See merge request gitlab-org/gitlab!50520
parents ab3740be 4914a729
......@@ -10,74 +10,6 @@ doc/api/graphql/reference/gitlab_schema.graphql
*.scss
*.md
## lovely-lovelace
app/assets/javascripts/alerts_settings/components/alerts_settings_wrapper.vue
app/assets/javascripts/behaviors/markdown/paste_markdown_table.js
app/assets/javascripts/boards/components/sidebar/remove_issue.vue
app/assets/javascripts/diffs/components/diff_row.vue
app/assets/javascripts/diffs/store/getters.js
app/assets/javascripts/dropzone_input.js
app/assets/javascripts/feature_flags/components/strategy.vue
app/assets/javascripts/ide/lib/create_diff.js
app/assets/javascripts/ide/stores/modules/pipelines/getters.js
app/assets/javascripts/members/components/table/members_table.vue
app/assets/javascripts/members/store/utils.js
app/assets/javascripts/monitoring/stores/actions.js
app/assets/javascripts/monitoring/stores/getters.js
app/assets/javascripts/packages/list/utils.js
app/assets/javascripts/pages/projects/forks/new/components/fork_groups_list.vue
app/assets/javascripts/pages/users/user_tabs.js
app/assets/javascripts/projects/settings/access_dropdown.js
## stoic-swirles
app/assets/javascripts/repository/log_tree.js
app/assets/javascripts/repository/utils/dom.js
app/assets/javascripts/sidebar/components/labels/sidebar_labels.vue
app/assets/javascripts/user_lists/store/utils.js
app/assets/javascripts/vue_shared/components/alert_details_table.vue
app/assets/javascripts/vue_shared/components/upload_dropzone/upload_dropzone.vue
app/assets/javascripts/vue_shared/constants.js
ee/app/assets/javascripts/analytics/cycle_analytics/utils.js
ee/app/assets/javascripts/analytics/repository_analytics/components/select_projects_dropdown.vue
ee/app/assets/javascripts/boards/stores/getters.js
ee/app/assets/javascripts/dependencies/store/modules/list/getters.js
ee/app/assets/javascripts/epic/store/getters.js
ee/app/assets/javascripts/insights/components/insights_page.vue
ee/app/assets/javascripts/pages/trial_registrations/new/username_suggester.js
ee/app/assets/javascripts/related_items_tree/store/mutations.js
ee/app/assets/javascripts/security_dashboard/components/project_vulnerabilities.vue
ee/spec/frontend/analytics/shared/components/groups_dropdown_filter_spec.js
ee/spec/frontend/analytics/shared/components/projects_dropdown_filter_spec.js
ee/spec/frontend/approvals/components/approvers_list_spec.js
ee/spec/frontend/approvals/components/rule_controls_spec.js
ee/spec/frontend/audit_events/components/audit_events_filter_spec.js
ee/spec/frontend/dependencies/components/dependencies_table_spec.js
ee/spec/frontend/geo_node_form/components/geo_node_form_capacities_spec.js
ee/spec/frontend/security_configuration/dast_profiles/graphql/cache_utils_spec.js
ee/spec/frontend/security_configuration/dast_site_profiles_form/components/dast_site_profile_form_spec.js
ee/spec/frontend/security_configuration/dast_site_validation/components/dast_site_validation_modal_spec.js
ee/spec/frontend/security_dashboard/components/vulnerability_list_spec.js
ee/spec/frontend/sidebar/components/status/status_spec.js
ee/spec/frontend/storage_counter/components/projects_table_spec.js
ee/spec/frontend/vulnerabilities/footer_spec.js
spec/frontend/blob/balsamiq/balsamiq_viewer_spec.js
## objective-swirles
spec/frontend/boards/components/sidebar/board_sidebar_labels_select_spec.js
spec/frontend/clusters/stores/clusters_store_spec.js
spec/frontend/diffs/components/diff_file_header_spec.js
spec/frontend/diffs/components/hidden_files_warning_spec.js
spec/frontend/environments/environment_monitoring_spec.js
spec/frontend/import_entities/import_groups/graphql/services/status_poller_spec.js
spec/frontend/issuable/related_issues/components/add_issuable_form_spec.js
spec/frontend/notes/components/discussion_filter_spec.js
spec/frontend/pipeline_editor/components/lint/ci_lint_results_spec.js
spec/frontend/projects/settings_service_desk/components/service_desk_setting_spec.js
spec/frontend/snippets/components/edit_spec.js
spec/frontend/user_lists/store/show/mutations_spec.js
spec/frontend/vue_shared/components/stacked_progress_bar_spec.js
spec/frontend_integration/ide/helpers/ide_helper.js
## boring-bohr
jest.config.base.js
jest.config.js
......
......@@ -243,7 +243,9 @@ export default {
});
},
editIntegration({ id }) {
const currentIntegration = this.integrations.list.find(integration => integration.id === id);
const currentIntegration = this.integrations.list.find(
(integration) => integration.id === id,
);
this.$apollo.mutate({
mutation: updateCurrentIntergrationMutation,
variables: {
......
const maxColumnWidth = (rows, columnIndex) => Math.max(...rows.map(row => row[columnIndex].length));
const maxColumnWidth = (rows, columnIndex) =>
Math.max(...rows.map((row) => row[columnIndex].length));
export default class PasteMarkdownTable {
constructor(clipboardData) {
......@@ -16,7 +17,7 @@ export default class PasteMarkdownTable {
this.calculateColumnWidths();
const markdownRows = this.rows.map(
row =>
(row) =>
// | Name | Title | Email Address |
// |--------------|-------|----------------|
// | Jane Atler | CEO | jane@acme.com |
......@@ -66,7 +67,7 @@ export default class PasteMarkdownTable {
return false;
}
this.rows = splitRows.map(row => row.split('\t'));
this.rows = splitRows.map((row) => row.split('\t'));
this.normalizeRows();
// Check that the max number of columns in the HTML matches the number of
......@@ -81,10 +82,10 @@ export default class PasteMarkdownTable {
// Ensure each row has the same number of columns
normalizeRows() {
const rowLengths = this.rows.map(row => row.length);
const rowLengths = this.rows.map((row) => row.length);
const maxLength = Math.max(...rowLengths);
this.rows.forEach(row => {
this.rows.forEach((row) => {
while (row.length < maxLength) {
row.push('');
}
......@@ -101,7 +102,7 @@ export default class PasteMarkdownTable {
const textColumnCount = this.rows[0].length;
let htmlColumnCount = 0;
this.doc.querySelectorAll('table tr').forEach(row => {
this.doc.querySelectorAll('table tr').forEach((row) => {
htmlColumnCount = Math.max(row.cells.length, htmlColumnCount);
});
......
......@@ -42,13 +42,13 @@ export default {
axios.patch(this.updateUrl, data).catch(() => {
Flash(__('Failed to remove issue from board, please try again.'));
lists.forEach(list => {
lists.forEach((list) => {
list.addIssue(issue);
});
});
// Remove from the frontend store
lists.forEach(list => {
lists.forEach((list) => {
list.removeIssue(issue);
});
......@@ -58,9 +58,11 @@ export default {
* Build the default patch request.
*/
buildPatchRequest(issue, lists) {
const listLabelIds = lists.map(list => list.label.id);
const listLabelIds = lists.map((list) => list.label.id);
const labelIds = issue.labels.map(label => label.id).filter(id => !listLabelIds.includes(id));
const labelIds = issue.labels
.map((label) => label.id)
.filter((id) => !listLabelIds.includes(id));
return {
label_ids: labelIds,
......
......@@ -115,7 +115,9 @@ export default {
const table = line.closest('.diff-table');
table.classList.remove('left-side-selected', 'right-side-selected');
const [lineClass] = ['left-side', 'right-side'].filter(name => line.classList.contains(name));
const [lineClass] = ['left-side', 'right-side'].filter((name) =>
line.classList.contains(name),
);
if (lineClass) {
table.classList.add(`${lineClass}-selected`);
......
......@@ -9,13 +9,13 @@ import {
export * from './getters_versions_dropdowns';
export const isParallelView = state => state.diffViewType === PARALLEL_DIFF_VIEW_TYPE;
export const isParallelView = (state) => state.diffViewType === PARALLEL_DIFF_VIEW_TYPE;
export const isInlineView = state => state.diffViewType === INLINE_DIFF_VIEW_TYPE;
export const isInlineView = (state) => state.diffViewType === INLINE_DIFF_VIEW_TYPE;
export const whichCollapsedTypes = state => {
const automatic = state.diffFiles.some(file => file.viewer?.automaticallyCollapsed);
const manual = state.diffFiles.some(file => file.viewer?.manuallyCollapsed);
export const whichCollapsedTypes = (state) => {
const automatic = state.diffFiles.some((file) => file.viewer?.automaticallyCollapsed);
const manual = state.diffFiles.some((file) => file.viewer?.manuallyCollapsed);
return {
any: automatic || manual,
......@@ -24,18 +24,18 @@ export const whichCollapsedTypes = state => {
};
};
export const commitId = state => (state.commit && state.commit.id ? state.commit.id : null);
export const commitId = (state) => (state.commit && state.commit.id ? state.commit.id : null);
/**
* Checks if the diff has all discussions expanded
* @param {Object} diff
* @returns {Boolean}
*/
export const diffHasAllExpandedDiscussions = (state, getters) => diff => {
export const diffHasAllExpandedDiscussions = (state, getters) => (diff) => {
const discussions = getters.getDiffFileDiscussions(diff);
return (
(discussions && discussions.length && discussions.every(discussion => discussion.expanded)) ||
(discussions && discussions.length && discussions.every((discussion) => discussion.expanded)) ||
false
);
};
......@@ -45,11 +45,13 @@ export const diffHasAllExpandedDiscussions = (state, getters) => diff => {
* @param {Object} diff
* @returns {Boolean}
*/
export const diffHasAllCollapsedDiscussions = (state, getters) => diff => {
export const diffHasAllCollapsedDiscussions = (state, getters) => (diff) => {
const discussions = getters.getDiffFileDiscussions(diff);
return (
(discussions && discussions.length && discussions.every(discussion => !discussion.expanded)) ||
(discussions &&
discussions.length &&
discussions.every((discussion) => !discussion.expanded)) ||
false
);
};
......@@ -59,9 +61,9 @@ export const diffHasAllCollapsedDiscussions = (state, getters) => diff => {
* @param {Object} diff
* @returns {Boolean}
*/
export const diffHasExpandedDiscussions = () => diff => {
return diff[INLINE_DIFF_LINES_KEY].filter(l => l.discussions.length >= 1).some(
l => l.discussionsExpanded,
export const diffHasExpandedDiscussions = () => (diff) => {
return diff[INLINE_DIFF_LINES_KEY].filter((l) => l.discussions.length >= 1).some(
(l) => l.discussionsExpanded,
);
};
......@@ -70,8 +72,8 @@ export const diffHasExpandedDiscussions = () => diff => {
* @param {Boolean} diff
* @returns {Boolean}
*/
export const diffHasDiscussions = () => diff => {
return diff[INLINE_DIFF_LINES_KEY].some(l => l.discussions.length >= 1);
export const diffHasDiscussions = () => (diff) => {
return diff[INLINE_DIFF_LINES_KEY].some((l) => l.discussions.length >= 1);
};
/**
......@@ -79,22 +81,22 @@ export const diffHasDiscussions = () => diff => {
* @param {Object} diff
* @returns {Array}
*/
export const getDiffFileDiscussions = (state, getters, rootState, rootGetters) => diff =>
export const getDiffFileDiscussions = (state, getters, rootState, rootGetters) => (diff) =>
rootGetters.discussions.filter(
discussion => discussion.diff_discussion && discussion.diff_file.file_hash === diff.file_hash,
(discussion) => discussion.diff_discussion && discussion.diff_file.file_hash === diff.file_hash,
) || [];
export const getDiffFileByHash = state => fileHash =>
state.diffFiles.find(file => file.file_hash === fileHash);
export const getDiffFileByHash = (state) => (fileHash) =>
state.diffFiles.find((file) => file.file_hash === fileHash);
export const flatBlobsList = state =>
Object.values(state.treeEntries).filter(f => f.type === 'blob');
export const flatBlobsList = (state) =>
Object.values(state.treeEntries).filter((f) => f.type === 'blob');
export const allBlobs = (state, getters) =>
getters.flatBlobsList.reduce((acc, file) => {
const { parentPath } = file;
if (parentPath && !acc.some(f => f.path === parentPath)) {
if (parentPath && !acc.some((f) => f.path === parentPath)) {
acc.push({
path: parentPath,
isHeader: true,
......@@ -102,13 +104,13 @@ export const allBlobs = (state, getters) =>
});
}
acc.find(f => f.path === parentPath).tree.push(file);
acc.find((f) => f.path === parentPath).tree.push(file);
return acc;
}, []);
export const getCommentFormForDiffFile = state => fileHash =>
state.commentForms.find(form => form.fileHash === fileHash);
export const getCommentFormForDiffFile = (state) => (fileHash) =>
state.commentForms.find((form) => form.fileHash === fileHash);
/**
* Returns the test coverage hits for a specific line of a given file
......@@ -116,7 +118,7 @@ export const getCommentFormForDiffFile = state => fileHash =>
* @param {number} line
* @returns {number}
*/
export const fileLineCoverage = state => (file, line) => {
export const fileLineCoverage = (state) => (file, line) => {
if (!state.coverageFiles.files) return {};
const fileCoverage = state.coverageFiles.files[file];
if (!fileCoverage) return {};
......@@ -137,13 +139,13 @@ export const fileLineCoverage = state => (file, line) => {
* Returns index of a currently selected diff in diffFiles
* @returns {number}
*/
export const currentDiffIndex = state =>
export const currentDiffIndex = (state) =>
Math.max(
0,
state.diffFiles.findIndex(diff => diff.file_hash === state.currentDiffFileId),
state.diffFiles.findIndex((diff) => diff.file_hash === state.currentDiffFileId),
);
export const diffLines = state => (file, unifiedDiffComponents) => {
export const diffLines = (state) => (file, unifiedDiffComponents) => {
if (!unifiedDiffComponents && state.diffViewType === INLINE_DIFF_VIEW_TYPE) {
return null;
}
......@@ -155,5 +157,5 @@ export const diffLines = state => (file, unifiedDiffComponents) => {
};
export function fileReviews(state) {
return state.diffFiles.map(file => isFileReviewed(state.mrReviews, file));
return state.diffFiles.map((file) => isFileReviewed(state.mrReviews, file));
}
......@@ -46,7 +46,7 @@ export default function dropzoneInput(form, config = { parallelUploads: 2 }) {
let uploadFile;
formTextarea.wrap('<div class="div-dropzone"></div>');
formTextarea.on('paste', event => handlePaste(event));
formTextarea.on('paste', (event) => handlePaste(event));
// Add dropzone area to the form.
const $mdArea = formTextarea.closest('.md-area');
......@@ -139,7 +139,7 @@ export default function dropzoneInput(form, config = { parallelUploads: 2 }) {
// removeAllFiles(true) stops uploading files (if any)
// and remove them from dropzone files queue.
$cancelButton.on('click', e => {
$cancelButton.on('click', (e) => {
e.preventDefault();
e.stopPropagation();
Dropzone.forElement($formDropzone.get(0)).removeAllFiles(true);
......@@ -149,7 +149,7 @@ export default function dropzoneInput(form, config = { parallelUploads: 2 }) {
// clear dropzone files queue, change status of failed files to undefined,
// and add that files to the dropzone files queue again.
// addFile() adds file to dropzone files queue and upload it.
$retryLink.on('click', e => {
$retryLink.on('click', (e) => {
const dropzoneInstance = Dropzone.forElement(
e.target.closest('.js-main-target-form').querySelector('.div-dropzone'),
);
......@@ -161,7 +161,7 @@ export default function dropzoneInput(form, config = { parallelUploads: 2 }) {
// uploading of files that are being uploaded at the moment.
dropzoneInstance.removeAllFiles(true);
failedFiles.map(failedFile => {
failedFiles.map((failedFile) => {
const file = failedFile;
if (file.status === Dropzone.ERROR) {
......@@ -173,7 +173,7 @@ export default function dropzoneInput(form, config = { parallelUploads: 2 }) {
});
});
// eslint-disable-next-line consistent-return
handlePaste = event => {
handlePaste = (event) => {
const pasteEvent = event.originalEvent;
const { clipboardData } = pasteEvent;
if (clipboardData && clipboardData.items) {
......@@ -198,7 +198,7 @@ export default function dropzoneInput(form, config = { parallelUploads: 2 }) {
}
};
isImage = data => {
isImage = (data) => {
let i = 0;
while (i < data.clipboardData.items.length) {
const item = data.clipboardData.items[i];
......@@ -228,7 +228,7 @@ export default function dropzoneInput(form, config = { parallelUploads: 2 }) {
return formTextarea.trigger('input');
};
addFileToForm = path => {
addFileToForm = (path) => {
$(form).append(`<input type="hidden" name="files[]" value="${escape(path)}">`);
};
......@@ -236,7 +236,7 @@ export default function dropzoneInput(form, config = { parallelUploads: 2 }) {
const closeSpinner = () => $uploadingProgressContainer.addClass('hide');
const showError = message => {
const showError = (message) => {
$uploadingErrorContainer.removeClass('hide');
$uploadingErrorMessage.html(message);
};
......@@ -269,15 +269,16 @@ export default function dropzoneInput(form, config = { parallelUploads: 2 }) {
insertToTextArea(filename, md);
closeSpinner();
})
.catch(e => {
.catch((e) => {
showError(e.response.data.message);
closeSpinner();
});
};
updateAttachingMessage = (files, messageContainer) => {
const filesCount = files.filter(file => file.status === 'uploading' || file.status === 'queued')
.length;
const filesCount = files.filter(
(file) => file.status === 'uploading' || file.status === 'queued',
).length;
const attachingMessage = n__('Attaching a file', 'Attaching %d files', filesCount);
messageContainer.text(`${attachingMessage} -`);
......
......@@ -83,7 +83,7 @@ export default {
);
},
filteredEnvironments() {
return this.environments.filter(e => !e.shouldBeDestroyed);
return this.environments.filter((e) => !e.shouldBeDestroyed);
},
isPercentUserRollout() {
return this.formStrategy.name === ROLLOUT_STRATEGY_PERCENT_ROLLOUT;
......@@ -91,7 +91,9 @@ export default {
},
methods: {
addEnvironment(environment) {
const allEnvironmentsScope = this.environments.find(scope => scope.environmentScope === '*');
const allEnvironmentsScope = this.environments.find(
(scope) => scope.environmentScope === '*',
);
if (allEnvironmentsScope) {
allEnvironmentsScope.shouldBeDestroyed = true;
}
......@@ -113,7 +115,7 @@ export default {
if (isNumber(environment.id)) {
Vue.set(environment, 'shouldBeDestroyed', true);
} else {
this.environments = this.environments.filter(e => e !== environment);
this.environments = this.environments.filter((e) => e !== environment);
}
if (this.filteredEnvironments.length === 0) {
this.environments.push({ environmentScope: '*' });
......
......@@ -32,8 +32,8 @@ const filesWithChanges = ({ stagedFiles = [], changedFiles = [], entries = {} })
// We need to clean "move" actions, because we can only support 100% similarity moves at the moment.
// This is because the previous file's content might not be loaded.
Object.values(changes)
.filter(change => change.action === commitActionTypes.move)
.forEach(change => {
.filter((change) => change.action === commitActionTypes.move)
.forEach((change) => {
const prev = changes[change.file.prevPath];
if (!prev) {
......@@ -51,14 +51,14 @@ const filesWithChanges = ({ stagedFiles = [], changedFiles = [], entries = {} })
// Next, we need to add deleted directories by looking at the parents
Object.values(changes)
.filter(change => change.action === commitActionTypes.delete && change.file.parentPath)
.filter((change) => change.action === commitActionTypes.delete && change.file.parentPath)
.forEach(({ file }) => {
// Do nothing if we've already visited this directory.
if (changes[file.parentPath]) {
return;
}
getDeletedParents(entries, file).forEach(parent => {
getDeletedParents(entries, file).forEach((parent) => {
changes[parent.path] = { action: commitActionTypes.delete, file: parent };
});
});
......@@ -66,13 +66,15 @@ const filesWithChanges = ({ stagedFiles = [], changedFiles = [], entries = {} })
return Object.values(changes);
};
const createDiff = state => {
const createDiff = (state) => {
const changes = filesWithChanges(state);
const toDelete = changes.filter(x => x.action === commitActionTypes.delete).map(x => x.file.path);
const toDelete = changes
.filter((x) => x.action === commitActionTypes.delete)
.map((x) => x.file.path);
const patch = changes
.filter(x => x.action !== commitActionTypes.delete)
.filter((x) => x.action !== commitActionTypes.delete)
.map(({ file, action }) => createFileDiff(file, action))
.join('');
......
import { states } from './constants';
export const hasLatestPipeline = state => !state.isLoadingPipeline && Boolean(state.latestPipeline);
export const hasLatestPipeline = (state) =>
!state.isLoadingPipeline && Boolean(state.latestPipeline);
export const pipelineFailed = state =>
export const pipelineFailed = (state) =>
state.latestPipeline && state.latestPipeline.details.status.text === states.failed;
export const failedStages = state =>
export const failedStages = (state) =>
state.stages
.filter(stage => stage.status.text.toLowerCase() === states.failed)
.map(stage => ({
.filter((stage) => stage.status.text.toLowerCase() === states.failed)
.map((stage) => ({
...stage,
jobs: stage.jobs.filter(job => job.status.text.toLowerCase() === states.failed),
jobs: stage.jobs.filter((job) => job.status.text.toLowerCase() === states.failed),
}));
export const failedJobsCount = state =>
export const failedJobsCount = (state) =>
state.stages.reduce(
(acc, stage) => acc + stage.jobs.filter(j => j.status.text === states.failed).length,
(acc, stage) => acc + stage.jobs.filter((j) => j.status.text === states.failed).length,
0,
);
export const jobsCount = state => state.stages.reduce((acc, stage) => acc + stage.jobs.length, 0);
export const jobsCount = (state) => state.stages.reduce((acc, stage) => acc + stage.jobs.length, 0);
......@@ -34,7 +34,9 @@ export default {
computed: {
...mapState(['members', 'tableFields', 'tableAttrs', 'currentUserId', 'sourceId']),
filteredFields() {
return FIELDS.filter(field => this.tableFields.includes(field.key) && this.showField(field));
return FIELDS.filter(
(field) => this.tableFields.includes(field.key) && this.showField(field),
);
},
userIsLoggedIn() {
return this.currentUserId !== null;
......@@ -56,7 +58,7 @@ export default {
return false;
}
return this.members.some(member => {
return this.members.some((member) => {
return (
canRemove(member, this.sourceId) ||
canResend(member) ||
......
export const findMember = (state, memberId) => state.members.find(member => member.id === memberId);
export const findMember = (state, memberId) =>
state.members.find((member) => member.id === memberId);
......@@ -114,7 +114,7 @@ export const fetchDashboard = ({ state, commit, dispatch, getters }) => {
}
return getDashboard(state.dashboardEndpoint, params)
.then(response => {
.then((response) => {
dispatch('receiveMetricsDashboardSuccess', { response });
/**
* After the dashboard is fetched, there can be non-blocking invalid syntax
......@@ -125,7 +125,7 @@ export const fetchDashboard = ({ state, commit, dispatch, getters }) => {
*/
dispatch('fetchDashboardValidationWarnings');
})
.catch(error => {
.catch((error) => {
Sentry.captureException(error);
commit(types.SET_ALL_DASHBOARDS, error.response?.data?.all_dashboards ?? []);
......@@ -185,9 +185,9 @@ export const fetchDashboardData = ({ state, dispatch, getters }) => {
dispatch('fetchVariableMetricLabelValues', { defaultQueryParams });
const promises = [];
state.dashboard.panelGroups.forEach(group => {
group.panels.forEach(panel => {
panel.metrics.forEach(metric => {
state.dashboard.panelGroups.forEach((group) => {
group.panels.forEach((panel) => {
panel.metrics.forEach((metric) => {
promises.push(dispatch('fetchPrometheusMetric', { metric, defaultQueryParams }));
});
});
......@@ -231,10 +231,10 @@ export const fetchPrometheusMetric = (
commit(types.REQUEST_METRIC_RESULT, { metricId: metric.metricId });
return getPrometheusQueryData(metric.prometheusEndpointPath, queryParams)
.then(data => {
.then((data) => {
commit(types.RECEIVE_METRIC_RESULT_SUCCESS, { metricId: metric.metricId, data });
})
.catch(error => {
.catch((error) => {
Sentry.captureException(error);
commit(types.RECEIVE_METRIC_RESULT_FAILURE, { metricId: metric.metricId, error });
......@@ -251,15 +251,15 @@ export const fetchDeploymentsData = ({ state, dispatch }) => {
}
return axios
.get(state.deploymentsEndpoint)
.then(resp => resp.data)
.then(response => {
.then((resp) => resp.data)
.then((response) => {
if (!response || !response.deployments) {
createFlash(s__('Metrics|Unexpected deployment data response from prometheus endpoint'));
}
dispatch('receiveDeploymentsDataSuccess', response.deployments);
})
.catch(error => {
.catch((error) => {
Sentry.captureException(error);
dispatch('receiveDeploymentsDataFailure');
createFlash(s__('Metrics|There was an error getting deployment information.'));
......@@ -285,10 +285,10 @@ export const fetchEnvironmentsData = ({ state, dispatch }) => {
states: [ENVIRONMENT_AVAILABLE_STATE],
},
})
.then(resp =>
.then((resp) =>
parseEnvironmentsResponse(resp.data?.project?.data?.environments, state.projectPath),
)
.then(environments => {
.then((environments) => {
if (!environments) {
createFlash(
s__('Metrics|There was an error fetching the environments data, please try again'),
......@@ -297,7 +297,7 @@ export const fetchEnvironmentsData = ({ state, dispatch }) => {
dispatch('receiveEnvironmentsDataSuccess', environments);
})
.catch(err => {
.catch((err) => {
Sentry.captureException(err);
dispatch('receiveEnvironmentsDataFailure');
createFlash(s__('Metrics|There was an error getting environments information.'));
......@@ -326,16 +326,18 @@ export const fetchAnnotations = ({ state, dispatch, getters }) => {
startingFrom: start,
},
})
.then(resp => resp.data?.project?.environments?.nodes?.[0].metricsDashboard?.annotations.nodes)
.then(
(resp) => resp.data?.project?.environments?.nodes?.[0].metricsDashboard?.annotations.nodes,
)
.then(parseAnnotationsResponse)
.then(annotations => {
.then((annotations) => {
if (!annotations) {
createFlash(s__('Metrics|There was an error fetching annotations. Please try again.'));
}
dispatch('receiveAnnotationsSuccess', annotations);
})
.catch(err => {
.catch((err) => {
Sentry.captureException(err);
dispatch('receiveAnnotationsFailure');
createFlash(s__('Metrics|There was an error getting annotations information.'));
......@@ -363,7 +365,7 @@ export const fetchDashboardValidationWarnings = ({ state, dispatch, getters }) =
dashboardPath,
},
})
.then(resp => resp.data?.project?.environments?.nodes?.[0]?.metricsDashboard)
.then((resp) => resp.data?.project?.environments?.nodes?.[0]?.metricsDashboard)
.then(({ schemaValidationWarnings } = {}) => {
const hasWarnings = schemaValidationWarnings && schemaValidationWarnings.length !== 0;
/**
......@@ -372,7 +374,7 @@ export const fetchDashboardValidationWarnings = ({ state, dispatch, getters }) =
*/
dispatch('receiveDashboardValidationWarningsSuccess', hasWarnings || false);
})
.catch(err => {
.catch((err) => {
Sentry.captureException(err);
dispatch('receiveDashboardValidationWarningsFailure');
createFlash(
......@@ -437,9 +439,9 @@ export const duplicateSystemDashboard = ({ state }, payload) => {
return axios
.post(state.dashboardsEndpoint, params)
.then(response => response.data)
.then(data => data.dashboard)
.catch(error => {
.then((response) => response.data)
.then((data) => data.dashboard)
.catch((error) => {
Sentry.captureException(error);
const { response } = error;
......@@ -466,7 +468,7 @@ export const fetchVariableMetricLabelValues = ({ state, commit }, { defaultQuery
const { start_time, end_time } = defaultQueryParams;
const optionsRequests = [];
state.variables.forEach(variable => {
state.variables.forEach((variable) => {
if (variable.type === VARIABLE_TYPES.metric_label_values) {
const { prometheusEndpointPath, label } = variable.options;
......@@ -474,7 +476,7 @@ export const fetchVariableMetricLabelValues = ({ state, commit }, { defaultQuery
start_time,
end_time,
})
.then(data => {
.then((data) => {
commit(types.UPDATE_VARIABLE_METRIC_LABEL_VALUES, { variable, label, data });
})
.catch(() => {
......@@ -512,7 +514,7 @@ export const fetchPanelPreview = ({ state, commit, dispatch }, panelPreviewYml)
dispatch('fetchPanelPreviewMetrics');
})
.catch(error => {
.catch((error) => {
commit(types.RECEIVE_PANEL_PREVIEW_FAILURE, extractErrorMessage(error));
});
};
......@@ -535,10 +537,10 @@ export const fetchPanelPreviewMetrics = ({ state, commit }) => {
return getPrometheusQueryData(metric.prometheusEndpointPath, params, {
cancelToken: cancelTokenSource.token,
})
.then(data => {
.then((data) => {
commit(types.RECEIVE_PANEL_PREVIEW_METRIC_RESULT_SUCCESS, { index, data });
})
.catch(error => {
.catch((error) => {
Sentry.captureException(error);
commit(types.RECEIVE_PANEL_PREVIEW_METRIC_RESULT_FAILURE, { index, error });
......
......@@ -5,8 +5,10 @@ import {
normalizeCustomDashboardPath,
} from './utils';
const metricsIdsInPanel = panel =>
panel.metrics.filter(metric => metric.metricId && metric.result).map(metric => metric.metricId);
const metricsIdsInPanel = (panel) =>
panel.metrics
.filter((metric) => metric.metricId && metric.result)
.map((metric) => metric.metricId);
/**
* Returns a reference to the currently selected dashboard
......@@ -17,8 +19,8 @@ const metricsIdsInPanel = panel =>
export const selectedDashboard = (state, getters) => {
const { allDashboards } = state;
return (
allDashboards.find(d => d.path === getters.fullDashboardPath) ||
allDashboards.find(d => d.default) ||
allDashboards.find((d) => d.path === getters.fullDashboardPath) ||
allDashboards.find((d) => d.default) ||
null
);
};
......@@ -32,15 +34,15 @@ export const selectedDashboard = (state, getters) => {
* @returns {Function} A function that returns an array of
* states in all the metric in the dashboard or group.
*/
export const getMetricStates = state => groupKey => {
export const getMetricStates = (state) => (groupKey) => {
let groups = state.dashboard.panelGroups;
if (groupKey) {
groups = groups.filter(group => group.key === groupKey);
groups = groups.filter((group) => group.key === groupKey);
}
const metricStates = groups.reduce((acc, group) => {
group.panels.forEach(panel => {
panel.metrics.forEach(metric => {
group.panels.forEach((panel) => {
panel.metrics.forEach((metric) => {
if (metric.state) {
acc.push(metric.state);
}
......@@ -64,15 +66,15 @@ export const getMetricStates = state => groupKey => {
* metrics in the dashboard that contain results, optionally
* filtered by group key.
*/
export const metricsWithData = state => groupKey => {
export const metricsWithData = (state) => (groupKey) => {
let groups = state.dashboard.panelGroups;
if (groupKey) {
groups = groups.filter(group => group.key === groupKey);
groups = groups.filter((group) => group.key === groupKey);
}
const res = [];
groups.forEach(group => {
group.panels.forEach(panel => {
groups.forEach((group) => {
group.panels.forEach((panel) => {
res.push(...metricsIdsInPanel(panel));
});
});
......@@ -89,7 +91,7 @@ export const metricsWithData = state => groupKey => {
* https://gitlab.com/gitlab-org/gitlab/-/issues/28241
* https://gitlab.com/gitlab-org/gitlab/-/merge_requests/27447
*/
export const metricsSavedToDb = state => {
export const metricsSavedToDb = (state) => {
const metricIds = [];
state.dashboard.panelGroups.forEach(({ panels }) => {
panels.forEach(({ metrics }) => {
......@@ -111,8 +113,8 @@ export const metricsSavedToDb = state => {
* @param {Object} state
* @returns {Array} List of environments
*/
export const filteredEnvironments = state =>
state.environments.filter(env =>
export const filteredEnvironments = (state) =>
state.environments.filter((env) =>
env.name.toLowerCase().includes((state.environmentsSearchTerm || '').trim().toLowerCase()),
);
......@@ -125,7 +127,7 @@ export const filteredEnvironments = state =>
* @param {Object} state
* @returns {Array} modified array of links
*/
export const linksWithMetadata = state => {
export const linksWithMetadata = (state) => {
const metadata = {
timeRange: state.timeRange,
};
......@@ -152,7 +154,7 @@ export const linksWithMetadata = state => {
* in the format of {variables[key1]=value1, variables[key2]=value2}
*/
export const getCustomVariablesParams = state =>
export const getCustomVariablesParams = (state) =>
state.variables.reduce((acc, variable) => {
const { name, value } = variable;
if (value !== null) {
......@@ -168,5 +170,5 @@ export const getCustomVariablesParams = state =>
* @param {Object} state
* @returns {String} full dashboard path
*/
export const fullDashboardPath = state =>
export const fullDashboardPath = (state) =>
normalizeCustomDashboardPath(state.currentDashboard, state.customDashboardBasePath);
import { LIST_KEY_PROJECT, SORT_FIELDS } from './constants';
export default isGroupPage => SORT_FIELDS.filter(f => f.key !== LIST_KEY_PROJECT || isGroupPage);
export default (isGroupPage) =>
SORT_FIELDS.filter((f) => f.key !== LIST_KEY_PROJECT || isGroupPage);
/**
* A small util function that works out if the delete action has deleted the
......
......@@ -31,7 +31,9 @@ export default {
},
computed: {
filteredNamespaces() {
return this.namespaces.filter(n => n.name.toLowerCase().includes(this.filter.toLowerCase()));
return this.namespaces.filter((n) =>
n.name.toLowerCase().includes(this.filter.toLowerCase()),
);
},
},
......@@ -43,7 +45,7 @@ export default {
loadGroups() {
axios
.get(this.endpoint)
.then(response => {
.then((response) => {
this.namespaces = response.data.namespaces;
})
.catch(() => createFlash(__('There was a problem fetching groups.')));
......
......@@ -100,8 +100,8 @@ export default class UserTabs {
bindEvents() {
this.$parentEl
.off('shown.bs.tab', '.nav-links a[data-toggle="tab"]')
.on('shown.bs.tab', '.nav-links a[data-toggle="tab"]', event => this.tabShown(event))
.on('click', '.gl-pagination a', event => this.changeProjectsPage(event));
.on('shown.bs.tab', '.nav-links a[data-toggle="tab"]', (event) => this.tabShown(event))
.on('click', '.gl-pagination a', (event) => this.changeProjectsPage(event));
window.addEventListener('resize', () => this.onResize());
}
......@@ -212,12 +212,14 @@ export default class UserTabs {
const calendarPath = $calendarWrap.data('calendarPath');
AjaxCache.retrieve(calendarPath)
.then(data => UserTabs.renderActivityCalendar(data, $calendarWrap))
.then((data) => UserTabs.renderActivityCalendar(data, $calendarWrap))
.catch(() => {
const cWrap = $calendarWrap[0];
cWrap.querySelector('.spinner').classList.add('invisible');
cWrap.querySelector('.user-calendar-error').classList.remove('invisible');
cWrap.querySelector('.user-calendar-error .js-retry-load').addEventListener('click', e => {
cWrap
.querySelector('.user-calendar-error .js-retry-load')
.addEventListener('click', (e) => {
e.preventDefault();
cWrap.querySelector('.user-calendar-error').classList.add('invisible');
cWrap.querySelector('.spinner').classList.remove('invisible');
......
......@@ -25,7 +25,7 @@ export default class AccessDropdown {
this.setSelectedItems([]);
this.persistPreselectedItems();
this.noOneObj = this.accessLevelsData.find(level => level.id === ACCESS_LEVEL_NONE);
this.noOneObj = this.accessLevelsData.find((level) => level.id === ACCESS_LEVEL_NONE);
this.initDropdown();
}
......@@ -45,7 +45,7 @@ export default class AccessDropdown {
onHide();
}
},
clicked: options => {
clicked: (options) => {
const { $el, e } = options;
const item = options.selectedObj;
const fossWithMergeAccess = !this.hasLicense && this.accessLevel === ACCESS_LEVELS.MERGE;
......@@ -56,7 +56,7 @@ export default class AccessDropdown {
// We're not multiselecting quite yet in "Merge" access dropdown, on FOSS:
// remove all preselected items before selecting this item
// https://gitlab.com/gitlab-org/gitlab/-/merge_requests/37499
this.accessLevelsData.forEach(level => {
this.accessLevelsData.forEach((level) => {
this.removeSelectedItem(level);
});
}
......@@ -65,7 +65,7 @@ export default class AccessDropdown {
if (this.noOneObj) {
if (item.id === this.noOneObj.id && !fossWithMergeAccess) {
// remove all others selected items
this.accessLevelsData.forEach(level => {
this.accessLevelsData.forEach((level) => {
if (level.id !== item.id) {
this.removeSelectedItem(level);
}
......@@ -109,7 +109,7 @@ export default class AccessDropdown {
return;
}
const persistedItems = itemsToPreselect.map(item => {
const persistedItems = itemsToPreselect.map((item) => {
const persistedItem = { ...item };
persistedItem.persisted = true;
return persistedItem;
......@@ -123,7 +123,7 @@ export default class AccessDropdown {
}
getSelectedItems() {
return this.items.filter(item => !item._destroy);
return this.items.filter((item) => !item._destroy);
}
getAllSelectedItems() {
......@@ -134,7 +134,7 @@ export default class AccessDropdown {
getInputData() {
const selectedItems = this.getAllSelectedItems();
const accessLevels = selectedItems.map(item => {
const accessLevels = selectedItems.map((item) => {
const obj = {};
if (typeof item.id !== 'undefined') {
......@@ -288,12 +288,14 @@ export default class AccessDropdown {
$dropdownToggleText.removeClass('is-default');
if (currentItems.length === 1 && currentItems[0].type === LEVEL_TYPES.ROLE) {
const roleData = this.accessLevelsData.find(data => data.id === currentItems[0].access_level);
const roleData = this.accessLevelsData.find(
(data) => data.id === currentItems[0].access_level,
);
return roleData.text;
}
const labelPieces = [];
const counts = countBy(currentItems, item => item.type);
const counts = countBy(currentItems, (item) => item.type);
if (counts[LEVEL_TYPES.ROLE] > 0) {
labelPieces.push(n__('1 role', '%d roles', counts[LEVEL_TYPES.ROLE]));
......@@ -336,7 +338,7 @@ export default class AccessDropdown {
});
} else {
this.getDeployKeys(query)
.then(deployKeysResponse => callback(this.consolidateData(deployKeysResponse.data)))
.then((deployKeysResponse) => callback(this.consolidateData(deployKeysResponse.data)))
.catch(() => createFlash({ message: __('Failed to load deploy keys.') }));
}
}
......@@ -365,7 +367,7 @@ export default class AccessDropdown {
/*
* Build roles
*/
const roles = this.accessLevelsData.map(level => {
const roles = this.accessLevelsData.map((level) => {
/* eslint-disable no-param-reassign */
// This re-assignment is intentional as
// level.type property is being used in removeSelectedItem()
......@@ -389,7 +391,7 @@ export default class AccessDropdown {
/*
* Build groups
*/
const groups = groupsResponse.map(group => ({
const groups = groupsResponse.map((group) => ({
...group,
type: LEVEL_TYPES.GROUP,
}));
......@@ -398,8 +400,8 @@ export default class AccessDropdown {
* Build users
*/
const users = selectedItems
.filter(item => item.type === LEVEL_TYPES.USER)
.map(item => {
.filter((item) => item.type === LEVEL_TYPES.USER)
.map((item) => {
// Save identifiers for easy-checking more later
map.push(LEVEL_TYPES.USER + item.user_id);
......@@ -414,7 +416,7 @@ export default class AccessDropdown {
// Has to be checked against server response
// because the selected item can be in filter results
usersResponse.forEach(response => {
usersResponse.forEach((response) => {
// Add is it has not been added
if (map.indexOf(LEVEL_TYPES.USER + response.id) === -1) {
const user = { ...response };
......@@ -444,7 +446,7 @@ export default class AccessDropdown {
}
if (this.deployKeysOnProtectedBranchesEnabled) {
const deployKeys = deployKeysResponse.map(response => {
const deployKeys = deployKeysResponse.map((response) => {
const {
id,
fingerprint,
......
......@@ -9,7 +9,9 @@ const fetchpromises = {};
const resolvers = {};
export function resolveCommit(commits, path, { resolve, entry }) {
const commit = commits.find(c => c.filePath === `${path}/${entry.name}` && c.type === entry.type);
const commit = commits.find(
(c) => c.filePath === `${path}/${entry.name}` && c.type === entry.type,
);
if (commit) {
resolve(commit);
......@@ -42,7 +44,7 @@ export function fetchLogsTree(client, path, offset, resolver = null) {
.then(({ data: newData, headers }) => {
const headerLogsOffset = headers['more-logs-offset'];
const sourceData = client.readQuery({ query: commitsQuery });
const data = produce(sourceData, draftState => {
const data = produce(sourceData, (draftState) => {
draftState.commits.push(...normalizeData(newData, path));
});
client.writeQuery({
......@@ -50,7 +52,7 @@ export function fetchLogsTree(client, path, offset, resolver = null) {
data,
});
resolvers[path].forEach(r => resolveCommit(data.commits, path, r));
resolvers[path].forEach((r) => resolveCommit(data.commits, path, r));
delete fetchpromises[path];
......
import { joinPaths } from '~/lib/utils/url_utility';
export const updateElementsVisibility = (selector, isVisible) => {
document.querySelectorAll(selector).forEach(elem => elem.classList.toggle('hidden', !isVisible));
document
.querySelectorAll(selector)
.forEach((elem) => elem.classList.toggle('hidden', !isVisible));
};
export const updateFormAction = (selector, basePath, path) => {
......
......@@ -50,9 +50,13 @@ export default {
$(this.$el).trigger('hidden.gl.dropdown');
},
getUpdateVariables(dropdownLabels) {
const currentLabelIds = this.selectedLabels.map(label => label.id);
const userAddedLabelIds = dropdownLabels.filter(label => label.set).map(label => label.id);
const userRemovedLabelIds = dropdownLabels.filter(label => !label.set).map(label => label.id);
const currentLabelIds = this.selectedLabels.map((label) => label.id);
const userAddedLabelIds = dropdownLabels
.filter((label) => label.set)
.map((label) => label.id);
const userRemovedLabelIds = dropdownLabels
.filter((label) => !label.set)
.map((label) => label.id);
const labelIds = difference(union(currentLabelIds, userAddedLabelIds), userRemovedLabelIds);
......@@ -116,7 +120,7 @@ export default {
}
const issuableType = camelCase(this.issuableType);
this.selectedLabels = data[mutationName]?.[issuableType]?.labels?.nodes?.map(label => ({
this.selectedLabels = data[mutationName]?.[issuableType]?.labels?.nodes?.map((label) => ({
...label,
id: getIdFromGraphQLId(label.id),
}));
......
export const parseUserIds = userIds => userIds.split(/\s*,\s*/g);
export const parseUserIds = (userIds) => userIds.split(/\s*,\s*/g);
export const stringifyUserIds = userIds => userIds.join(',');
export const stringifyUserIds = (userIds) => userIds.join(',');
export const getErrorMessages = error => [].concat(error?.response?.data?.message ?? error.message);
export const getErrorMessages = (error) =>
[].concat(error?.response?.data?.message ?? error.message);
......@@ -49,7 +49,8 @@ export default {
label: s__('AlertManagement|Key'),
thClass,
tdClass,
formatter: string => capitalizeFirstCharacter(convertToSentenceCase(splitCamelCase(string))),
formatter: (string) =>
capitalizeFirstCharacter(convertToSentenceCase(splitCamelCase(string))),
},
{
key: 'value',
......
......@@ -62,7 +62,9 @@ export default {
return files.every(this.isFileValid);
},
isValidDragDataType({ dataTransfer }) {
return Boolean(dataTransfer && dataTransfer.types.some(t => t === VALID_DATA_TRANSFER_TYPE));
return Boolean(
dataTransfer && dataTransfer.types.some((t) => t === VALID_DATA_TRANSFER_TYPE),
);
},
ondrop({ dataTransfer = {} }) {
this.dragCounter = 0;
......
......@@ -54,5 +54,6 @@ export const timeRanges = [
},
];
export const defaultTimeRange = timeRanges.find(tr => tr.default);
export const getTimeWindow = timeWindowName => timeRanges.find(tr => tr.name === timeWindowName);
export const defaultTimeRange = timeRanges.find((tr) => tr.default);
export const getTimeWindow = (timeWindowName) =>
timeRanges.find((tr) => tr.name === timeWindowName);
......@@ -28,11 +28,12 @@ export const removeFlash = (type = 'alert') => {
export const toggleSelectedLabel = ({ selectedLabelIds = [], value = null }) => {
if (!value) return selectedLabelIds;
return selectedLabelIds.includes(value)
? selectedLabelIds.filter(v => v !== value)
? selectedLabelIds.filter((v) => v !== value)
: [...selectedLabelIds, value];
};
export const isStartEvent = ev => Boolean(ev) && Boolean(ev.canBeStartEvent) && ev.canBeStartEvent;
export const isStartEvent = (ev) =>
Boolean(ev) && Boolean(ev.canBeStartEvent) && ev.canBeStartEvent;
export const eventToOption = (obj = null) => {
if (!obj || (!obj.text && !obj.identifier)) return null;
......@@ -55,7 +56,7 @@ export const isLabelEvent = (labelEvents = [], ev = null) =>
Boolean(ev) && labelEvents.length && labelEvents.includes(ev);
export const getLabelEventsIdentifiers = (events = []) =>
events.filter(ev => ev.type && ev.type === EVENT_TYPE_LABEL).map(i => i.identifier);
events.filter((ev) => ev.type && ev.type === EVENT_TYPE_LABEL).map((i) => i.identifier);
/**
* Checks if the specified stage is in memory or persisted to storage based on the id
......@@ -101,7 +102,7 @@ export const transformRawStages = (stages = []) =>
export const transformRawTasksByTypeData = (data = []) => {
if (!data.length) return [];
return data.map(d => convertObjectPropsToCamelCase(d, { deep: true }));
return data.map((d) => convertObjectPropsToCamelCase(d, { deep: true }));
};
/**
......@@ -137,10 +138,10 @@ export const transformRawTasksByTypeData = (data = []) => {
* @param {Array} data - The duration data for selected stages
* @returns {Array} An array with each item being an object containing the duration_in_seconds and finished_at values for an event
*/
export const flattenDurationChartData = data =>
export const flattenDurationChartData = (data) =>
data
.map(stage =>
stage.data.map(event => {
.map((stage) =>
stage.data.map((event) => {
const date = new Date(event.finished_at);
return {
...event,
......@@ -202,7 +203,7 @@ export const getDurationChartData = (data, startDate, endDate) => {
currentDate = dayAfter(currentDate)
) {
const currentISODate = dateFormat(newDate(currentDate), dateFormats.isoDate);
const valuesForDay = flattenedData.filter(object => object.finished_at === currentISODate);
const valuesForDay = flattenedData.filter((object) => object.finished_at === currentISODate);
const summedData = valuesForDay.reduce((total, value) => total + value.duration_in_seconds, 0);
const summedDataInDays = secondsToDays(summedData);
......@@ -212,7 +213,7 @@ export const getDurationChartData = (data, startDate, endDate) => {
return eventData;
};
export const orderByDate = (a, b, dateFmt = datetime => new Date(datetime).getTime()) =>
export const orderByDate = (a, b, dateFmt = (datetime) => new Date(datetime).getTime()) =>
dateFmt(a) - dateFmt(b);
/**
......@@ -224,7 +225,7 @@ export const orderByDate = (a, b, dateFmt = datetime => new Date(datetime).getTi
export const flattenTaskByTypeSeries = (series = {}) =>
Object.entries(series)
.sort((a, b) => orderByDate(a[0], b[0]))
.map(dataSet => dataSet[1]);
.map((dataSet) => dataSet[1]);
/**
* @typedef {Object} RawTasksByTypeData
......@@ -325,7 +326,7 @@ export const flashErrorIfStatusNotOk = ({ error, message }) => {
* @param {Object} Response - Axios ajax response
* @returns {Object} Returns the axios ajax response
*/
export const checkForDataError = response => {
export const checkForDataError = (response) => {
const { data, status } = response;
if (data?.error) {
throw buildDataError({ status, error: data.error });
......@@ -333,7 +334,7 @@ export const checkForDataError = response => {
return response;
};
export const throwIfUserForbidden = error => {
export const throwIfUserForbidden = (error) => {
if (error?.response?.status === httpStatus.FORBIDDEN) {
throw error;
}
......@@ -352,7 +353,7 @@ export const isStageNameExistsError = ({ status, errors }) =>
* @returns {Array} An array of stages formatted with data required for the path navigation
*/
export const transformStagesForPathNavigation = ({ stages, medians, selectedStage }) => {
const formattedStages = stages.map(stage => {
const formattedStages = stages.map((stage) => {
const { days } = parseSeconds(medians[stage.id], {
daysPerWeek: 7,
hoursPerDay: 24,
......
......@@ -41,7 +41,7 @@ export default {
},
update(data) {
return (
data.group?.projects?.nodes?.map(project => ({
data.group?.projects?.nodes?.map((project) => ({
...project,
parsedId: getIdFromGraphQLId(project.id),
isSelected: false,
......@@ -66,7 +66,7 @@ export default {
},
computed: {
filteredProjects() {
return this.groupProjects.filter(project =>
return this.groupProjects.filter((project) =>
project.name.toLowerCase().includes(this.projectSearchTerm.toLowerCase()),
);
},
......@@ -80,19 +80,21 @@ export default {
return __('Select projects');
},
selectedProjectIds() {
return this.groupProjects.filter(project => project.isSelected).map(project => project.id);
return this.groupProjects
.filter((project) => project.isSelected)
.map((project) => project.id);
},
},
methods: {
clickDropdownProject(id) {
const index = this.groupProjects.map(project => project.id).indexOf(id);
const index = this.groupProjects.map((project) => project.id).indexOf(id);
this.groupProjects[index].isSelected = !this.groupProjects[index].isSelected;
this.selectAllProjects = false;
this.$emit('select-project', this.groupProjects[index]);
},
clickSelectAllProjects() {
this.selectAllProjects = true;
this.groupProjects = this.groupProjects.map(project => ({
this.groupProjects = this.groupProjects.map((project) => ({
...project,
isSelected: false,
}));
......@@ -109,7 +111,7 @@ export default {
after: this.projectsPageInfo.endCursor,
},
updateQuery(previousResult, { fetchMoreResult }) {
const results = produce(fetchMoreResult, draftData => {
const results = produce(fetchMoreResult, (draftData) => {
// eslint-disable-next-line no-param-reassign
draftData.group.projects.nodes = [
...previousResult.group.projects.nodes,
......
......@@ -3,22 +3,24 @@ import gettersCE from '~/boards/stores/getters';
export default {
...gettersCE,
isSwimlanesOn: state => {
isSwimlanesOn: (state) => {
return Boolean(gon?.features?.swimlanes && state.isShowingEpicsSwimlanes);
},
getIssuesByEpic: (state, getters) => (listId, epicId) => {
return getters.getIssuesByList(listId).filter(issue => issue.epic && issue.epic.id === epicId);
return getters
.getIssuesByList(listId)
.filter((issue) => issue.epic && issue.epic.id === epicId);
},
getUnassignedIssues: (state, getters) => listId => {
return getters.getIssuesByList(listId).filter(i => Boolean(i.epic) === false);
getUnassignedIssues: (state, getters) => (listId) => {
return getters.getIssuesByList(listId).filter((i) => Boolean(i.epic) === false);
},
getEpicById: state => epicId => {
return state.epics.find(epic => epic.id === epicId);
getEpicById: (state) => (epicId) => {
return state.epics.find((epic) => epic.id === epicId);
},
shouldUseGraphQL: state => {
shouldUseGraphQL: (state) => {
return state.isShowingEpicsSwimlanes || gon?.features?.graphqlBoardLists;
},
};
......@@ -4,9 +4,10 @@ import { getTimeago } from '~/lib/utils/datetime_utility';
export const generatedAtTimeAgo = ({ reportInfo: { generatedAt } }) =>
generatedAt ? getTimeago().format(generatedAt) : '';
export const isJobNotSetUp = state => state.reportInfo.status === REPORT_STATUS.jobNotSetUp;
export const isJobFailed = state => state.reportInfo.status === REPORT_STATUS.jobFailed;
export const isIncomplete = state => state.reportInfo.status === REPORT_STATUS.incomplete;
export const hasNoDependencies = state => state.reportInfo.status === REPORT_STATUS.noDependencies;
export const isJobNotSetUp = (state) => state.reportInfo.status === REPORT_STATUS.jobNotSetUp;
export const isJobFailed = (state) => state.reportInfo.status === REPORT_STATUS.jobFailed;
export const isIncomplete = (state) => state.reportInfo.status === REPORT_STATUS.incomplete;
export const hasNoDependencies = (state) =>
state.reportInfo.status === REPORT_STATUS.noDependencies;
export const downloadEndpoint = ({ endpoint }) => endpoint;
......@@ -4,24 +4,25 @@ import epicUtils from '../utils/epic_utils';
import { statusType } from '../constants';
export const isEpicOpen = state => state.state === statusType.open;
export const isEpicOpen = (state) => state.state === statusType.open;
export const isUserSignedIn = () => Boolean(gon.current_user_id);
export const startDateTime = state => (state.startDate ? parsePikadayDate(state.startDate) : null);
export const startDateTime = (state) =>
state.startDate ? parsePikadayDate(state.startDate) : null;
export const startDateTimeFixed = state =>
export const startDateTimeFixed = (state) =>
state.startDateFixed ? parsePikadayDate(state.startDateFixed) : null;
export const startDateTimeFromMilestones = state =>
export const startDateTimeFromMilestones = (state) =>
state.startDateFromMilestones ? parsePikadayDate(state.startDateFromMilestones) : null;
export const dueDateTime = state => (state.dueDate ? parsePikadayDate(state.dueDate) : null);
export const dueDateTime = (state) => (state.dueDate ? parsePikadayDate(state.dueDate) : null);
export const dueDateTimeFixed = state =>
export const dueDateTimeFixed = (state) =>
state.dueDateFixed ? parsePikadayDate(state.dueDateFixed) : null;
export const dueDateTimeFromMilestones = state =>
export const dueDateTimeFromMilestones = (state) =>
state.dueDateFromMilestones ? parsePikadayDate(state.dueDateFromMilestones) : null;
export const startDateForCollapsedSidebar = (state, getters) =>
......@@ -55,4 +56,4 @@ export const isDateInvalid = (state, getters) => {
);
};
export const ancestors = state => (state.ancestors ? [...state.ancestors].reverse() : []);
export const ancestors = (state) => (state.ancestors ? [...state.ancestors].reverse() : []);
......@@ -35,7 +35,7 @@ export default {
return this.pageConfig.charts;
},
chartKeys() {
return this.charts.map(chart => chart.title);
return this.charts.map((chart) => chart.title);
},
hasChartsConfigured() {
return !isUndefined(this.charts) && this.charts.length > 0;
......@@ -55,7 +55,9 @@ export default {
if (this.hasChartsConfigured) {
this.initChartData(this.chartKeys);
this.charts.forEach(chart => this.fetchChartData({ endpoint: this.queryEndpoint, chart }));
this.charts.forEach((chart) =>
this.fetchChartData({ endpoint: this.queryEndpoint, chart }),
);
}
},
},
......
......@@ -29,7 +29,9 @@ export default class UsernameSuggester {
throw new Error('The API path was not specified.');
}
this.sourceElements = sourceElementsIds.map(id => document.getElementById(id)).filter(Boolean);
this.sourceElements = sourceElementsIds
.map((id) => document.getElementById(id))
.filter(Boolean);
this.isLoading = false;
this.debouncedSuggestWrapper = debounce(
this.suggestUsername.bind(this),
......@@ -42,7 +44,7 @@ export default class UsernameSuggester {
}
bindEvents() {
this.sourceElements.forEach(sourceElement => {
this.sourceElements.forEach((sourceElement) => {
sourceElement.addEventListener('change', this.debouncedSuggestWrapper);
});
}
......@@ -76,7 +78,7 @@ export default class UsernameSuggester {
*/
joinSources() {
return this.sourceElements
.map(el => el.value)
.map((el) => el.value)
.filter(Boolean)
.join('_');
}
......@@ -84,7 +86,7 @@ export default class UsernameSuggester {
cleanup() {
window.removeEventListener('beforeunload', this.cleanupWrapper);
this.sourceElements.forEach(sourceElement =>
this.sourceElements.forEach((sourceElement) =>
sourceElement.removeEventListener('change', this.debouncedSuggestWrapper),
);
}
......
......@@ -49,7 +49,7 @@ export default {
},
[types.SET_ITEM_CHILDREN_FLAGS](state, { children }) {
children.forEach(item => {
children.forEach((item) => {
Vue.set(state.childrenFlags, item.reference, {
itemExpanded: false,
itemChildrenFetchInProgress: false,
......@@ -166,7 +166,9 @@ export default {
},
[types.ADD_PENDING_REFERENCES](state, references) {
const nonDuplicateReferences = references.filter(ref => !state.pendingReferences.includes(ref));
const nonDuplicateReferences = references.filter(
(ref) => !state.pendingReferences.includes(ref),
);
state.pendingReferences.push(...nonDuplicateReferences);
},
......
......@@ -70,7 +70,8 @@ export default {
},
update({ project = {} }) {
const { available = [], enabled = [], pipelineRun = [] } = project?.securityScanners || {};
const translateScannerName = scannerName => this.$options.i18n[scannerName] || scannerName;
const translateScannerName = (scannerName) =>
this.$options.i18n[scannerName] || scannerName;
return {
available: available.map(translateScannerName),
......@@ -97,7 +98,7 @@ export default {
this.$apollo.queries.vulnerabilities.fetchMore({
variables: { after: this.pageInfo.endCursor },
updateQuery: (previousResult, { fetchMoreResult }) => {
const results = produce(fetchMoreResult, draftData => {
const results = produce(fetchMoreResult, (draftData) => {
// eslint-disable-next-line no-param-reassign
draftData.project.vulnerabilities.nodes = [
...previousResult.project.vulnerabilities.nodes,
......
......@@ -47,9 +47,9 @@ describe('GroupsDropdownFilter component', () => {
const findDropdownItems = () =>
findDropdown()
.findAll(GlDropdownItem)
.filter(w => w.text() !== 'No matching results');
.filter((w) => w.text() !== 'No matching results');
const findDropdownAtIndex = index => findDropdownItems().at(index);
const findDropdownAtIndex = (index) => findDropdownItems().at(index);
const findDropdownButton = () => findDropdown().find('.dropdown-toggle');
const findDropdownButtonAvatar = () => findDropdown().find('.gl-avatar');
......@@ -58,7 +58,8 @@ describe('GroupsDropdownFilter component', () => {
expect(dropdown.find('div.gl-avatar-identicon').exists()).toBe(hasIdenticon);
};
const selectDropdownAtIndex = index => findDropdownAtIndex(index).find('button').trigger('click');
const selectDropdownAtIndex = (index) =>
findDropdownAtIndex(index).find('button').trigger('click');
describe('when passed a defaultGroup as prop', () => {
beforeEach(() => {
......
......@@ -59,22 +59,23 @@ describe('ProjectsDropdownFilter component', () => {
const findDropdownItems = () =>
findDropdown()
.findAll(GlDropdownItem)
.filter(w => w.text() !== 'No matching results');
.filter((w) => w.text() !== 'No matching results');
const findDropdownAtIndex = index => findDropdownItems().at(index);
const findDropdownAtIndex = (index) => findDropdownItems().at(index);
const findDropdownButton = () => findDropdown().find('.dropdown-toggle');
const findDropdownButtonAvatar = () => findDropdown().find('.gl-avatar');
const findDropdownButtonAvatarAtIndex = index => findDropdownAtIndex(index).find('img.gl-avatar');
const findDropdownButtonIdentIconAtIndex = index =>
const findDropdownButtonAvatarAtIndex = (index) =>
findDropdownAtIndex(index).find('img.gl-avatar');
const findDropdownButtonIdentIconAtIndex = (index) =>
findDropdownAtIndex(index).find('div.gl-avatar-identicon');
const findDropdownNameAtIndex = index =>
const findDropdownNameAtIndex = (index) =>
findDropdownAtIndex(index).find('[data-testid="project-name"');
const findDropdownFullPathAtIndex = index =>
const findDropdownFullPathAtIndex = (index) =>
findDropdownAtIndex(index).find('[data-testid="project-full-path"]');
const selectDropdownItemAtIndex = index =>
const selectDropdownItemAtIndex = (index) =>
findDropdownAtIndex(index).find('button').trigger('click');
describe('queryParams are applied when fetching data', () => {
......
......@@ -50,7 +50,9 @@ describe('ApproversList', () => {
it('renders items', () => {
factory();
const items = wrapper.findAll(ApproversListItem).wrappers.map(item => item.props('approver'));
const items = wrapper
.findAll(ApproversListItem)
.wrappers.map((item) => item.props('approver'));
expect(items).toEqual(TEST_APPROVERS);
});
......
......@@ -10,7 +10,7 @@ localVue.use(Vuex);
const TEST_RULE = { id: 10 };
const findButtonLabel = button => button.attributes('aria-label') || button.text();
const findButtonLabel = (button) => button.attributes('aria-label') || button.text();
const hasLabel = (button, label) => findButtonLabel(button) === label;
describe('EE Approvals RuleControls', () => {
......@@ -28,14 +28,17 @@ describe('EE Approvals RuleControls', () => {
});
};
const findButtons = () => wrapper.findAll(GlButton);
const findButton = label => findButtons().filter(button => hasLabel(button, label)).wrappers[0];
const findButton = (label) =>
findButtons().filter((button) => hasLabel(button, label)).wrappers[0];
const findEditButton = () => findButton('Edit');
const findRemoveButton = () => findButton('Remove');
beforeEach(() => {
store = createStoreOptions(MREditModule());
({ actions } = store.modules.approvals);
['requestEditRule', 'requestDeleteRule'].forEach(actionName => jest.spyOn(actions, actionName));
['requestEditRule', 'requestDeleteRule'].forEach((actionName) =>
jest.spyOn(actions, actionName),
);
});
afterEach(() => {
......
......@@ -10,7 +10,8 @@ describe('AuditEventsFilter', () => {
const value = [{ type: 'project', value: { data: 1, operator: '=' } }];
const findFilteredSearch = () => wrapper.find(GlFilteredSearch);
const getAvailableTokens = () => findFilteredSearch().props('availableTokens');
const getAvailableTokenProps = type => getAvailableTokens().find(token => token.type === type);
const getAvailableTokenProps = (type) =>
getAvailableTokens().find((token) => token.type === type);
const initComponent = (props = {}) => {
wrapper = shallowMount(AuditEventsFilter, {
......
......@@ -25,7 +25,7 @@ describe('DependenciesTable component', () => {
const findTableRows = () => wrapper.findAll('tbody > tr');
const findRowToggleButtons = () => wrapper.findAll(GlButton);
const findDependencyVulnerabilities = () => wrapper.find(DependencyVulnerabilities);
const normalizeWhitespace = string => string.replace(/\s+/g, ' ');
const normalizeWhitespace = (string) => string.replace(/\s+/g, ' ');
const expectDependencyRow = (rowWrapper, dependency) => {
const [
......@@ -97,7 +97,7 @@ describe('DependenciesTable component', () => {
const expectedLabels = DependenciesTable.fields.map(({ label }) => label);
const headerCells = wrapper.findAll('thead th').wrappers;
expect(headerCells.map(cell => cell.text())).toEqual(expectedLabels);
expect(headerCells.map((cell) => cell.text())).toEqual(expectedLabels);
});
it('does not render any rows', () => {
......@@ -189,7 +189,9 @@ describe('DependenciesTable component', () => {
let rowIndexWithVulnerabilities;
beforeEach(() => {
rowIndexWithVulnerabilities = dependencies.findIndex(dep => dep.vulnerabilities.length > 0);
rowIndexWithVulnerabilities = dependencies.findIndex(
(dep) => dep.vulnerabilities.length > 0,
);
});
it('can be displayed by clicking on the toggle button', () => {
......
......@@ -61,7 +61,7 @@ describe('GeoNodeFormCapacities', () => {
const findGeoNodeFormReverificationIntervalField = () =>
wrapper.find('#node-reverification-interval-field');
const findErrorMessage = () => wrapper.find('.invalid-feedback');
const findFieldLabel = id => wrapper.vm.formGroups.find(el => el.id === id).label;
const findFieldLabel = (id) => wrapper.vm.formGroups.find((el) => el.id === id).label;
describe('template', () => {
describe.each`
......@@ -276,11 +276,15 @@ describe('GeoNodeFormCapacities', () => {
});
it('contains conditional form groups for primary', () => {
expect(wrapper.vm.visibleFormGroups.some(g => g.conditional === 'primary')).toBeTruthy();
expect(
wrapper.vm.visibleFormGroups.some((g) => g.conditional === 'primary'),
).toBeTruthy();
});
it('does not contain conditional form groups for secondary', () => {
expect(wrapper.vm.visibleFormGroups.some(g => g.conditional === 'secondary')).toBeFalsy();
expect(
wrapper.vm.visibleFormGroups.some((g) => g.conditional === 'secondary'),
).toBeFalsy();
});
});
......@@ -291,12 +295,12 @@ describe('GeoNodeFormCapacities', () => {
it('contains conditional form groups for secondary', () => {
expect(
wrapper.vm.visibleFormGroups.some(g => g.conditional === 'secondary'),
wrapper.vm.visibleFormGroups.some((g) => g.conditional === 'secondary'),
).toBeTruthy();
});
it('does not contain conditional form groups for primary', () => {
expect(wrapper.vm.visibleFormGroups.some(g => g.conditional === 'primary')).toBeFalsy();
expect(wrapper.vm.visibleFormGroups.some((g) => g.conditional === 'primary')).toBeFalsy();
});
});
});
......
......@@ -9,7 +9,9 @@ import { siteProfiles } from '../mocks/mock_data';
describe('EE - DastProfiles GraphQL CacheUtils', () => {
describe('appendToPreviousResult', () => {
it.each(['siteProfiles', 'scannerProfiles'])('appends new results to previous', profileType => {
it.each(['siteProfiles', 'scannerProfiles'])(
'appends new results to previous',
(profileType) => {
const previousResult = { project: { [profileType]: { edges: ['foo'] } } };
const fetchMoreResult = { project: { [profileType]: { edges: ['bar'] } } };
......@@ -17,11 +19,14 @@ describe('EE - DastProfiles GraphQL CacheUtils', () => {
const result = appendToPreviousResult(profileType)(previousResult, { fetchMoreResult });
expect(result).toEqual(expected);
});
},
);
});
describe('removeProfile', () => {
it.each(['foo', 'bar'])('removes the profile with the given id from the cache', profileType => {
it.each(['foo', 'bar'])(
'removes the profile with the given id from the cache',
(profileType) => {
const mockQueryBody = { query: 'foo', variables: { foo: 'bar' } };
const mockProfiles = [{ id: 0 }, { id: 1 }];
const mockData = {
......@@ -53,7 +58,8 @@ describe('EE - DastProfiles GraphQL CacheUtils', () => {
},
},
});
});
},
);
});
describe('dastProfilesDeleteResponse', () => {
......
......@@ -43,7 +43,7 @@ describe('DastSiteProfileForm', () => {
const withinComponent = () => within(wrapper.element);
const findForm = () => wrapper.find(GlForm);
const findByTestId = testId => wrapper.find(`[data-testid="${testId}"]`);
const findByTestId = (testId) => wrapper.find(`[data-testid="${testId}"]`);
const findProfileNameInput = () => findByTestId('profile-name-input');
const findTargetUrlInput = () => findByTestId('target-url-input');
const findAuthSection = () => wrapper.find(DastSiteAuthSection);
......@@ -60,7 +60,7 @@ describe('DastSiteProfileForm', () => {
field.trigger('blur');
};
const mockClientFactory = handlers => {
const mockClientFactory = (handlers) => {
const mockClient = createMockClient();
requestHandlers = {
......@@ -81,7 +81,7 @@ describe('DastSiteProfileForm', () => {
return mockClient;
};
const respondWith = handlers => {
const respondWith = (handlers) => {
apolloProvider.defaultClient = mockClientFactory(handlers);
};
......@@ -130,11 +130,14 @@ describe('DastSiteProfileForm', () => {
createFullComponent();
});
it.each(['asd', 'example.com'])('is marked as invalid provided an invalid URL', async value => {
it.each(['asd', 'example.com'])(
'is marked as invalid provided an invalid URL',
async (value) => {
await setFieldValue(findTargetUrlInput(), value);
expect(wrapper.text()).toContain(errorMessage);
});
},
);
it('is marked as valid provided a valid URL', async () => {
await setFieldValue(findTargetUrlInput(), targetUrl);
......@@ -259,7 +262,7 @@ describe('DastSiteProfileForm', () => {
const alert = findAlert();
expect(alert.exists()).toBe(true);
errors.forEach(error => {
errors.forEach((error) => {
expect(alert.text()).toContain(error);
});
});
......
......@@ -71,16 +71,16 @@ describe('DastSiteValidationModal', () => {
const createFullComponent = componentFactory(mount);
const withinComponent = () => within(wrapper.find(GlModal).element);
const findByTestId = id => wrapper.find(`[data-testid="${id}"`);
const findByTestId = (id) => wrapper.find(`[data-testid="${id}"`);
const findDownloadButton = () => findByTestId('download-dast-text-file-validation-button');
const findValidationPathPrefix = () => findByTestId('dast-site-validation-path-prefix');
const findValidationPathInput = () => findByTestId('dast-site-validation-path-input');
const findValidateButton = () => findByTestId('validate-dast-site-button');
const findRadioInputForValidationMethod = validationMethod =>
const findRadioInputForValidationMethod = (validationMethod) =>
withinComponent().queryByRole('radio', {
name: new RegExp(`${validationMethod} validation`, 'i'),
});
const enableValidationMethod = validationMethod =>
const enableValidationMethod = (validationMethod) =>
createWrapper(findRadioInputForValidationMethod(validationMethod)).trigger('click');
afterEach(() => {
......@@ -155,9 +155,12 @@ describe('DastSiteValidationModal', () => {
expect(downloadButton).not.toBeNull();
});
it.each(validationMethods)('renders a radio input for "%s" validation', validationMethod => {
it.each(validationMethods)(
'renders a radio input for "%s" validation',
(validationMethod) => {
expect(findRadioInputForValidationMethod(validationMethod)).not.toBe(null);
});
},
);
it('renders an input group with the target URL prepended', () => {
const inputGroup = withinComponent().getByRole('group', {
......@@ -179,7 +182,7 @@ describe('DastSiteValidationModal', () => {
});
describe('validation methods', () => {
describe.each(validationMethods)('common behaviour', validationMethod => {
describe.each(validationMethods)('common behaviour', (validationMethod) => {
const expectedFileName = `GitLab-DAST-Site-Validation-${token}.txt`;
describe.each`
......@@ -260,7 +263,7 @@ describe('DastSiteValidationModal', () => {
it.each([
/step 2 - add following http header to your site/i,
/step 3 - confirm header location and validate/i,
])('shows the correct descriptions', descriptionText => {
])('shows the correct descriptions', (descriptionText) => {
expect(withinComponent().getByText(descriptionText)).not.toBe(null);
});
......@@ -284,7 +287,7 @@ describe('DastSiteValidationModal', () => {
});
});
describe.each(validationMethods)('"%s" validation submission', validationMethod => {
describe.each(validationMethods)('"%s" validation submission', (validationMethod) => {
beforeEach(async () => {
createFullComponent();
await waitForPromises();
......
......@@ -43,20 +43,20 @@ describe('Vulnerability list component', () => {
const findTable = () => wrapper.find(GlTable);
const findSortableColumn = () => wrapper.find('[aria-sort="descending"]');
const findCell = label => wrapper.find(`.js-${label}`);
const findCell = (label) => wrapper.find(`.js-${label}`);
const findRows = () => wrapper.findAll('tbody tr');
const findRow = (index = 0) => findRows().at(index);
const findRowById = id => wrapper.find(`tbody tr[data-pk="${id}"`);
const findAutoFixBulbInRow = row => row.find('[data-testid="vulnerability-solutions-bulb"]');
const findRowById = (id) => wrapper.find(`tbody tr[data-pk="${id}"`);
const findAutoFixBulbInRow = (row) => row.find('[data-testid="vulnerability-solutions-bulb"]');
const findIssuesBadge = (index = 0) => wrapper.findAll(IssuesBadge).at(index);
const findRemediatedBadge = () => wrapper.find(RemediatedBadge);
const findSecurityScannerAlert = () => wrapper.find(SecurityScannerAlert);
const findDismissalButton = () => findSecurityScannerAlert().find('button[aria-label="Dismiss"]');
const findSelectionSummary = () => wrapper.find(SelectionSummary);
const findRowVulnerabilityCommentIcon = row => findRow(row).find(VulnerabilityCommentIcon);
const findDataCell = label => wrapper.find(`[data-testid="${label}"]`);
const findDataCells = label => wrapper.findAll(`[data-testid="${label}"]`);
const findLocationTextWrapper = cell => cell.find(GlTruncate);
const findRowVulnerabilityCommentIcon = (row) => findRow(row).find(VulnerabilityCommentIcon);
const findDataCell = (label) => wrapper.find(`[data-testid="${label}"]`);
const findDataCells = (label) => wrapper.findAll(`[data-testid="${label}"]`);
const findLocationTextWrapper = (cell) => cell.find(GlTruncate);
const findFiltersProducedNoResults = () => wrapper.find(FiltersProducedNoResults);
const findDashboardHasNoVulnerabilities = () => wrapper.find(DashboardHasNoVulnerabilities);
const findVendorNames = () => wrapper.find(`[data-testid="vulnerability-vendor"]`);
......@@ -350,7 +350,7 @@ describe('Vulnerability list component', () => {
beforeEach(() => {
newVulnerabilities = generateVulnerabilities();
newVulnerabilities = newVulnerabilities.map(v => ({
newVulnerabilities = newVulnerabilities.map((v) => ({
...v,
scanner: { vendor: 'GitLab' },
}));
......@@ -372,7 +372,7 @@ describe('Vulnerability list component', () => {
beforeEach(() => {
newVulnerabilities = generateVulnerabilities();
newVulnerabilities = newVulnerabilities.map(v => ({ ...v, scanner: { vendor: '' } }));
newVulnerabilities = newVulnerabilities.map((v) => ({ ...v, scanner: { vendor: '' } }));
wrapper = createWrapper({
props: {
vulnerabilities: newVulnerabilities,
......@@ -460,14 +460,14 @@ describe('Vulnerability list component', () => {
${['DISMISSED']}
${[]}
${['DETECTED', 'DISMISSED']}
`('should only show vulnerabilities that match filter $state', state => {
`('should only show vulnerabilities that match filter $state', (state) => {
wrapper = createWrapper({ props: { vulnerabilities, filters: { state } } });
const filteredVulnerabilities = vulnerabilities.filter(x =>
const filteredVulnerabilities = vulnerabilities.filter((x) =>
state.length ? state.includes(x.state) : true,
);
expect(findRows().length).toBe(filteredVulnerabilities.length);
filteredVulnerabilities.forEach(vulnerability => {
filteredVulnerabilities.forEach((vulnerability) => {
expect(findRowById(vulnerability.id).exists()).toBe(true);
});
});
......@@ -576,7 +576,8 @@ describe('Vulnerability list component', () => {
});
describe('row click', () => {
const findRowCheckbox = index => findRow(index).find('[data-testid="vulnerability-checkbox"]');
const findRowCheckbox = (index) =>
findRow(index).find('[data-testid="vulnerability-checkbox"]');
beforeEach(() => {
wrapper = createWrapper({ props: { vulnerabilities } });
......@@ -585,15 +586,15 @@ describe('Vulnerability list component', () => {
it('will select and deselect vulnerabilities', async () => {
const rowCount = vulnerabilities.length;
const rowsToClick = [0, 1, 2];
const clickRows = () => rowsToClick.forEach(row => findRow(row).trigger('click'));
const expectRowCheckboxesToBe = condition => {
const clickRows = () => rowsToClick.forEach((row) => findRow(row).trigger('click'));
const expectRowCheckboxesToBe = (condition) => {
for (let i = 0; i < rowCount; i += 1)
expect(findRowCheckbox(i).element.checked).toBe(condition(i));
};
clickRows();
await wrapper.vm.$nextTick();
expectRowCheckboxesToBe(i => rowsToClick.includes(i));
expectRowCheckboxesToBe((i) => rowsToClick.includes(i));
clickRows();
await wrapper.vm.$nextTick();
......
......@@ -4,23 +4,23 @@ import Status from 'ee/sidebar/components/status/status.vue';
import { healthStatus, healthStatusTextMap } from 'ee/sidebar/constants';
import { createMockDirective, getBinding } from 'helpers/vue_mock_directive';
const getStatusText = wrapper => wrapper.find('.value .text-plain').text();
const getStatusText = (wrapper) => wrapper.find('.value .text-plain').text();
const getStatusTitleText = wrapper => wrapper.find('[data-testid="statusTitle"]').text();
const getStatusTitleText = (wrapper) => wrapper.find('[data-testid="statusTitle"]').text();
const getStatusTooltipValue = wrapper =>
const getStatusTooltipValue = (wrapper) =>
getBinding(wrapper.find({ ref: 'status' }).element, 'gl-tooltip').value;
const getEditButtonTooltipValue = wrapper =>
const getEditButtonTooltipValue = (wrapper) =>
getBinding(wrapper.find('[data-testid="editButtonTooltip"]').element, 'gl-tooltip').value;
const getEditButton = wrapper => wrapper.find({ ref: 'editButton' });
const getEditButton = (wrapper) => wrapper.find({ ref: 'editButton' });
const getDropdownClasses = wrapper => wrapper.find('[data-testid="dropdownWrapper"]').classes();
const getDropdownClasses = (wrapper) => wrapper.find('[data-testid="dropdownWrapper"]').classes();
const getDropdownElement = wrapper => wrapper.find(GlDropdown);
const getDropdownElement = (wrapper) => wrapper.find(GlDropdown);
const getRemoveStatusItem = wrapper => wrapper.find(GlDropdownItem);
const getRemoveStatusItem = (wrapper) => wrapper.find(GlDropdownItem);
describe('Status', () => {
let wrapper;
......@@ -157,7 +157,9 @@ describe('Status', () => {
});
});
describe.each(Object.values(healthStatus))(`when "%s" is provided for status`, statusValue => {
describe.each(Object.values(healthStatus))(
`when "%s" is provided for status`,
(statusValue) => {
beforeEach(() => {
const props = {
status: statusValue,
......@@ -175,7 +177,8 @@ describe('Status', () => {
`Health status: ${healthStatusTextMap[statusValue]}`,
);
});
});
},
);
});
describe('status dropdown', () => {
......@@ -243,7 +246,7 @@ describe('Status', () => {
});
describe('dropdown', () => {
const getIterableArray = arr => {
const getIterableArray = (arr) => {
return arr.map((value, index) => [value, index]);
};
......
......@@ -52,7 +52,9 @@ describe('Usage Quotas project table component', () => {
});
it('renders excess storage rows with error state', () => {
const rowsWithError = findTableRowsWithExcessStorage().filter(r => r.classes('gl-bg-red-50'));
const rowsWithError = findTableRowsWithExcessStorage().filter((r) =>
r.classes('gl-bg-red-50'),
);
expect(rowsWithError).toHaveLength(1);
});
});
......
......@@ -283,7 +283,9 @@ describe('Vulnerability Footer', () => {
const statusDescription = () => wrapper.find(StatusDescription);
const vulnerabilityStates = Object.keys(VULNERABILITY_STATES);
it.each(vulnerabilityStates)(`shows detection note when vulnerability state is '%s'`, state => {
it.each(vulnerabilityStates)(
`shows detection note when vulnerability state is '%s'`,
(state) => {
createWrapper({ state });
expect(detectionNote().exists()).toBe(true);
......@@ -291,6 +293,7 @@ describe('Vulnerability Footer', () => {
state: 'detected',
pipeline: vulnerability.pipeline,
});
});
},
);
});
});
......@@ -49,7 +49,7 @@ describe('BalsamiqViewer', () => {
);
});
it('should call `renderFile` on request success', done => {
it('should call `renderFile` on request success', (done) => {
jest.spyOn(axios, 'get').mockReturnValue(requestSuccess);
jest.spyOn(bv, 'renderFile').mockImplementation(() => {});
......@@ -61,7 +61,7 @@ describe('BalsamiqViewer', () => {
.catch(done.fail);
});
it('should not call `renderFile` on request failure', done => {
it('should not call `renderFile` on request failure', (done) => {
jest.spyOn(axios, 'get').mockReturnValue(Promise.reject());
jest.spyOn(bv, 'renderFile').mockImplementation(() => {});
......@@ -95,8 +95,8 @@ describe('BalsamiqViewer', () => {
balsamiqViewer.viewer = viewer;
balsamiqViewer.getPreviews.mockReturnValue(previews);
balsamiqViewer.renderPreview.mockImplementation(preview => preview);
viewer.appendChild.mockImplementation(containerElement => {
balsamiqViewer.renderPreview.mockImplementation((preview) => preview);
viewer.appendChild.mockImplementation((containerElement) => {
container = containerElement;
});
......@@ -177,7 +177,9 @@ describe('BalsamiqViewer', () => {
database,
};
jest.spyOn(BalsamiqViewer, 'parsePreview').mockImplementation(preview => preview.toString());
jest
.spyOn(BalsamiqViewer, 'parsePreview')
.mockImplementation((preview) => preview.toString());
database.exec.mockReturnValue(thumbnails);
getPreviews = BalsamiqViewer.prototype.getPreviews.call(balsamiqViewer);
......
......@@ -10,8 +10,8 @@ import createFlash from '~/flash';
jest.mock('~/flash');
const TEST_LABELS_PAYLOAD = TEST_LABELS.map(label => ({ ...label, set: true }));
const TEST_LABELS_TITLES = TEST_LABELS.map(label => label.title);
const TEST_LABELS_PAYLOAD = TEST_LABELS.map((label) => ({ ...label, set: true }));
const TEST_LABELS_TITLES = TEST_LABELS.map((label) => label.title);
describe('~/boards/components/sidebar/board_sidebar_labels_select.vue', () => {
let wrapper;
......@@ -44,7 +44,8 @@ describe('~/boards/components/sidebar/board_sidebar_labels_select.vue', () => {
};
const findLabelsSelect = () => wrapper.find({ ref: 'labelsSelect' });
const findLabelsTitles = () => wrapper.findAll(GlLabel).wrappers.map(item => item.props('title'));
const findLabelsTitles = () =>
wrapper.findAll(GlLabel).wrappers.map((item) => item.props('title'));
const findCollapsed = () => wrapper.find('[data-testid="collapsed-content"]');
it('renders "None" when no labels are selected', () => {
......@@ -76,7 +77,7 @@ describe('~/boards/components/sidebar/board_sidebar_labels_select.vue', () => {
it('commits change to the server', () => {
expect(wrapper.vm.setActiveIssueLabels).toHaveBeenCalledWith({
addLabelIds: TEST_LABELS.map(label => label.id),
addLabelIds: TEST_LABELS.map((label) => label.id),
projectPath: 'gitlab-org/test-subgroup/gitlab-test',
removeLabelIds: [],
});
......
......@@ -237,7 +237,9 @@ describe('Clusters Store', () => {
});
});
describe.each(APPLICATION_INSTALLED_STATUSES)('given the current app status is %s', status => {
describe.each(APPLICATION_INSTALLED_STATUSES)(
'given the current app status is %s',
(status) => {
it('marks application as installed', () => {
const mockResponseData =
CLUSTERS_MOCK_DATA.GET['/gitlab-org/gitlab-shell/clusters/2/status.json'].data;
......@@ -249,7 +251,8 @@ describe('Clusters Store', () => {
expect(store.state.applications[RUNNER].installed).toBe(true);
});
});
},
);
it('sets default hostname for jupyter when ingress has a ip address', () => {
const mockResponseData =
......
......@@ -62,7 +62,7 @@ describe('DiffFileHeader component', () => {
diffHasDiscussionsResultMock,
diffHasExpandedDiscussionsResultMock,
...Object.values(mockStoreConfig.modules.diffs.actions),
].forEach(mock => mock.mockReset());
].forEach((mock) => mock.mockReset());
wrapper.destroy();
});
......@@ -80,7 +80,7 @@ describe('DiffFileHeader component', () => {
const findCollapseIcon = () => wrapper.find({ ref: 'collapseIcon' });
const findEditButton = () => wrapper.find({ ref: 'editButton' });
const createComponent = props => {
const createComponent = (props) => {
mockStoreConfig = cloneDeep(defaultMockStoreConfig);
const store = new Vuex.Store(mockStoreConfig);
......@@ -219,7 +219,7 @@ describe('DiffFileHeader component', () => {
});
describe('for any file', () => {
const otherModes = Object.keys(diffViewerModes).filter(m => m !== 'mode_changed');
const otherModes = Object.keys(diffViewerModes).filter((m) => m !== 'mode_changed');
it('for mode_changed file mode displays mode changes', () => {
createComponent({
......@@ -236,7 +236,9 @@ describe('DiffFileHeader component', () => {
expect(findModeChangedLine().text()).toMatch(/old-mode.+new-mode/);
});
it.each(otherModes.map(m => [m]))('for %s file mode does not display mode changes', mode => {
it.each(otherModes.map((m) => [m]))(
'for %s file mode does not display mode changes',
(mode) => {
createComponent({
diffFile: {
...diffFile,
......@@ -249,7 +251,8 @@ describe('DiffFileHeader component', () => {
},
});
expect(findModeChangedLine().exists()).toBeFalsy();
});
},
);
it('displays the LFS label for files stored in LFS', () => {
createComponent({
......
......@@ -26,13 +26,15 @@ describe('HiddenFilesWarning', () => {
});
it('has a correct plain diff URL', () => {
const plainDiffLink = wrapper.findAll('a').wrappers.filter(x => x.text() === 'Plain diff')[0];
const plainDiffLink = wrapper.findAll('a').wrappers.filter((x) => x.text() === 'Plain diff')[0];
expect(plainDiffLink.attributes('href')).toBe(propsData.plainDiffPath);
});
it('has a correct email patch URL', () => {
const emailPatchLink = wrapper.findAll('a').wrappers.filter(x => x.text() === 'Email patch')[0];
const emailPatchLink = wrapper
.findAll('a')
.wrappers.filter((x) => x.text() === 'Email patch')[0];
expect(emailPatchLink.attributes('href')).toBe(propsData.emailPatchPath);
});
......
......@@ -16,7 +16,8 @@ describe('Monitoring Component', () => {
};
const findButtons = () => wrapper.findAll(GlButton);
const findButtonsByIcon = icon => findButtons().filter(button => button.props('icon') === icon);
const findButtonsByIcon = (icon) =>
findButtons().filter((button) => button.props('icon') === icon);
beforeEach(() => {
createWrapper();
......
......@@ -23,7 +23,7 @@ describe('Bulk import status poller', () => {
let clientMock;
const listQueryCacheCalls = () =>
clientMock.readQuery.mock.calls.filter(call => call[0].query === bulkImportSourceGroupsQuery);
clientMock.readQuery.mock.calls.filter((call) => call[0].query === bulkImportSourceGroupsQuery);
beforeEach(() => {
clientMock = createMockClient({
......@@ -142,9 +142,11 @@ describe('Bulk import status poller', () => {
clientMock.cache.writeQuery({
query: bulkImportSourceGroupsQuery,
data: {
bulkImportSourceGroups: [STARTED_GROUP_1, NOT_STARTED_GROUP, STARTED_GROUP_2].map(group =>
generateFakeEntry(group),
),
bulkImportSourceGroups: [
STARTED_GROUP_1,
NOT_STARTED_GROUP,
STARTED_GROUP_2,
].map((group) => generateFakeEntry(group)),
},
});
......@@ -155,9 +157,9 @@ describe('Bulk import status poller', () => {
await waitForPromises();
const [[doc]] = clientMock.query.mock.calls;
const { selections } = doc.query.definitions[0].selectionSet;
expect(selections.every(field => field.name.value === 'group')).toBeTruthy();
expect(selections.every((field) => field.name.value === 'group')).toBeTruthy();
expect(selections).toHaveLength(2);
expect(selections.map(sel => sel.arguments[0].value.value)).toStrictEqual([
expect(selections.map((sel) => sel.arguments[0].value.value)).toStrictEqual([
`${TARGET_NAMESPACE}/${STARTED_GROUP_1.import_target.new_name}`,
`${TARGET_NAMESPACE}/${STARTED_GROUP_2.import_target.new_name}`,
]);
......@@ -167,7 +169,7 @@ describe('Bulk import status poller', () => {
clientMock.cache.writeQuery({
query: bulkImportSourceGroupsQuery,
data: {
bulkImportSourceGroups: [STARTED_GROUP_1, STARTED_GROUP_2].map(group =>
bulkImportSourceGroups: [STARTED_GROUP_1, STARTED_GROUP_2].map((group) =>
generateFakeEntry(group),
),
},
......@@ -189,7 +191,7 @@ describe('Bulk import status poller', () => {
clientMock.cache.writeQuery({
query: bulkImportSourceGroupsQuery,
data: {
bulkImportSourceGroups: [STARTED_GROUP_1, STARTED_GROUP_2].map(group =>
bulkImportSourceGroups: [STARTED_GROUP_1, STARTED_GROUP_2].map((group) =>
generateFakeEntry(group),
),
},
......
......@@ -22,13 +22,14 @@ const issuable2 = {
const pathIdSeparator = PathIdSeparator.Issue;
const findFormInput = wrapper => wrapper.find('.js-add-issuable-form-input').element;
const findFormInput = (wrapper) => wrapper.find('.js-add-issuable-form-input').element;
const findRadioInput = (inputs, value) => inputs.filter(input => input.element.value === value)[0];
const findRadioInput = (inputs, value) =>
inputs.filter((input) => input.element.value === value)[0];
const findRadioInputs = wrapper => wrapper.findAll('[name="linked-issue-type-radio"]');
const findRadioInputs = (wrapper) => wrapper.findAll('[name="linked-issue-type-radio"]');
const constructWrapper = props => {
const constructWrapper = (props) => {
return shallowMount(AddIssuableForm, {
propsData: {
inputValue: '',
......@@ -192,7 +193,7 @@ describe('AddIssuableForm', () => {
});
describe('when the form is submitted', () => {
it('emits an event with a "relates_to" link type when the "relates to" radio input selected', done => {
it('emits an event with a "relates_to" link type when the "relates to" radio input selected', (done) => {
jest.spyOn(wrapper.vm, '$emit').mockImplementation(() => {});
wrapper.vm.linkedIssueType = linkedIssueTypesMap.RELATES_TO;
......@@ -207,7 +208,7 @@ describe('AddIssuableForm', () => {
});
});
it('emits an event with a "blocks" link type when the "blocks" radio input selected', done => {
it('emits an event with a "blocks" link type when the "blocks" radio input selected', (done) => {
jest.spyOn(wrapper.vm, '$emit').mockImplementation(() => {});
wrapper.vm.linkedIssueType = linkedIssueTypesMap.BLOCKS;
......@@ -222,7 +223,7 @@ describe('AddIssuableForm', () => {
});
});
it('emits an event with a "is_blocked_by" link type when the "is blocked by" radio input selected', done => {
it('emits an event with a "is_blocked_by" link type when the "is blocked by" radio input selected', (done) => {
jest.spyOn(wrapper.vm, '$emit').mockImplementation(() => {});
wrapper.vm.linkedIssueType = linkedIssueTypesMap.IS_BLOCKED_BY;
......@@ -237,7 +238,7 @@ describe('AddIssuableForm', () => {
});
});
it('shows error message when error is present', done => {
it('shows error message when error is present', (done) => {
const itemAddFailureMessage = 'Something went wrong while submitting.';
wrapper.setProps({
hasError: true,
......
......@@ -25,7 +25,8 @@ describe('DiscussionFilter component', () => {
const filterDiscussion = jest.fn();
const findFilter = filterType => wrapper.find(`.dropdown-item[data-filter-type="${filterType}"]`);
const findFilter = (filterType) =>
wrapper.find(`.dropdown-item[data-filter-type="${filterType}"]`);
const mountComponent = () => {
const discussions = [
......@@ -145,7 +146,7 @@ describe('DiscussionFilter component', () => {
window.mrTabs = undefined;
});
it('only renders when discussion tab is active', done => {
it('only renders when discussion tab is active', (done) => {
eventHub.$emit('MergeRequestTabChange', 'commit');
wrapper.vm.$nextTick(() => {
......@@ -160,7 +161,7 @@ describe('DiscussionFilter component', () => {
window.location.hash = '';
});
it('updates the filter when the URL links to a note', done => {
it('updates the filter when the URL links to a note', (done) => {
window.location.hash = `note_${discussionMock.notes[0].id}`;
wrapper.vm.currentValue = discussionFiltersMock[2].value;
wrapper.vm.handleLocationHash();
......@@ -171,7 +172,7 @@ describe('DiscussionFilter component', () => {
});
});
it('does not update the filter when the current filter is "Show all activity"', done => {
it('does not update the filter when the current filter is "Show all activity"', (done) => {
window.location.hash = `note_${discussionMock.notes[0].id}`;
wrapper.vm.handleLocationHash();
......@@ -181,7 +182,7 @@ describe('DiscussionFilter component', () => {
});
});
it('only updates filter when the URL links to a note', done => {
it('only updates filter when the URL links to a note', (done) => {
window.location.hash = `testing123`;
wrapper.vm.handleLocationHash();
......@@ -191,7 +192,7 @@ describe('DiscussionFilter component', () => {
});
});
it('fetches discussions when there is a hash', done => {
it('fetches discussions when there is a hash', (done) => {
window.location.hash = `note_${discussionMock.notes[0].id}`;
wrapper.vm.currentValue = discussionFiltersMock[2].value;
jest.spyOn(wrapper.vm, 'selectFilter').mockImplementation(() => {});
......@@ -203,7 +204,7 @@ describe('DiscussionFilter component', () => {
});
});
it('does not fetch discussions when there is no hash', done => {
it('does not fetch discussions when there is no hash', (done) => {
window.location.hash = '';
jest.spyOn(wrapper.vm, 'selectFilter').mockImplementation(() => {});
wrapper.vm.handleLocationHash();
......
......@@ -25,8 +25,9 @@ describe('CI Lint Results', () => {
};
const findTable = () => wrapper.find(GlTable);
const findByTestId = selector => () => wrapper.find(`[data-testid="ci-lint-${selector}"]`);
const findAllByTestId = selector => () => wrapper.findAll(`[data-testid="ci-lint-${selector}"]`);
const findByTestId = (selector) => () => wrapper.find(`[data-testid="ci-lint-${selector}"]`);
const findAllByTestId = (selector) => () =>
wrapper.findAll(`[data-testid="ci-lint-${selector}"]`);
const findLinkToDoc = () => wrapper.find(GlLink);
const findErrors = findByTestId('errors');
const findWarnings = findByTestId('warnings');
......@@ -37,7 +38,7 @@ describe('CI Lint Results', () => {
const findBeforeScripts = findAllByTestId('before-script');
const findScripts = findAllByTestId('script');
const findAfterScripts = findAllByTestId('after-script');
const filterEmptyScripts = property => mockJobs.filter(job => job[property].length !== 0);
const filterEmptyScripts = (property) => mockJobs.filter((job) => job[property].length !== 0);
afterEach(() => {
wrapper.destroy();
......
......@@ -185,7 +185,9 @@ describe('ServiceDeskSetting', () => {
const expectedTemplates = [''].concat(templates);
const dropdown = findTemplateDropdown();
const dropdownList = Array.from(dropdown.element.children).map(option => option.innerText);
const dropdownList = Array.from(dropdown.element.children).map(
(option) => option.innerText,
);
expect(dropdown.element.children).toHaveLength(expectedTemplates.length);
expect(dropdownList.includes('Bug')).toEqual(true);
......
......@@ -149,9 +149,11 @@ describe('Snippet Edit app', () => {
const hasDisabledSubmit = () => Boolean(findSubmitButton().attributes('disabled'));
const clickSubmitBtn = () => wrapper.find('[data-testid="snippet-edit-form"]').trigger('submit');
const triggerBlobActions = actions => findBlobActions().vm.$emit('actions', actions);
const setUploadFilesHtml = paths => {
wrapper.vm.$el.innerHTML = paths.map(path => `<input name="files[]" value="${path}">`).join('');
const triggerBlobActions = (actions) => findBlobActions().vm.$emit('actions', actions);
const setUploadFilesHtml = (paths) => {
wrapper.vm.$el.innerHTML = paths
.map((path) => `<input name="files[]" value="${path}">`)
.join('');
};
const getApiData = ({
id,
......@@ -189,7 +191,7 @@ describe('Snippet Edit app', () => {
it.each([[{}], [{ snippetGid: '' }]])(
'should render all required components with %s',
props => {
(props) => {
createComponent(props);
expect(wrapper.find(TitleField).exists()).toBe(true);
......@@ -257,7 +259,7 @@ describe('Snippet Edit app', () => {
describe('default visibility', () => {
it.each([SNIPPET_VISIBILITY_PRIVATE, SNIPPET_VISIBILITY_INTERNAL, SNIPPET_VISIBILITY_PUBLIC])(
'marks %s visibility by default',
async visibility => {
async (visibility) => {
createComponent({
props: { snippetGid: '' },
selectedLevel: visibility,
......
......@@ -57,7 +57,7 @@ describe('User Lists Show Mutations', () => {
});
it('adds the new IDs to the state unless empty', () => {
newIds.filter(id => id).forEach(id => expect(mockState.userIds).toContain(id));
newIds.filter((id) => id).forEach((id) => expect(mockState.userIds).toContain(id));
});
it('does not add duplicate IDs to the state', () => {
......@@ -80,7 +80,9 @@ describe('User Lists Show Mutations', () => {
});
it('should leave the rest of the IDs alone', () => {
userIds.filter(id => id !== removedId).forEach(id => expect(mockState.userIds).toContain(id));
userIds
.filter((id) => id !== removedId)
.forEach((id) => expect(mockState.userIds).toContain(id));
});
});
});
......@@ -3,7 +3,7 @@ import Vue from 'vue';
import mountComponent from 'helpers/vue_mount_component_helper';
import stackedProgressBarComponent from '~/vue_shared/components/stacked_progress_bar.vue';
const createComponent = config => {
const createComponent = (config) => {
const Component = Vue.extend(stackedProgressBarComponent);
const defaultConfig = {
successLabel: 'Synced',
......@@ -29,11 +29,12 @@ describe('StackedProgressBarComponent', () => {
vm.$destroy();
});
const findSuccessBarText = wrapper => wrapper.$el.querySelector('.status-green').innerText.trim();
const findNeutralBarText = wrapper =>
const findSuccessBarText = (wrapper) =>
wrapper.$el.querySelector('.status-green').innerText.trim();
const findNeutralBarText = (wrapper) =>
wrapper.$el.querySelector('.status-neutral').innerText.trim();
const findFailureBarText = wrapper => wrapper.$el.querySelector('.status-red').innerText.trim();
const findUnavailableBarText = wrapper =>
const findFailureBarText = (wrapper) => wrapper.$el.querySelector('.status-red').innerText.trim();
const findUnavailableBarText = (wrapper) =>
wrapper.$el.querySelector('.status-unavailable').innerText.trim();
describe('computed', () => {
......
......@@ -8,11 +8,11 @@ import {
findByText,
} from '@testing-library/dom';
const isFolderRowOpen = row => row.matches('.folder.is-open');
const isFolderRowOpen = (row) => row.matches('.folder.is-open');
const getLeftSidebar = () => screen.getByTestId('left-sidebar');
export const switchLeftSidebarTab = name => {
export const switchLeftSidebarTab = (name) => {
const sidebar = getLeftSidebar();
const button = getByLabelText(sidebar, name);
......@@ -23,7 +23,7 @@ export const switchLeftSidebarTab = name => {
export const getStatusBar = () => document.querySelector('.ide-status-bar');
export const waitForMonacoEditor = () =>
new Promise(resolve => window.monaco.editor.onDidCreateEditor(resolve));
new Promise((resolve) => window.monaco.editor.onDidCreateEditor(resolve));
export const findMonacoEditor = () =>
screen.findAllByLabelText(/Editor content;/).then(([x]) => x.closest('.monaco-editor'));
......@@ -31,7 +31,7 @@ export const findMonacoEditor = () =>
export const findMonacoDiffEditor = () =>
screen.findAllByLabelText(/Editor content;/).then(([x]) => x.closest('.monaco-diff-editor'));
export const findAndSetEditorValue = async value => {
export const findAndSetEditorValue = async (value) => {
const editor = await findMonacoEditor();
const uri = editor.getAttribute('data-uri');
......@@ -56,10 +56,12 @@ const findFileChild = async (row, name, index = 0) => {
const container = await findFileRowContainer(row);
const children = await findAllByText(container, name, { selector: '.file-row-name' });
return children.map(x => x.closest('.file-row')).find(x => x.dataset.level === index.toString());
return children
.map((x) => x.closest('.file-row'))
.find((x) => x.dataset.level === index.toString());
};
const openFileRow = row => {
const openFileRow = (row) => {
if (!row || isFolderRowOpen(row)) {
return;
}
......@@ -101,7 +103,7 @@ const fillFileNameModal = async (value, submitText = 'Create file') => {
createButton.click();
};
const findAndClickRootAction = async name => {
const findAndClickRootAction = async (name) => {
const container = await findRootActions();
const button = getByLabelText(container, name);
......@@ -112,13 +114,13 @@ export const clickPreviewMarkdown = () => {
screen.getByText('Preview Markdown').click();
};
export const openFile = async path => {
export const openFile = async (path) => {
const row = await findAndTraverseToPath(path);
openFileRow(row);
};
export const waitForTabToOpen = fileName =>
export const waitForTabToOpen = (fileName) =>
findByText(document.querySelector('.multi-file-edit-pane'), fileName);
export const createFile = async (path, content) => {
......@@ -137,10 +139,10 @@ export const createFile = async (path, content) => {
};
export const getFilesList = () => {
return screen.getAllByTestId('file-row-name-container').map(e => e.textContent.trim());
return screen.getAllByTestId('file-row-name-container').map((e) => e.textContent.trim());
};
export const deleteFile = async path => {
export const deleteFile = async (path) => {
const row = await findAndTraverseToPath(path);
clickFileRowAction(row, 'Delete');
};
......@@ -152,7 +154,7 @@ export const renameFile = async (path, newPath) => {
await fillFileNameModal(newPath, 'Rename file');
};
export const closeFile = async path => {
export const closeFile = async (path) => {
const button = await screen.getByLabelText(`Close ${path}`, {
selector: '.multi-file-tabs button',
});
......@@ -164,7 +166,7 @@ export const commit = async () => {
switchLeftSidebarTab('Commit');
screen.getByTestId('begin-commit-button').click();
await screen.findByLabelText(/Commit to .+ branch/).then(x => x.click());
await screen.findByLabelText(/Commit to .+ branch/).then((x) => x.click());
screen.getByText('Commit').click();
};
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