Commit 792e3493 authored by Lukas Eipert's avatar Lukas Eipert

Run prettier on 31 files - 2 of 73

Part of our prettier migration; changing the arrow-parens style.
parent 8869ce08
...@@ -10,39 +10,6 @@ doc/api/graphql/reference/gitlab_schema.graphql ...@@ -10,39 +10,6 @@ doc/api/graphql/reference/gitlab_schema.graphql
*.scss *.scss
*.md *.md
## 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 ## objective-swirles
spec/frontend/boards/components/sidebar/board_sidebar_labels_select_spec.js spec/frontend/boards/components/sidebar/board_sidebar_labels_select_spec.js
spec/frontend/clusters/stores/clusters_store_spec.js spec/frontend/clusters/stores/clusters_store_spec.js
......
...@@ -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);
......
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