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