Commit 0daff5ee authored by Simon Knox's avatar Simon Knox

Merge branch 'feature/prevent-boards-store-create-graphql-boards' into 'master'

Boards - Prevent boardsStore creation on graphQL boards

See merge request gitlab-org/gitlab!51424
parents 1622ac99 6ae76691
<script> <script>
// This component is being replaced in favor of './board_column_new.vue' for GraphQL boards import { mapGetters, mapActions, mapState } from 'vuex';
import Sortable from 'sortablejs';
import BoardListHeader from 'ee_else_ce/boards/components/board_list_header.vue'; import BoardListHeader from 'ee_else_ce/boards/components/board_list_header.vue';
import BoardList from './board_list.vue'; import BoardList from './board_list.vue';
import boardsStore from '../stores/boards_store'; import { isListDraggable } from '../boards_util';
import { getBoardSortableDefaultOptions, sortableEnd } from '../mixins/sortable_default_options';
export default { export default {
components: { components: {
...@@ -32,53 +30,27 @@ export default { ...@@ -32,53 +30,27 @@ export default {
default: false, default: false,
}, },
}, },
data() {
return {
detailIssue: boardsStore.detail,
filter: boardsStore.filter,
};
},
computed: { computed: {
...mapState(['filterParams']),
...mapGetters(['getIssuesByList']),
listIssues() { listIssues() {
return this.list.issues; return this.getIssuesByList(this.list.id);
},
isListDraggable() {
return isListDraggable(this.list);
}, },
}, },
watch: { watch: {
filter: { filterParams: {
handler() { handler() {
this.list.page = 1; this.fetchIssuesForList({ listId: this.list.id });
this.list.getIssues(true).catch(() => {
// TODO: handle request error
});
}, },
deep: true, deep: true,
immediate: true,
}, },
}, },
mounted() { methods: {
const instance = this; ...mapActions(['fetchIssuesForList']),
const sortableOptions = getBoardSortableDefaultOptions({
disabled: this.disabled,
group: 'boards',
draggable: '.is-draggable',
handle: '.js-board-handle',
onEnd(e) {
sortableEnd();
const sortable = this;
if (e.newIndex !== undefined && e.oldIndex !== e.newIndex) {
const order = sortable.toArray();
const list = boardsStore.findList('id', parseInt(e.item.dataset.id, 10));
instance.$nextTick(() => {
boardsStore.moveList(list, order);
});
}
},
});
Sortable.create(this.$el.parentNode, sortableOptions);
}, },
}; };
</script> </script>
...@@ -86,20 +58,25 @@ export default { ...@@ -86,20 +58,25 @@ export default {
<template> <template>
<div <div
:class="{ :class="{
'is-draggable': !list.preset, 'is-draggable': isListDraggable,
'is-expandable': list.isExpandable, 'is-collapsed': list.collapsed,
'is-collapsed': !list.isExpanded, 'board-type-assignee': list.listType === 'assignee',
'board-type-assignee': list.type === 'assignee',
}" }"
:data-id="list.id" :data-id="list.id"
class="board gl-display-inline-block gl-h-full gl-px-3 gl-vertical-align-top gl-white-space-normal" class="board gl-display-inline-block gl-h-full gl-px-3 gl-vertical-align-top gl-white-space-normal is-expandable"
data-qa-selector="board_list" data-qa-selector="board_list"
> >
<div <div
class="board-inner gl-display-flex gl-flex-direction-column gl-relative gl-h-full gl-rounded-base" class="board-inner gl-display-flex gl-flex-direction-column gl-relative gl-h-full gl-rounded-base"
> >
<board-list-header :can-admin-list="canAdminList" :list="list" :disabled="disabled" /> <board-list-header :can-admin-list="canAdminList" :list="list" :disabled="disabled" />
<board-list ref="board-list" :disabled="disabled" :issues="listIssues" :list="list" /> <board-list
ref="board-list"
:disabled="disabled"
:issues="listIssues"
:list="list"
:can-admin-list="canAdminList"
/>
</div> </div>
</div> </div>
</template> </template>
<script> <script>
import { mapGetters, mapActions, mapState } from 'vuex'; // This component is being replaced in favor of './board_column.vue' for GraphQL boards
import BoardListHeader from 'ee_else_ce/boards/components/board_list_header_new.vue'; import Sortable from 'sortablejs';
import BoardList from './board_list_new.vue'; import BoardListHeader from 'ee_else_ce/boards/components/board_list_header_deprecated.vue';
import { isListDraggable } from '../boards_util'; import BoardList from './board_list_deprecated.vue';
import boardsStore from '../stores/boards_store';
import { getBoardSortableDefaultOptions, sortableEnd } from '../mixins/sortable_default_options';
export default { export default {
components: { components: {
...@@ -30,27 +32,53 @@ export default { ...@@ -30,27 +32,53 @@ export default {
default: false, default: false,
}, },
}, },
data() {
return {
detailIssue: boardsStore.detail,
filter: boardsStore.filter,
};
},
computed: { computed: {
...mapState(['filterParams']),
...mapGetters(['getIssuesByList']),
listIssues() { listIssues() {
return this.getIssuesByList(this.list.id); return this.list.issues;
},
isListDraggable() {
return isListDraggable(this.list);
}, },
}, },
watch: { watch: {
filterParams: { filter: {
handler() { handler() {
this.fetchIssuesForList({ listId: this.list.id }); this.list.page = 1;
this.list.getIssues(true).catch(() => {
// TODO: handle request error
});
}, },
deep: true, deep: true,
immediate: true,
}, },
}, },
methods: { mounted() {
...mapActions(['fetchIssuesForList']), const instance = this;
const sortableOptions = getBoardSortableDefaultOptions({
disabled: this.disabled,
group: 'boards',
draggable: '.is-draggable',
handle: '.js-board-handle',
onEnd(e) {
sortableEnd();
const sortable = this;
if (e.newIndex !== undefined && e.oldIndex !== e.newIndex) {
const order = sortable.toArray();
const list = boardsStore.findList('id', parseInt(e.item.dataset.id, 10));
instance.$nextTick(() => {
boardsStore.moveList(list, order);
});
}
},
});
Sortable.create(this.$el.parentNode, sortableOptions);
}, },
}; };
</script> </script>
...@@ -58,25 +86,20 @@ export default { ...@@ -58,25 +86,20 @@ export default {
<template> <template>
<div <div
:class="{ :class="{
'is-draggable': isListDraggable, 'is-draggable': !list.preset,
'is-collapsed': list.collapsed, 'is-expandable': list.isExpandable,
'board-type-assignee': list.listType === 'assignee', 'is-collapsed': !list.isExpanded,
'board-type-assignee': list.type === 'assignee',
}" }"
:data-id="list.id" :data-id="list.id"
class="board gl-display-inline-block gl-h-full gl-px-3 gl-vertical-align-top gl-white-space-normal is-expandable" class="board gl-display-inline-block gl-h-full gl-px-3 gl-vertical-align-top gl-white-space-normal"
data-qa-selector="board_list" data-qa-selector="board_list"
> >
<div <div
class="board-inner gl-display-flex gl-flex-direction-column gl-relative gl-h-full gl-rounded-base" class="board-inner gl-display-flex gl-flex-direction-column gl-relative gl-h-full gl-rounded-base"
> >
<board-list-header :can-admin-list="canAdminList" :list="list" :disabled="disabled" /> <board-list-header :can-admin-list="canAdminList" :list="list" :disabled="disabled" />
<board-list <board-list ref="board-list" :disabled="disabled" :issues="listIssues" :list="list" />
ref="board-list"
:disabled="disabled"
:issues="listIssues"
:list="list"
:can-admin-list="canAdminList"
/>
</div> </div>
</div> </div>
</template> </template>
...@@ -3,15 +3,15 @@ import Draggable from 'vuedraggable'; ...@@ -3,15 +3,15 @@ import Draggable from 'vuedraggable';
import { mapState, mapGetters, mapActions } from 'vuex'; import { mapState, mapGetters, mapActions } from 'vuex';
import { sortBy } from 'lodash'; import { sortBy } from 'lodash';
import { GlAlert } from '@gitlab/ui'; import { GlAlert } from '@gitlab/ui';
import BoardColumnDeprecated from './board_column_deprecated.vue';
import BoardColumn from './board_column.vue'; import BoardColumn from './board_column.vue';
import BoardColumnNew from './board_column_new.vue';
import glFeatureFlagMixin from '~/vue_shared/mixins/gl_feature_flags_mixin'; import glFeatureFlagMixin from '~/vue_shared/mixins/gl_feature_flags_mixin';
import defaultSortableConfig from '~/sortable/sortable_config'; import defaultSortableConfig from '~/sortable/sortable_config';
import { sortableEnd, sortableStart } from '~/boards/mixins/sortable_default_options'; import { sortableEnd, sortableStart } from '~/boards/mixins/sortable_default_options';
export default { export default {
components: { components: {
BoardColumn: gon.features?.graphqlBoardLists ? BoardColumnNew : BoardColumn, BoardColumn: gon.features?.graphqlBoardLists ? BoardColumn : BoardColumnDeprecated,
BoardContentSidebar: () => import('ee_component/boards/components/board_content_sidebar.vue'), BoardContentSidebar: () => import('ee_component/boards/components/board_content_sidebar.vue'),
EpicsSwimlanes: () => import('ee_component/boards/components/epics_swimlanes.vue'), EpicsSwimlanes: () => import('ee_component/boards/components/epics_swimlanes.vue'),
GlAlert, GlAlert,
...@@ -20,7 +20,8 @@ export default { ...@@ -20,7 +20,8 @@ export default {
props: { props: {
lists: { lists: {
type: Array, type: Array,
required: true, required: false,
default: () => [],
}, },
canAdminList: { canAdminList: {
type: Boolean, type: Boolean,
...@@ -53,7 +54,7 @@ export default { ...@@ -53,7 +54,7 @@ export default {
fallbackOnBody: false, fallbackOnBody: false,
group: 'boards-list', group: 'boards-list',
tag: 'div', tag: 'div',
value: this.lists, value: this.boardListsToUse,
}; };
return this.canDragColumns ? options : {}; return this.canDragColumns ? options : {};
......
<script>
import Draggable from 'vuedraggable';
import { mapActions, mapState } from 'vuex';
import { GlLoadingIcon } from '@gitlab/ui';
import defaultSortableConfig from '~/sortable/sortable_config';
import { sortableStart, sortableEnd } from '~/boards/mixins/sortable_default_options';
import BoardNewIssue from './board_new_issue_new.vue';
import BoardCard from './board_card.vue';
import eventHub from '../eventhub';
import { sprintf, __ } from '~/locale';
export default {
name: 'BoardList',
i18n: {
loadingIssues: __('Loading issues'),
loadingMoreissues: __('Loading more issues'),
showingAllIssues: __('Showing all issues'),
},
components: {
BoardCard,
BoardNewIssue,
GlLoadingIcon,
},
props: {
disabled: {
type: Boolean,
required: true,
},
list: {
type: Object,
required: true,
},
issues: {
type: Array,
required: true,
},
canAdminList: {
type: Boolean,
required: false,
default: false,
},
},
data() {
return {
scrollOffset: 250,
showCount: false,
showIssueForm: false,
};
},
computed: {
...mapState(['pageInfoByListId', 'listsFlags']),
paginatedIssueText() {
return sprintf(__('Showing %{pageSize} of %{total} issues'), {
pageSize: this.issues.length,
total: this.list.issuesCount,
});
},
issuesSizeExceedsMax() {
return this.list.maxIssueCount > 0 && this.list.issuesCount > this.list.maxIssueCount;
},
hasNextPage() {
return this.pageInfoByListId[this.list.id].hasNextPage;
},
loading() {
return this.listsFlags[this.list.id]?.isLoading;
},
loadingMore() {
return this.listsFlags[this.list.id]?.isLoadingMore;
},
listRef() {
// When list is draggable, the reference to the list needs to be accessed differently
return this.canAdminList ? this.$refs.list.$el : this.$refs.list;
},
showingAllIssues() {
return this.issues.length === this.list.issuesCount;
},
treeRootWrapper() {
return this.canAdminList ? Draggable : 'ul';
},
treeRootOptions() {
const options = {
...defaultSortableConfig,
fallbackOnBody: false,
group: 'board-list',
tag: 'ul',
'ghost-class': 'board-card-drag-active',
'data-list-id': this.list.id,
value: this.issues,
};
return this.canAdminList ? options : {};
},
},
watch: {
issues() {
this.$nextTick(() => {
this.showCount = this.scrollHeight() > Math.ceil(this.listHeight());
});
},
},
created() {
eventHub.$on(`toggle-issue-form-${this.list.id}`, this.toggleForm);
eventHub.$on(`scroll-board-list-${this.list.id}`, this.scrollToTop);
},
mounted() {
// Scroll event on list to load more
this.listRef.addEventListener('scroll', this.onScroll);
},
beforeDestroy() {
eventHub.$off(`toggle-issue-form-${this.list.id}`, this.toggleForm);
eventHub.$off(`scroll-board-list-${this.list.id}`, this.scrollToTop);
this.listRef.removeEventListener('scroll', this.onScroll);
},
methods: {
...mapActions(['fetchIssuesForList', 'moveIssue']),
listHeight() {
return this.listRef.getBoundingClientRect().height;
},
scrollHeight() {
return this.listRef.scrollHeight;
},
scrollTop() {
return this.listRef.scrollTop + this.listHeight();
},
scrollToTop() {
this.listRef.scrollTop = 0;
},
loadNextPage() {
this.fetchIssuesForList({ listId: this.list.id, fetchNext: true });
},
toggleForm() {
this.showIssueForm = !this.showIssueForm;
},
onScroll() {
window.requestAnimationFrame(() => {
if (
!this.loadingMore &&
this.scrollTop() > this.scrollHeight() - this.scrollOffset &&
this.hasNextPage
) {
this.loadNextPage();
}
});
},
handleDragOnStart() {
sortableStart();
},
handleDragOnEnd(params) {
sortableEnd();
const { newIndex, oldIndex, from, to, item } = params;
const { issueId, issueIid, issuePath } = item.dataset;
const { children } = to;
let moveBeforeId;
let moveAfterId;
const getIssueId = (el) => Number(el.dataset.issueId);
// If issue is being moved within the same list
if (from === to) {
if (newIndex > oldIndex && children.length > 1) {
// If issue is being moved down we look for the issue that ends up before
moveBeforeId = getIssueId(children[newIndex]);
} else if (newIndex < oldIndex && children.length > 1) {
// If issue is being moved up we look for the issue that ends up after
moveAfterId = getIssueId(children[newIndex]);
} else {
// If issue remains in the same list at the same position we do nothing
return;
}
} else {
// We look for the issue that ends up before the moved issue if it exists
if (children[newIndex - 1]) {
moveBeforeId = getIssueId(children[newIndex - 1]);
}
// We look for the issue that ends up after the moved issue if it exists
if (children[newIndex]) {
moveAfterId = getIssueId(children[newIndex]);
}
}
this.moveIssue({
issueId,
issueIid,
issuePath,
fromListId: from.dataset.listId,
toListId: to.dataset.listId,
moveBeforeId,
moveAfterId,
});
},
},
};
</script>
<template>
<div
v-show="!list.collapsed"
class="board-list-component gl-relative gl-h-full gl-display-flex gl-flex-direction-column"
data-qa-selector="board_list_cards_area"
>
<div
v-if="loading"
class="gl-mt-4 gl-text-center"
:aria-label="$options.i18n.loadingIssues"
data-testid="board_list_loading"
>
<gl-loading-icon />
</div>
<board-new-issue v-if="list.listType !== 'closed' && showIssueForm" :list="list" />
<component
:is="treeRootWrapper"
v-show="!loading"
ref="list"
v-bind="treeRootOptions"
:data-board="list.id"
:data-board-type="list.listType"
:class="{ 'bg-danger-100': issuesSizeExceedsMax }"
class="board-list gl-w-full gl-h-full gl-list-style-none gl-mb-0 gl-p-2 js-board-list"
data-testid="tree-root-wrapper"
@start="handleDragOnStart"
@end="handleDragOnEnd"
>
<board-card
v-for="(issue, index) in issues"
ref="issue"
:key="issue.id"
:index="index"
:list="list"
:issue="issue"
:disabled="disabled"
/>
<li v-if="showCount" class="board-list-count gl-text-center" data-issue-id="-1">
<gl-loading-icon v-if="loadingMore" :label="$options.i18n.loadingMoreissues" />
<span v-if="showingAllIssues">{{ $options.i18n.showingAllIssues }}</span>
<span v-else>{{ paginatedIssueText }}</span>
</li>
</component>
</div>
</template>
<script> <script>
import { mapActions, mapState } from 'vuex';
import { GlButton } from '@gitlab/ui'; import { GlButton } from '@gitlab/ui';
import { getMilestone } from 'ee_else_ce/boards/boards_util'; import { getMilestone } from 'ee_else_ce/boards/boards_util';
import ListIssue from 'ee_else_ce/boards/models/issue';
import eventHub from '../eventhub'; import eventHub from '../eventhub';
import ProjectSelect from './project_select_deprecated.vue'; import ProjectSelect from './project_select.vue';
import boardsStore from '../stores/boards_store';
import glFeatureFlagMixin from '~/vue_shared/mixins/gl_feature_flags_mixin'; import glFeatureFlagMixin from '~/vue_shared/mixins/gl_feature_flags_mixin';
import { __ } from '~/locale';
// This component is being replaced in favor of './board_new_issue_new.vue' for GraphQL boards
export default { export default {
name: 'BoardNewIssue', name: 'BoardNewIssue',
i18n: {
submit: __('Submit issue'),
cancel: __('Cancel'),
},
components: { components: {
ProjectSelect, ProjectSelect,
GlButton, GlButton,
}, },
mixins: [glFeatureFlagMixin()], mixins: [glFeatureFlagMixin()],
inject: ['groupId'], inject: ['groupId', 'weightFeatureAvailable', 'boardWeight'],
props: { props: {
list: { list: {
type: Object, type: Object,
...@@ -26,69 +28,58 @@ export default { ...@@ -26,69 +28,58 @@ export default {
data() { data() {
return { return {
title: '', title: '',
error: false,
selectedProject: {},
}; };
}, },
computed: { computed: {
...mapState(['selectedProject']),
disabled() { disabled() {
if (this.groupId) { if (this.groupId) {
return this.title === '' || !this.selectedProject.name; return this.title === '' || !this.selectedProject.name;
} }
return this.title === ''; return this.title === '';
}, },
inputFieldId() {
// eslint-disable-next-line @gitlab/require-i18n-strings
return `${this.list.id}-title`;
},
}, },
mounted() { mounted() {
this.$refs.input.focus(); this.$refs.input.focus();
eventHub.$on('setSelectedProject', this.setSelectedProject); eventHub.$on('setSelectedProject', this.setSelectedProject);
}, },
methods: { methods: {
...mapActions(['addListNewIssue']),
submit(e) { submit(e) {
e.preventDefault(); e.preventDefault();
if (this.title.trim() === '') return Promise.resolve();
this.error = false;
const labels = this.list.label ? [this.list.label] : []; const labels = this.list.label ? [this.list.label] : [];
const assignees = this.list.assignee ? [this.list.assignee] : []; const assignees = this.list.assignee ? [this.list.assignee] : [];
const milestone = getMilestone(this.list); const milestone = getMilestone(this.list);
const { weightFeatureAvailable } = boardsStore; const weight = this.weightFeatureAvailable ? this.boardWeight : undefined;
const { weight } = weightFeatureAvailable ? boardsStore.state.currentBoard : {};
const issue = new ListIssue({ const { title } = this;
title: this.title,
labels,
subscribed: true,
assignees,
milestone,
project_id: this.selectedProject.id,
weight,
});
eventHub.$emit(`scroll-board-list-${this.list.id}`); eventHub.$emit(`scroll-board-list-${this.list.id}`);
this.cancel();
return this.list return this.addListNewIssue({
.newIssue(issue) issueInput: {
.then(() => { title,
boardsStore.setIssueDetail(issue); labelIds: labels?.map((l) => l.id),
boardsStore.setListDetail(this.list); assigneeIds: assignees?.map((a) => a?.id),
}) milestoneId: milestone?.id,
.catch(() => { projectPath: this.selectedProject.fullPath,
this.list.removeIssue(issue); weight: weight >= 0 ? weight : null,
},
// Show error message list: this.list,
this.error = true; }).then(() => {
}); this.reset();
});
}, },
cancel() { reset() {
this.title = ''; this.title = '';
eventHub.$emit(`toggle-issue-form-${this.list.id}`); eventHub.$emit(`toggle-issue-form-${this.list.id}`);
}, },
setSelectedProject(selectedProject) {
this.selectedProject = selectedProject;
},
}, },
}; };
</script> </script>
...@@ -96,13 +87,10 @@ export default { ...@@ -96,13 +87,10 @@ export default {
<template> <template>
<div class="board-new-issue-form"> <div class="board-new-issue-form">
<div class="board-card position-relative p-3 rounded"> <div class="board-card position-relative p-3 rounded">
<form @submit="submit($event)"> <form ref="submitForm" @submit="submit">
<div v-if="error" class="flash-container"> <label :for="inputFieldId" class="label-bold">{{ __('Title') }}</label>
<div class="flash-alert">{{ __('An error occurred. Please try again.') }}</div>
</div>
<label :for="list.id + '-title'" class="label-bold">{{ __('Title') }}</label>
<input <input
:id="list.id + '-title'" :id="inputFieldId"
ref="input" ref="input"
v-model="title" v-model="title"
class="form-control" class="form-control"
...@@ -119,16 +107,18 @@ export default { ...@@ -119,16 +107,18 @@ export default {
variant="success" variant="success"
category="primary" category="primary"
type="submit" type="submit"
>{{ __('Submit issue') }}</gl-button
> >
{{ $options.i18n.submit }}
</gl-button>
<gl-button <gl-button
ref="cancelButton" ref="cancelButton"
class="float-right" class="float-right"
type="button" type="button"
variant="default" variant="default"
@click="cancel" @click="reset"
>{{ __('Cancel') }}</gl-button
> >
{{ $options.i18n.cancel }}
</gl-button>
</div> </div>
</form> </form>
</div> </div>
......
<script> <script>
import { mapActions, mapState } from 'vuex';
import { GlButton } from '@gitlab/ui'; import { GlButton } from '@gitlab/ui';
import { getMilestone } from 'ee_else_ce/boards/boards_util'; import { getMilestone } from 'ee_else_ce/boards/boards_util';
import ListIssue from 'ee_else_ce/boards/models/issue';
import eventHub from '../eventhub'; import eventHub from '../eventhub';
import ProjectSelect from './project_select.vue'; import ProjectSelect from './project_select_deprecated.vue';
import boardsStore from '../stores/boards_store';
import glFeatureFlagMixin from '~/vue_shared/mixins/gl_feature_flags_mixin'; import glFeatureFlagMixin from '~/vue_shared/mixins/gl_feature_flags_mixin';
import { __ } from '~/locale';
// This component is being replaced in favor of './board_new_issue.vue' for GraphQL boards
export default { export default {
name: 'BoardNewIssue', name: 'BoardNewIssue',
i18n: {
submit: __('Submit issue'),
cancel: __('Cancel'),
},
components: { components: {
ProjectSelect, ProjectSelect,
GlButton, GlButton,
}, },
mixins: [glFeatureFlagMixin()], mixins: [glFeatureFlagMixin()],
inject: ['groupId', 'weightFeatureAvailable', 'boardWeight'], inject: ['groupId'],
props: { props: {
list: { list: {
type: Object, type: Object,
...@@ -28,57 +26,69 @@ export default { ...@@ -28,57 +26,69 @@ export default {
data() { data() {
return { return {
title: '', title: '',
error: false,
selectedProject: {},
}; };
}, },
computed: { computed: {
...mapState(['selectedProject']),
disabled() { disabled() {
if (this.groupId) { if (this.groupId) {
return this.title === '' || !this.selectedProject.name; return this.title === '' || !this.selectedProject.name;
} }
return this.title === ''; return this.title === '';
}, },
inputFieldId() {
// eslint-disable-next-line @gitlab/require-i18n-strings
return `${this.list.id}-title`;
},
}, },
mounted() { mounted() {
this.$refs.input.focus(); this.$refs.input.focus();
eventHub.$on('setSelectedProject', this.setSelectedProject);
}, },
methods: { methods: {
...mapActions(['addListNewIssue']),
submit(e) { submit(e) {
e.preventDefault(); e.preventDefault();
if (this.title.trim() === '') return Promise.resolve();
this.error = false;
const labels = this.list.label ? [this.list.label] : []; const labels = this.list.label ? [this.list.label] : [];
const assignees = this.list.assignee ? [this.list.assignee] : []; const assignees = this.list.assignee ? [this.list.assignee] : [];
const milestone = getMilestone(this.list); const milestone = getMilestone(this.list);
const weight = this.weightFeatureAvailable ? this.boardWeight : undefined; const { weightFeatureAvailable } = boardsStore;
const { weight } = weightFeatureAvailable ? boardsStore.state.currentBoard : {};
const { title } = this; const issue = new ListIssue({
title: this.title,
labels,
subscribed: true,
assignees,
milestone,
project_id: this.selectedProject.id,
weight,
});
eventHub.$emit(`scroll-board-list-${this.list.id}`); eventHub.$emit(`scroll-board-list-${this.list.id}`);
this.cancel();
return this.addListNewIssue({ return this.list
issueInput: { .newIssue(issue)
title, .then(() => {
labelIds: labels?.map((l) => l.id), boardsStore.setIssueDetail(issue);
assigneeIds: assignees?.map((a) => a?.id), boardsStore.setListDetail(this.list);
milestoneId: milestone?.id, })
projectPath: this.selectedProject.fullPath, .catch(() => {
weight: weight >= 0 ? weight : null, this.list.removeIssue(issue);
},
list: this.list, // Show error message
}).then(() => { this.error = true;
this.reset(); });
});
}, },
reset() { cancel() {
this.title = ''; this.title = '';
eventHub.$emit(`toggle-issue-form-${this.list.id}`); eventHub.$emit(`toggle-issue-form-${this.list.id}`);
}, },
setSelectedProject(selectedProject) {
this.selectedProject = selectedProject;
},
}, },
}; };
</script> </script>
...@@ -86,10 +96,13 @@ export default { ...@@ -86,10 +96,13 @@ export default {
<template> <template>
<div class="board-new-issue-form"> <div class="board-new-issue-form">
<div class="board-card position-relative p-3 rounded"> <div class="board-card position-relative p-3 rounded">
<form ref="submitForm" @submit="submit"> <form @submit="submit($event)">
<label :for="inputFieldId" class="label-bold">{{ __('Title') }}</label> <div v-if="error" class="flash-container">
<div class="flash-alert">{{ __('An error occurred. Please try again.') }}</div>
</div>
<label :for="list.id + '-title'" class="label-bold">{{ __('Title') }}</label>
<input <input
:id="inputFieldId" :id="list.id + '-title'"
ref="input" ref="input"
v-model="title" v-model="title"
class="form-control" class="form-control"
...@@ -106,18 +119,16 @@ export default { ...@@ -106,18 +119,16 @@ export default {
variant="success" variant="success"
category="primary" category="primary"
type="submit" type="submit"
>{{ __('Submit issue') }}</gl-button
> >
{{ $options.i18n.submit }}
</gl-button>
<gl-button <gl-button
ref="cancelButton" ref="cancelButton"
class="float-right" class="float-right"
type="button" type="button"
variant="default" variant="default"
@click="reset" @click="cancel"
>{{ __('Cancel') }}</gl-button
> >
{{ $options.i18n.cancel }}
</gl-button>
</div> </div>
</form> </form>
</div> </div>
......
...@@ -68,8 +68,10 @@ export default () => { ...@@ -68,8 +68,10 @@ export default () => {
issueBoardsApp.$destroy(true); issueBoardsApp.$destroy(true);
} }
boardsStore.create(); if (!gon?.features?.graphqlBoardLists) {
boardsStore.setTimeTrackingLimitToHours($boardApp.dataset.timeTrackingLimitToHours); boardsStore.create();
boardsStore.setTimeTrackingLimitToHours($boardApp.dataset.timeTrackingLimitToHours);
}
issueBoardsApp = new Vue({ issueBoardsApp = new Vue({
el: $boardApp, el: $boardApp,
......
<script> <script>
import BoardListHeaderFoss from '~/boards/components/board_list_header.vue'; import BoardListHeaderFoss from '~/boards/components/board_list_header.vue';
import { __, sprintf, s__ } from '~/locale'; import { __, sprintf, s__ } from '~/locale';
import boardsStore from '~/boards/stores/boards_store';
export default { export default {
extends: BoardListHeaderFoss, extends: BoardListHeaderFoss,
data() { inject: ['weightFeatureAvailable'],
return {
weightFeatureAvailable: boardsStore.weightFeatureAvailable,
};
},
computed: { computed: {
issuesTooltip() { issuesTooltip() {
const { maxIssueCount } = this.list; const { maxIssueCount } = this.list;
......
<script> <script>
import BoardListHeaderFoss from '~/boards/components/board_list_header_new.vue'; import BoardListHeaderFoss from '~/boards/components/board_list_header_deprecated.vue';
import { __, sprintf, s__ } from '~/locale'; import { __, sprintf, s__ } from '~/locale';
import boardsStore from '~/boards/stores/boards_store';
export default { export default {
extends: BoardListHeaderFoss, extends: BoardListHeaderFoss,
inject: ['weightFeatureAvailable'], data() {
return {
weightFeatureAvailable: boardsStore.weightFeatureAvailable,
};
},
computed: { computed: {
issuesTooltip() { issuesTooltip() {
const { maxIssueCount } = this.list; const { maxIssueCount } = this.list;
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
import { mapActions, mapGetters, mapState } from 'vuex'; import { mapActions, mapGetters, mapState } from 'vuex';
import { GlButton, GlIcon, GlTooltipDirective } from '@gitlab/ui'; import { GlButton, GlIcon, GlTooltipDirective } from '@gitlab/ui';
import Draggable from 'vuedraggable'; import Draggable from 'vuedraggable';
import BoardListHeader from 'ee_else_ce/boards/components/board_list_header_new.vue'; import BoardListHeader from 'ee_else_ce/boards/components/board_list_header.vue';
import { DRAGGABLE_TAG } from '../constants'; import { DRAGGABLE_TAG } from '../constants';
import defaultSortableConfig from '~/sortable/sortable_config'; import defaultSortableConfig from '~/sortable/sortable_config';
import { n__ } from '~/locale'; import { n__ } from '~/locale';
......
...@@ -5,7 +5,7 @@ import { GlLoadingIcon } from '@gitlab/ui'; ...@@ -5,7 +5,7 @@ import { GlLoadingIcon } from '@gitlab/ui';
import defaultSortableConfig from '~/sortable/sortable_config'; import defaultSortableConfig from '~/sortable/sortable_config';
import BoardCardLayout from '~/boards/components/board_card_layout.vue'; import BoardCardLayout from '~/boards/components/board_card_layout.vue';
import eventHub from '~/boards/eventhub'; import eventHub from '~/boards/eventhub';
import BoardNewIssue from '~/boards/components/board_new_issue_new.vue'; import BoardNewIssue from '~/boards/components/board_new_issue.vue';
import { ISSUABLE } from '~/boards/constants'; import { ISSUABLE } from '~/boards/constants';
export default { export default {
......
import { shallowMount, createLocalVue } from '@vue/test-utils'; import { shallowMount, createLocalVue } from '@vue/test-utils';
import AxiosMockAdapter from 'axios-mock-adapter';
import Vue from 'vue';
import Vuex from 'vuex'; import Vuex from 'vuex';
import BoardListHeader from 'ee/boards/components/board_list_header_new.vue'; import BoardListHeader from 'ee/boards/components/board_list_header_deprecated.vue';
import getters from 'ee/boards/stores/getters'; import getters from 'ee/boards/stores/getters';
import { mockLabelList } from 'jest/boards/mock_data'; import { TEST_HOST } from 'helpers/test_constants';
import { listObj } from 'jest/boards/mock_data';
import { ListType, inactiveId } from '~/boards/constants'; import { ListType, inactiveId } from '~/boards/constants';
import List from '~/boards/models/list';
import axios from '~/lib/utils/axios_utils';
import sidebarEventHub from '~/sidebar/event_hub'; import sidebarEventHub from '~/sidebar/event_hub';
const localVue = createLocalVue(); const localVue = createLocalVue();
...@@ -14,15 +19,20 @@ localVue.use(Vuex); ...@@ -14,15 +19,20 @@ localVue.use(Vuex);
describe('Board List Header Component', () => { describe('Board List Header Component', () => {
let store; let store;
let wrapper; let wrapper;
let axiosMock;
beforeEach(() => { beforeEach(() => {
window.gon = {};
axiosMock = new AxiosMockAdapter(axios);
axiosMock.onGet(`${TEST_HOST}/lists/1/issues`).reply(200, { issues: [] });
store = new Vuex.Store({ state: { activeId: inactiveId }, getters }); store = new Vuex.Store({ state: { activeId: inactiveId }, getters });
jest.spyOn(store, 'dispatch').mockImplementation(); jest.spyOn(store, 'dispatch').mockImplementation();
}); });
afterEach(() => { afterEach(() => {
axiosMock.restore();
wrapper.destroy(); wrapper.destroy();
wrapper = null;
localStorage.clear(); localStorage.clear();
}); });
...@@ -31,25 +41,26 @@ describe('Board List Header Component', () => { ...@@ -31,25 +41,26 @@ describe('Board List Header Component', () => {
listType = ListType.backlog, listType = ListType.backlog,
collapsed = false, collapsed = false,
withLocalStorage = true, withLocalStorage = true,
isSwimlanesHeader = false,
weightFeatureAvailable = false,
} = {}) => { } = {}) => {
const boardId = '1'; const boardId = '1';
const listMock = { const listMock = {
...mockLabelList, ...listObj,
listType, list_type: listType,
collapsed, collapsed,
}; };
if (listType === ListType.assignee) { if (listType === ListType.assignee) {
delete listMock.label; delete listMock.label;
listMock.assignee = {}; listMock.user = {};
} }
// Making List reactive
const list = Vue.observable(new List(listMock));
if (withLocalStorage) { if (withLocalStorage) {
localStorage.setItem( localStorage.setItem(
`boards.${boardId}.${listMock.listType}.${listMock.id}.expanded`, `boards.${boardId}.${list.type}.${list.id}.expanded`,
(!collapsed).toString(), (!collapsed).toString(),
); );
} }
...@@ -59,12 +70,10 @@ describe('Board List Header Component', () => { ...@@ -59,12 +70,10 @@ describe('Board List Header Component', () => {
localVue, localVue,
propsData: { propsData: {
disabled: false, disabled: false,
list: listMock, list,
isSwimlanesHeader,
}, },
provide: { provide: {
boardId, boardId,
weightFeatureAvailable,
}, },
}); });
}; };
...@@ -88,8 +97,6 @@ describe('Board List Header Component', () => { ...@@ -88,8 +97,6 @@ describe('Board List Header Component', () => {
}); });
it('has a test for each list type', () => { it('has a test for each list type', () => {
createComponent();
Object.values(ListType).forEach((value) => { Object.values(ListType).forEach((value) => {
expect([...hasSettings, ...hasNoSettings]).toContain(value); expect([...hasSettings, ...hasNoSettings]).toContain(value);
}); });
...@@ -109,7 +116,7 @@ describe('Board List Header Component', () => { ...@@ -109,7 +116,7 @@ describe('Board List Header Component', () => {
}); });
it('does not emit event when there is an active List', () => { it('does not emit event when there is an active List', () => {
store.state.activeId = mockLabelList.id; store.state.activeId = listObj.id;
createComponent({ listType: hasSettings[0] }); createComponent({ listType: hasSettings[0] });
wrapper.vm.openSidebarSettings(); wrapper.vm.openSidebarSettings();
...@@ -117,26 +124,4 @@ describe('Board List Header Component', () => { ...@@ -117,26 +124,4 @@ describe('Board List Header Component', () => {
}); });
}); });
}); });
describe('Swimlanes header', () => {
it('when collapsed, it displays info icon', () => {
createComponent({ isSwimlanesHeader: true, collapsed: true });
expect(wrapper.find('.board-header-collapsed-info-icon').exists()).toBe(true);
});
});
describe('weightFeatureAvailable', () => {
it('weightFeatureAvailable is true', () => {
createComponent({ weightFeatureAvailable: true });
expect(wrapper.find({ ref: 'weightTooltip' }).exists()).toBe(true);
});
it('weightFeatureAvailable is false', () => {
createComponent();
expect(wrapper.find({ ref: 'weightTooltip' }).exists()).toBe(false);
});
});
}); });
import { shallowMount, createLocalVue } from '@vue/test-utils'; import { shallowMount, createLocalVue } from '@vue/test-utils';
import AxiosMockAdapter from 'axios-mock-adapter';
import Vue from 'vue';
import Vuex from 'vuex'; import Vuex from 'vuex';
import BoardListHeader from 'ee/boards/components/board_list_header.vue'; import BoardListHeader from 'ee/boards/components/board_list_header.vue';
import getters from 'ee/boards/stores/getters'; import getters from 'ee/boards/stores/getters';
import { TEST_HOST } from 'helpers/test_constants'; import { mockLabelList } from 'jest/boards/mock_data';
import { listObj } from 'jest/boards/mock_data';
import { ListType, inactiveId } from '~/boards/constants'; import { ListType, inactiveId } from '~/boards/constants';
import List from '~/boards/models/list';
import axios from '~/lib/utils/axios_utils';
import sidebarEventHub from '~/sidebar/event_hub'; import sidebarEventHub from '~/sidebar/event_hub';
const localVue = createLocalVue(); const localVue = createLocalVue();
...@@ -19,20 +14,15 @@ localVue.use(Vuex); ...@@ -19,20 +14,15 @@ localVue.use(Vuex);
describe('Board List Header Component', () => { describe('Board List Header Component', () => {
let store; let store;
let wrapper; let wrapper;
let axiosMock;
beforeEach(() => { beforeEach(() => {
window.gon = {};
axiosMock = new AxiosMockAdapter(axios);
axiosMock.onGet(`${TEST_HOST}/lists/1/issues`).reply(200, { issues: [] });
store = new Vuex.Store({ state: { activeId: inactiveId }, getters }); store = new Vuex.Store({ state: { activeId: inactiveId }, getters });
jest.spyOn(store, 'dispatch').mockImplementation(); jest.spyOn(store, 'dispatch').mockImplementation();
}); });
afterEach(() => { afterEach(() => {
axiosMock.restore();
wrapper.destroy(); wrapper.destroy();
wrapper = null;
localStorage.clear(); localStorage.clear();
}); });
...@@ -41,26 +31,25 @@ describe('Board List Header Component', () => { ...@@ -41,26 +31,25 @@ describe('Board List Header Component', () => {
listType = ListType.backlog, listType = ListType.backlog,
collapsed = false, collapsed = false,
withLocalStorage = true, withLocalStorage = true,
isSwimlanesHeader = false,
weightFeatureAvailable = false,
} = {}) => { } = {}) => {
const boardId = '1'; const boardId = '1';
const listMock = { const listMock = {
...listObj, ...mockLabelList,
list_type: listType, listType,
collapsed, collapsed,
}; };
if (listType === ListType.assignee) { if (listType === ListType.assignee) {
delete listMock.label; delete listMock.label;
listMock.user = {}; listMock.assignee = {};
} }
// Making List reactive
const list = Vue.observable(new List(listMock));
if (withLocalStorage) { if (withLocalStorage) {
localStorage.setItem( localStorage.setItem(
`boards.${boardId}.${list.type}.${list.id}.expanded`, `boards.${boardId}.${listMock.listType}.${listMock.id}.expanded`,
(!collapsed).toString(), (!collapsed).toString(),
); );
} }
...@@ -70,10 +59,12 @@ describe('Board List Header Component', () => { ...@@ -70,10 +59,12 @@ describe('Board List Header Component', () => {
localVue, localVue,
propsData: { propsData: {
disabled: false, disabled: false,
list, list: listMock,
isSwimlanesHeader,
}, },
provide: { provide: {
boardId, boardId,
weightFeatureAvailable,
}, },
}); });
}; };
...@@ -97,6 +88,8 @@ describe('Board List Header Component', () => { ...@@ -97,6 +88,8 @@ describe('Board List Header Component', () => {
}); });
it('has a test for each list type', () => { it('has a test for each list type', () => {
createComponent();
Object.values(ListType).forEach((value) => { Object.values(ListType).forEach((value) => {
expect([...hasSettings, ...hasNoSettings]).toContain(value); expect([...hasSettings, ...hasNoSettings]).toContain(value);
}); });
...@@ -116,7 +109,7 @@ describe('Board List Header Component', () => { ...@@ -116,7 +109,7 @@ describe('Board List Header Component', () => {
}); });
it('does not emit event when there is an active List', () => { it('does not emit event when there is an active List', () => {
store.state.activeId = listObj.id; store.state.activeId = mockLabelList.id;
createComponent({ listType: hasSettings[0] }); createComponent({ listType: hasSettings[0] });
wrapper.vm.openSidebarSettings(); wrapper.vm.openSidebarSettings();
...@@ -124,4 +117,26 @@ describe('Board List Header Component', () => { ...@@ -124,4 +117,26 @@ describe('Board List Header Component', () => {
}); });
}); });
}); });
describe('Swimlanes header', () => {
it('when collapsed, it displays info icon', () => {
createComponent({ isSwimlanesHeader: true, collapsed: true });
expect(wrapper.find('.board-header-collapsed-info-icon').exists()).toBe(true);
});
});
describe('weightFeatureAvailable', () => {
it('weightFeatureAvailable is true', () => {
createComponent({ weightFeatureAvailable: true });
expect(wrapper.find({ ref: 'weightTooltip' }).exists()).toBe(true);
});
it('weightFeatureAvailable is false', () => {
createComponent();
expect(wrapper.find({ ref: 'weightTooltip' }).exists()).toBe(false);
});
});
}); });
...@@ -6,7 +6,7 @@ import EpicLane from 'ee/boards/components/epic_lane.vue'; ...@@ -6,7 +6,7 @@ import EpicLane from 'ee/boards/components/epic_lane.vue';
import EpicsSwimlanes from 'ee/boards/components/epics_swimlanes.vue'; import EpicsSwimlanes from 'ee/boards/components/epics_swimlanes.vue';
import IssueLaneList from 'ee/boards/components/issues_lane_list.vue'; import IssueLaneList from 'ee/boards/components/issues_lane_list.vue';
import getters from 'ee/boards/stores/getters'; import getters from 'ee/boards/stores/getters';
import BoardListHeader from 'ee_else_ce/boards/components/board_list_header_new.vue'; import BoardListHeader from 'ee_else_ce/boards/components/board_list_header.vue';
import { mockLists, mockEpics, mockIssuesByListId, issues } from '../mock_data'; import { mockLists, mockEpics, mockIssuesByListId, issues } from '../mock_data';
const localVue = createLocalVue(); const localVue = createLocalVue();
......
/* global List */
/* global ListIssue */
import Vue from 'vue';
import MockAdapter from 'axios-mock-adapter';
import waitForPromises from 'helpers/wait_for_promises';
import axios from '~/lib/utils/axios_utils';
import eventHub from '~/boards/eventhub';
import BoardList from '~/boards/components/board_list_deprecated.vue';
import '~/boards/models/issue';
import '~/boards/models/list';
import { listObj, boardsMockInterceptor } from './mock_data';
import store from '~/boards/stores';
import boardsStore from '~/boards/stores/boards_store';
const createComponent = ({ done, listIssueProps = {}, componentProps = {}, listProps = {} }) => {
const el = document.createElement('div');
document.body.appendChild(el);
const mock = new MockAdapter(axios);
mock.onAny().reply(boardsMockInterceptor);
boardsStore.create();
const BoardListComp = Vue.extend(BoardList);
const list = new List({ ...listObj, ...listProps });
const issue = new ListIssue({
title: 'Testing',
id: 1,
iid: 1,
confidential: false,
labels: [],
assignees: [],
...listIssueProps,
});
if (!Object.prototype.hasOwnProperty.call(listProps, 'issuesSize')) {
list.issuesSize = 1;
}
list.issues.push(issue);
const component = new BoardListComp({
el,
store,
propsData: {
disabled: false,
list,
issues: list.issues,
...componentProps,
},
provide: {
groupId: null,
rootPath: '/',
},
}).$mount();
Vue.nextTick(() => {
done();
});
return { component, mock };
};
describe('Board list component', () => {
let mock;
let component;
let getIssues;
function generateIssues(compWrapper) {
for (let i = 1; i < 20; i += 1) {
const issue = { ...compWrapper.list.issues[0] };
issue.id += i;
compWrapper.list.issues.push(issue);
}
}
describe('When Expanded', () => {
beforeEach((done) => {
getIssues = jest.spyOn(List.prototype, 'getIssues').mockReturnValue(new Promise(() => {}));
({ mock, component } = createComponent({ done }));
});
afterEach(() => {
mock.restore();
component.$destroy();
});
it('loads first page of issues', () => {
return waitForPromises().then(() => {
expect(getIssues).toHaveBeenCalled();
});
});
it('renders component', () => {
expect(component.$el.classList.contains('board-list-component')).toBe(true);
});
it('renders loading icon', () => {
component.list.loading = true;
return Vue.nextTick().then(() => {
expect(component.$el.querySelector('.board-list-loading')).not.toBeNull();
});
});
it('renders issues', () => {
expect(component.$el.querySelectorAll('.board-card').length).toBe(1);
});
it('sets data attribute with issue id', () => {
expect(component.$el.querySelector('.board-card').getAttribute('data-issue-id')).toBe('1');
});
it('shows new issue form', () => {
component.toggleForm();
return Vue.nextTick().then(() => {
expect(component.$el.querySelector('.board-new-issue-form')).not.toBeNull();
expect(component.$el.querySelector('.is-smaller')).not.toBeNull();
});
});
it('shows new issue form after eventhub event', () => {
eventHub.$emit(`toggle-issue-form-${component.list.id}`);
return Vue.nextTick().then(() => {
expect(component.$el.querySelector('.board-new-issue-form')).not.toBeNull();
expect(component.$el.querySelector('.is-smaller')).not.toBeNull();
});
});
it('does not show new issue form for closed list', () => {
component.list.type = 'closed';
component.toggleForm();
return Vue.nextTick().then(() => {
expect(component.$el.querySelector('.board-new-issue-form')).toBeNull();
});
});
it('shows count list item', () => {
component.showCount = true;
return Vue.nextTick().then(() => {
expect(component.$el.querySelector('.board-list-count')).not.toBeNull();
expect(component.$el.querySelector('.board-list-count').textContent.trim()).toBe(
'Showing all issues',
);
});
});
it('sets data attribute with invalid id', () => {
component.showCount = true;
return Vue.nextTick().then(() => {
expect(component.$el.querySelector('.board-list-count').getAttribute('data-issue-id')).toBe(
'-1',
);
});
});
it('shows how many more issues to load', () => {
component.showCount = true;
component.list.issuesSize = 20;
return Vue.nextTick().then(() => {
expect(component.$el.querySelector('.board-list-count').textContent.trim()).toBe(
'Showing 1 of 20 issues',
);
});
});
it('loads more issues after scrolling', () => {
jest.spyOn(component.list, 'nextPage').mockImplementation(() => {});
generateIssues(component);
component.$refs.list.dispatchEvent(new Event('scroll'));
return waitForPromises().then(() => {
expect(component.list.nextPage).toHaveBeenCalled();
});
});
it('does not load issues if already loading', () => {
component.list.nextPage = jest
.spyOn(component.list, 'nextPage')
.mockReturnValue(new Promise(() => {}));
component.onScroll();
component.onScroll();
return waitForPromises().then(() => {
expect(component.list.nextPage).toHaveBeenCalledTimes(1);
});
});
it('shows loading more spinner', () => {
component.showCount = true;
component.list.loadingMore = true;
return Vue.nextTick().then(() => {
expect(component.$el.querySelector('.board-list-count .gl-spinner')).not.toBeNull();
});
});
});
describe('When Collapsed', () => {
beforeEach((done) => {
getIssues = jest.spyOn(List.prototype, 'getIssues').mockReturnValue(new Promise(() => {}));
({ mock, component } = createComponent({
done,
listProps: { type: 'closed', collapsed: true, issuesSize: 50 },
}));
generateIssues(component);
component.scrollHeight = jest.spyOn(component, 'scrollHeight').mockReturnValue(0);
});
afterEach(() => {
mock.restore();
component.$destroy();
});
it('does not load all issues', () => {
return waitForPromises().then(() => {
// Initial getIssues from list constructor
expect(getIssues).toHaveBeenCalledTimes(1);
});
});
});
describe('max issue count warning', () => {
beforeEach((done) => {
({ mock, component } = createComponent({
done,
listProps: { type: 'closed', collapsed: true, issuesSize: 50 },
}));
});
afterEach(() => {
mock.restore();
component.$destroy();
});
describe('when issue count exceeds max issue count', () => {
it('sets background to bg-danger-100', () => {
component.list.issuesSize = 4;
component.list.maxIssueCount = 3;
return Vue.nextTick().then(() => {
expect(component.$el.querySelector('.bg-danger-100')).not.toBeNull();
});
});
});
describe('when list issue count does NOT exceed list max issue count', () => {
it('does not sets background to bg-danger-100', () => {
component.list.issuesSize = 2;
component.list.maxIssueCount = 3;
return Vue.nextTick().then(() => {
expect(component.$el.querySelector('.bg-danger-100')).toBeNull();
});
});
});
describe('when list max issue count is 0', () => {
it('does not sets background to bg-danger-100', () => {
component.list.maxIssueCount = 0;
return Vue.nextTick().then(() => {
expect(component.$el.querySelector('.bg-danger-100')).toBeNull();
});
});
});
});
});
...@@ -5,7 +5,7 @@ import MockAdapter from 'axios-mock-adapter'; ...@@ -5,7 +5,7 @@ import MockAdapter from 'axios-mock-adapter';
import Vue from 'vue'; import Vue from 'vue';
import Sortable from 'sortablejs'; import Sortable from 'sortablejs';
import axios from '~/lib/utils/axios_utils'; import axios from '~/lib/utils/axios_utils';
import BoardList from '~/boards/components/board_list.vue'; import BoardList from '~/boards/components/board_list_deprecated.vue';
import '~/boards/models/issue'; import '~/boards/models/issue';
import '~/boards/models/list'; import '~/boards/models/list';
......
import Vuex from 'vuex';
import { useFakeRequestAnimationFrame } from 'helpers/fake_request_animation_frame';
import { createLocalVue, mount } from '@vue/test-utils';
import eventHub from '~/boards/eventhub';
import BoardList from '~/boards/components/board_list_new.vue';
import BoardCard from '~/boards/components/board_card.vue';
import '~/boards/models/list';
import { mockList, mockIssuesByListId, issues, mockIssues } from './mock_data';
import defaultState from '~/boards/stores/state';
const localVue = createLocalVue();
localVue.use(Vuex);
const actions = {
fetchIssuesForList: jest.fn(),
};
const createStore = (state = defaultState) => {
return new Vuex.Store({
state,
actions,
});
};
const createComponent = ({
listIssueProps = {},
componentProps = {},
listProps = {},
state = {},
} = {}) => {
const store = createStore({
issuesByListId: mockIssuesByListId,
issues,
pageInfoByListId: {
'gid://gitlab/List/1': { hasNextPage: true },
'gid://gitlab/List/2': {},
},
listsFlags: {
'gid://gitlab/List/1': {},
'gid://gitlab/List/2': {},
},
...state,
});
const list = {
...mockList,
...listProps,
};
const issue = {
title: 'Testing',
id: 1,
iid: 1,
confidential: false,
labels: [],
assignees: [],
...listIssueProps,
};
if (!Object.prototype.hasOwnProperty.call(listProps, 'issuesCount')) {
list.issuesCount = 1;
}
const component = mount(BoardList, {
localVue,
propsData: {
disabled: false,
list,
issues: [issue],
canAdminList: true,
...componentProps,
},
store,
provide: {
groupId: null,
rootPath: '/',
weightFeatureAvailable: false,
boardWeight: null,
},
});
return component;
};
describe('Board list component', () => {
let wrapper;
const findByTestId = (testId) => wrapper.find(`[data-testid="${testId}"]`);
useFakeRequestAnimationFrame();
afterEach(() => {
wrapper.destroy();
wrapper = null;
});
describe('When Expanded', () => {
beforeEach(() => {
wrapper = createComponent();
});
it('renders component', () => {
expect(wrapper.find('.board-list-component').exists()).toBe(true);
});
it('renders loading icon', () => {
wrapper = createComponent({
state: { listsFlags: { 'gid://gitlab/List/1': { isLoading: true } } },
});
expect(findByTestId('board_list_loading').exists()).toBe(true);
});
it('renders issues', () => {
expect(wrapper.findAll(BoardCard).length).toBe(1);
});
it('sets data attribute with issue id', () => {
expect(wrapper.find('.board-card').attributes('data-issue-id')).toBe('1');
});
it('shows new issue form', async () => {
wrapper.vm.toggleForm();
await wrapper.vm.$nextTick();
expect(wrapper.find('.board-new-issue-form').exists()).toBe(true);
});
it('shows new issue form after eventhub event', async () => {
eventHub.$emit(`toggle-issue-form-${wrapper.vm.list.id}`);
await wrapper.vm.$nextTick();
expect(wrapper.find('.board-new-issue-form').exists()).toBe(true);
});
it('does not show new issue form for closed list', () => {
wrapper.setProps({ list: { type: 'closed' } });
wrapper.vm.toggleForm();
expect(wrapper.find('.board-new-issue-form').exists()).toBe(false);
});
it('shows count list item', async () => {
wrapper.vm.showCount = true;
await wrapper.vm.$nextTick();
expect(wrapper.find('.board-list-count').exists()).toBe(true);
expect(wrapper.find('.board-list-count').text()).toBe('Showing all issues');
});
it('sets data attribute with invalid id', async () => {
wrapper.vm.showCount = true;
await wrapper.vm.$nextTick();
expect(wrapper.find('.board-list-count').attributes('data-issue-id')).toBe('-1');
});
it('shows how many more issues to load', async () => {
wrapper.vm.showCount = true;
wrapper.setProps({ list: { issuesCount: 20 } });
await wrapper.vm.$nextTick();
expect(wrapper.find('.board-list-count').text()).toBe('Showing 1 of 20 issues');
});
});
describe('load more issues', () => {
beforeEach(() => {
wrapper = createComponent({
listProps: { issuesCount: 25 },
});
});
it('loads more issues after scrolling', () => {
wrapper.vm.listRef.dispatchEvent(new Event('scroll'));
expect(actions.fetchIssuesForList).toHaveBeenCalled();
});
it('does not load issues if already loading', () => {
wrapper = createComponent({
state: { listsFlags: { 'gid://gitlab/List/1': { isLoadingMore: true } } },
});
wrapper.vm.listRef.dispatchEvent(new Event('scroll'));
expect(actions.fetchIssuesForList).not.toHaveBeenCalled();
});
it('shows loading more spinner', async () => {
wrapper = createComponent({
state: { listsFlags: { 'gid://gitlab/List/1': { isLoadingMore: true } } },
});
wrapper.vm.showCount = true;
await wrapper.vm.$nextTick();
expect(wrapper.find('.board-list-count .gl-spinner').exists()).toBe(true);
});
});
describe('max issue count warning', () => {
beforeEach(() => {
wrapper = createComponent({
listProps: { issuesCount: 50 },
});
});
describe('when issue count exceeds max issue count', () => {
it('sets background to bg-danger-100', async () => {
wrapper.setProps({ list: { issuesCount: 4, maxIssueCount: 3 } });
await wrapper.vm.$nextTick();
expect(wrapper.find('.bg-danger-100').exists()).toBe(true);
});
});
describe('when list issue count does NOT exceed list max issue count', () => {
it('does not sets background to bg-danger-100', () => {
wrapper.setProps({ list: { issuesCount: 2, maxIssueCount: 3 } });
expect(wrapper.find('.bg-danger-100').exists()).toBe(false);
});
});
describe('when list max issue count is 0', () => {
it('does not sets background to bg-danger-100', () => {
wrapper.setProps({ list: { maxIssueCount: 0 } });
expect(wrapper.find('.bg-danger-100').exists()).toBe(false);
});
});
});
describe('drag & drop issue', () => {
beforeEach(() => {
wrapper = createComponent();
});
describe('handleDragOnStart', () => {
it('adds a class `is-dragging` to document body', () => {
expect(document.body.classList.contains('is-dragging')).toBe(false);
findByTestId('tree-root-wrapper').vm.$emit('start');
expect(document.body.classList.contains('is-dragging')).toBe(true);
});
});
describe('handleDragOnEnd', () => {
it('removes class `is-dragging` from document body', () => {
jest.spyOn(wrapper.vm, 'moveIssue').mockImplementation(() => {});
document.body.classList.add('is-dragging');
findByTestId('tree-root-wrapper').vm.$emit('end', {
oldIndex: 1,
newIndex: 0,
item: {
dataset: {
issueId: mockIssues[0].id,
issueIid: mockIssues[0].iid,
issuePath: mockIssues[0].referencePath,
},
},
to: { children: [], dataset: { listId: 'gid://gitlab/List/1' } },
from: { dataset: { listId: 'gid://gitlab/List/2' } },
});
expect(document.body.classList.contains('is-dragging')).toBe(false);
});
});
});
});
This diff is collapsed.
...@@ -4,7 +4,7 @@ import Vue from 'vue'; ...@@ -4,7 +4,7 @@ import Vue from 'vue';
import { mount } from '@vue/test-utils'; import { mount } from '@vue/test-utils';
import MockAdapter from 'axios-mock-adapter'; import MockAdapter from 'axios-mock-adapter';
import axios from '~/lib/utils/axios_utils'; import axios from '~/lib/utils/axios_utils';
import boardNewIssue from '~/boards/components/board_new_issue.vue'; import boardNewIssue from '~/boards/components/board_new_issue_deprecated.vue';
import boardsStore from '~/boards/stores/boards_store'; import boardsStore from '~/boards/stores/boards_store';
import '~/boards/models/list'; import '~/boards/models/list';
......
import Vue from 'vue';
import { shallowMount } from '@vue/test-utils'; import { shallowMount } from '@vue/test-utils';
import AxiosMockAdapter from 'axios-mock-adapter';
import { TEST_HOST } from 'helpers/test_constants';
import { listObj } from 'jest/boards/mock_data'; import { listObj } from 'jest/boards/mock_data';
import BoardColumn from '~/boards/components/board_column_new.vue'; import Board from '~/boards/components/board_column_deprecated.vue';
import List from '~/boards/models/list';
import { ListType } from '~/boards/constants'; import { ListType } from '~/boards/constants';
import { createStore } from '~/boards/stores'; import axios from '~/lib/utils/axios_utils';
describe('Board Column Component', () => { describe('Board Column Component', () => {
let wrapper; let wrapper;
let store; let axiosMock;
beforeEach(() => {
window.gon = {};
axiosMock = new AxiosMockAdapter(axios);
axiosMock.onGet(`${TEST_HOST}/lists/1/issues`).reply(200, { issues: [] });
});
afterEach(() => { afterEach(() => {
axiosMock.restore();
wrapper.destroy(); wrapper.destroy();
wrapper = null;
localStorage.clear();
}); });
const createComponent = ({ listType = ListType.backlog, collapsed = false } = {}) => { const createComponent = ({
listType = ListType.backlog,
collapsed = false,
withLocalStorage = true,
} = {}) => {
const boardId = '1'; const boardId = '1';
const listMock = { const listMock = {
...listObj, ...listObj,
listType, list_type: listType,
collapsed, collapsed,
}; };
if (listType === ListType.assignee) { if (listType === ListType.assignee) {
delete listMock.label; delete listMock.label;
listMock.assignee = {}; listMock.user = {};
} }
store = createStore(); // Making List reactive
const list = Vue.observable(new List(listMock));
wrapper = shallowMount(BoardColumn, { if (withLocalStorage) {
store, localStorage.setItem(
`boards.${boardId}.${list.type}.${list.id}.expanded`,
(!collapsed).toString(),
);
}
wrapper = shallowMount(Board, {
propsData: { propsData: {
boardId,
disabled: false, disabled: false,
list: listMock, list,
}, },
provide: { provide: {
boardId, boardId,
...@@ -57,7 +82,7 @@ describe('Board Column Component', () => { ...@@ -57,7 +82,7 @@ describe('Board Column Component', () => {
it('has class is-collapsed when list is collapsed', () => { it('has class is-collapsed when list is collapsed', () => {
createComponent({ collapsed: false }); createComponent({ collapsed: false });
expect(isCollapsed()).toBe(false); expect(wrapper.vm.list.isExpanded).toBe(true);
}); });
it('does not have class is-collapsed when list is expanded', () => { it('does not have class is-collapsed when list is expanded', () => {
......
import Vue from 'vue';
import { shallowMount } from '@vue/test-utils'; import { shallowMount } from '@vue/test-utils';
import AxiosMockAdapter from 'axios-mock-adapter';
import { TEST_HOST } from 'helpers/test_constants';
import { listObj } from 'jest/boards/mock_data'; import { listObj } from 'jest/boards/mock_data';
import Board from '~/boards/components/board_column.vue'; import BoardColumn from '~/boards/components/board_column.vue';
import List from '~/boards/models/list';
import { ListType } from '~/boards/constants'; import { ListType } from '~/boards/constants';
import axios from '~/lib/utils/axios_utils'; import { createStore } from '~/boards/stores';
describe('Board Column Component', () => { describe('Board Column Component', () => {
let wrapper; let wrapper;
let axiosMock; let store;
beforeEach(() => {
window.gon = {};
axiosMock = new AxiosMockAdapter(axios);
axiosMock.onGet(`${TEST_HOST}/lists/1/issues`).reply(200, { issues: [] });
});
afterEach(() => { afterEach(() => {
axiosMock.restore();
wrapper.destroy(); wrapper.destroy();
wrapper = null;
localStorage.clear();
}); });
const createComponent = ({ const createComponent = ({ listType = ListType.backlog, collapsed = false } = {}) => {
listType = ListType.backlog,
collapsed = false,
withLocalStorage = true,
} = {}) => {
const boardId = '1'; const boardId = '1';
const listMock = { const listMock = {
...listObj, ...listObj,
list_type: listType, listType,
collapsed, collapsed,
}; };
if (listType === ListType.assignee) { if (listType === ListType.assignee) {
delete listMock.label; delete listMock.label;
listMock.user = {}; listMock.assignee = {};
} }
// Making List reactive store = createStore();
const list = Vue.observable(new List(listMock));
if (withLocalStorage) { wrapper = shallowMount(BoardColumn, {
localStorage.setItem( store,
`boards.${boardId}.${list.type}.${list.id}.expanded`,
(!collapsed).toString(),
);
}
wrapper = shallowMount(Board, {
propsData: { propsData: {
boardId,
disabled: false, disabled: false,
list, list: listMock,
}, },
provide: { provide: {
boardId, boardId,
...@@ -82,7 +57,7 @@ describe('Board Column Component', () => { ...@@ -82,7 +57,7 @@ describe('Board Column Component', () => {
it('has class is-collapsed when list is collapsed', () => { it('has class is-collapsed when list is collapsed', () => {
createComponent({ collapsed: false }); createComponent({ collapsed: false });
expect(wrapper.vm.list.isExpanded).toBe(true); expect(isCollapsed()).toBe(false);
}); });
it('does not have class is-collapsed when list is expanded', () => { it('does not have class is-collapsed when list is expanded', () => {
......
...@@ -4,7 +4,7 @@ import { GlAlert } from '@gitlab/ui'; ...@@ -4,7 +4,7 @@ import { GlAlert } from '@gitlab/ui';
import Draggable from 'vuedraggable'; import Draggable from 'vuedraggable';
import EpicsSwimlanes from 'ee_component/boards/components/epics_swimlanes.vue'; import EpicsSwimlanes from 'ee_component/boards/components/epics_swimlanes.vue';
import getters from 'ee_else_ce/boards/stores/getters'; import getters from 'ee_else_ce/boards/stores/getters';
import BoardColumn from '~/boards/components/board_column.vue'; import BoardColumnDeprecated from '~/boards/components/board_column_deprecated.vue';
import { mockLists, mockListsWithModel } from '../mock_data'; import { mockLists, mockListsWithModel } from '../mock_data';
import BoardContent from '~/boards/components/board_content.vue'; import BoardContent from '~/boards/components/board_content.vue';
...@@ -17,6 +17,7 @@ const actions = { ...@@ -17,6 +17,7 @@ const actions = {
describe('BoardContent', () => { describe('BoardContent', () => {
let wrapper; let wrapper;
window.gon = {};
const defaultState = { const defaultState = {
isShowingEpicsSwimlanes: false, isShowingEpicsSwimlanes: false,
...@@ -56,10 +57,12 @@ describe('BoardContent', () => { ...@@ -56,10 +57,12 @@ describe('BoardContent', () => {
wrapper.destroy(); wrapper.destroy();
}); });
it('renders a BoardColumn component per list', () => { it('renders a BoardColumnDeprecated component per list', () => {
createComponent(); createComponent();
expect(wrapper.findAll(BoardColumn)).toHaveLength(mockLists.length); expect(wrapper.findAllComponents(BoardColumnDeprecated)).toHaveLength(
mockListsWithModel.length,
);
}); });
it('does not display EpicsSwimlanes component', () => { it('does not display EpicsSwimlanes component', () => {
...@@ -70,6 +73,13 @@ describe('BoardContent', () => { ...@@ -70,6 +73,13 @@ describe('BoardContent', () => {
}); });
describe('graphqlBoardLists feature flag enabled', () => { describe('graphqlBoardLists feature flag enabled', () => {
beforeEach(() => {
createComponent({ graphqlBoardListsEnabled: true });
gon.features = {
graphqlBoardLists: true,
};
});
describe('can admin list', () => { describe('can admin list', () => {
beforeEach(() => { beforeEach(() => {
createComponent({ graphqlBoardListsEnabled: true, props: { canAdminList: true } }); createComponent({ graphqlBoardListsEnabled: true, props: { canAdminList: true } });
...@@ -85,7 +95,7 @@ describe('BoardContent', () => { ...@@ -85,7 +95,7 @@ describe('BoardContent', () => {
createComponent({ graphqlBoardListsEnabled: true, props: { canAdminList: false } }); createComponent({ graphqlBoardListsEnabled: true, props: { canAdminList: false } });
}); });
it('renders draggable component', () => { it('does not render draggable component', () => {
expect(wrapper.find(Draggable).exists()).toBe(false); expect(wrapper.find(Draggable).exists()).toBe(false);
}); });
}); });
......
import Vuex from 'vuex'; import Vue from 'vue';
import { shallowMount, createLocalVue } from '@vue/test-utils'; import { shallowMount } from '@vue/test-utils';
import AxiosMockAdapter from 'axios-mock-adapter';
import { mockLabelList } from 'jest/boards/mock_data';
import BoardListHeader from '~/boards/components/board_list_header_new.vue'; import { TEST_HOST } from 'helpers/test_constants';
import { listObj } from 'jest/boards/mock_data';
import BoardListHeader from '~/boards/components/board_list_header_deprecated.vue';
import List from '~/boards/models/list';
import { ListType } from '~/boards/constants'; import { ListType } from '~/boards/constants';
import axios from '~/lib/utils/axios_utils';
const localVue = createLocalVue();
localVue.use(Vuex);
describe('Board List Header Component', () => { describe('Board List Header Component', () => {
let wrapper; let wrapper;
let store; let axiosMock;
const updateListSpy = jest.fn(); beforeEach(() => {
window.gon = {};
axiosMock = new AxiosMockAdapter(axios);
axiosMock.onGet(`${TEST_HOST}/lists/1/issues`).reply(200, { issues: [] });
});
afterEach(() => { afterEach(() => {
axiosMock.restore();
wrapper.destroy(); wrapper.destroy();
wrapper = null;
localStorage.clear(); localStorage.clear();
}); });
...@@ -26,54 +31,45 @@ describe('Board List Header Component', () => { ...@@ -26,54 +31,45 @@ describe('Board List Header Component', () => {
listType = ListType.backlog, listType = ListType.backlog,
collapsed = false, collapsed = false,
withLocalStorage = true, withLocalStorage = true,
currentUserId = null,
} = {}) => { } = {}) => {
const boardId = '1'; const boardId = '1';
const listMock = { const listMock = {
...mockLabelList, ...listObj,
listType, list_type: listType,
collapsed, collapsed,
}; };
if (listType === ListType.assignee) { if (listType === ListType.assignee) {
delete listMock.label; delete listMock.label;
listMock.assignee = {}; listMock.user = {};
} }
// Making List reactive
const list = Vue.observable(new List(listMock));
if (withLocalStorage) { if (withLocalStorage) {
localStorage.setItem( localStorage.setItem(
`boards.${boardId}.${listMock.listType}.${listMock.id}.expanded`, `boards.${boardId}.${list.type}.${list.id}.expanded`,
(!collapsed).toString(), (!collapsed).toString(),
); );
} }
store = new Vuex.Store({
state: {},
actions: { updateList: updateListSpy },
getters: {},
});
wrapper = shallowMount(BoardListHeader, { wrapper = shallowMount(BoardListHeader, {
store,
localVue,
propsData: { propsData: {
disabled: false, disabled: false,
list: listMock, list,
}, },
provide: { provide: {
boardId, boardId,
weightFeatureAvailable: false,
currentUserId,
}, },
}); });
}; };
const isCollapsed = () => wrapper.vm.list.collapsed; const isCollapsed = () => !wrapper.props().list.isExpanded;
const isExpanded = () => !isCollapsed; const isExpanded = () => wrapper.vm.list.isExpanded;
const findAddIssueButton = () => wrapper.find({ ref: 'newIssueBtn' }); const findAddIssueButton = () => wrapper.find({ ref: 'newIssueBtn' });
const findTitle = () => wrapper.find('.board-title');
const findCaret = () => wrapper.find('.board-title-caret'); const findCaret = () => wrapper.find('.board-title-caret');
describe('Add issue button', () => { describe('Add issue button', () => {
...@@ -93,8 +89,6 @@ describe('Board List Header Component', () => { ...@@ -93,8 +89,6 @@ describe('Board List Header Component', () => {
}); });
it('has a test for each list type', () => { it('has a test for each list type', () => {
createComponent();
Object.values(ListType).forEach((value) => { Object.values(ListType).forEach((value) => {
expect([...hasAddButton, ...hasNoAddButton]).toContain(value); expect([...hasAddButton, ...hasNoAddButton]).toContain(value);
}); });
...@@ -108,80 +102,64 @@ describe('Board List Header Component', () => { ...@@ -108,80 +102,64 @@ describe('Board List Header Component', () => {
}); });
describe('expanding / collapsing the column', () => { describe('expanding / collapsing the column', () => {
it('does not collapse when clicking the header', async () => { it('does not collapse when clicking the header', () => {
createComponent(); createComponent();
expect(isCollapsed()).toBe(false); expect(isCollapsed()).toBe(false);
wrapper.find('[data-testid="board-list-header"]').trigger('click'); wrapper.find('[data-testid="board-list-header"]').trigger('click');
await wrapper.vm.$nextTick(); return wrapper.vm.$nextTick().then(() => {
expect(isCollapsed()).toBe(false);
expect(isCollapsed()).toBe(false); });
}); });
it('collapses expanded Column when clicking the collapse icon', async () => { it('collapses expanded Column when clicking the collapse icon', () => {
createComponent(); createComponent();
expect(isCollapsed()).toBe(false); expect(isExpanded()).toBe(true);
findCaret().vm.$emit('click'); findCaret().vm.$emit('click');
await wrapper.vm.$nextTick(); return wrapper.vm.$nextTick().then(() => {
expect(isCollapsed()).toBe(true);
expect(isCollapsed()).toBe(true); });
}); });
it('expands collapsed Column when clicking the expand icon', async () => { it('expands collapsed Column when clicking the expand icon', () => {
createComponent({ collapsed: true }); createComponent({ collapsed: true });
expect(isCollapsed()).toBe(true); expect(isCollapsed()).toBe(true);
findCaret().vm.$emit('click'); findCaret().vm.$emit('click');
await wrapper.vm.$nextTick(); return wrapper.vm.$nextTick().then(() => {
expect(isCollapsed()).toBe(false);
expect(isCollapsed()).toBe(false); });
}); });
it("when logged in it calls list update and doesn't set localStorage", async () => { it("when logged in it calls list update and doesn't set localStorage", () => {
createComponent({ withLocalStorage: false, currentUserId: 1 }); jest.spyOn(List.prototype, 'update');
window.gon.current_user_id = 1;
findCaret().vm.$emit('click');
await wrapper.vm.$nextTick();
expect(updateListSpy).toHaveBeenCalledTimes(1);
expect(localStorage.getItem(`${wrapper.vm.uniqueKey}.expanded`)).toBe(null);
});
it("when logged out it doesn't call list update and sets localStorage", async () => { createComponent({ withLocalStorage: false });
createComponent();
findCaret().vm.$emit('click'); findCaret().vm.$emit('click');
await wrapper.vm.$nextTick();
expect(updateListSpy).not.toHaveBeenCalled(); return wrapper.vm.$nextTick().then(() => {
expect(localStorage.getItem(`${wrapper.vm.uniqueKey}.expanded`)).toBe(String(isExpanded())); expect(wrapper.vm.list.update).toHaveBeenCalledTimes(1);
expect(localStorage.getItem(`${wrapper.vm.uniqueKey}.expanded`)).toBe(null);
});
}); });
});
describe('user can drag', () => { it("when logged out it doesn't call list update and sets localStorage", () => {
const cannotDragList = [ListType.backlog, ListType.closed]; jest.spyOn(List.prototype, 'update');
const canDragList = [ListType.label, ListType.milestone, ListType.assignee];
it.each(cannotDragList)( createComponent();
'does not have user-can-drag-class so user cannot drag list',
(listType) => {
createComponent({ listType });
expect(findTitle().classes()).not.toContain('user-can-drag');
},
);
it.each(canDragList)('has user-can-drag-class so user can drag list', (listType) => { findCaret().vm.$emit('click');
createComponent({ listType });
expect(findTitle().classes()).toContain('user-can-drag'); return wrapper.vm.$nextTick().then(() => {
expect(wrapper.vm.list.update).not.toHaveBeenCalled();
expect(localStorage.getItem(`${wrapper.vm.uniqueKey}.expanded`)).toBe(String(isExpanded()));
});
}); });
}); });
}); });
import Vue from 'vue'; import Vuex from 'vuex';
import { shallowMount } from '@vue/test-utils'; import { shallowMount, createLocalVue } from '@vue/test-utils';
import AxiosMockAdapter from 'axios-mock-adapter';
import { TEST_HOST } from 'helpers/test_constants'; import { mockLabelList } from 'jest/boards/mock_data';
import { listObj } from 'jest/boards/mock_data';
import BoardListHeader from '~/boards/components/board_list_header.vue'; import BoardListHeader from '~/boards/components/board_list_header.vue';
import List from '~/boards/models/list';
import { ListType } from '~/boards/constants'; import { ListType } from '~/boards/constants';
import axios from '~/lib/utils/axios_utils';
const localVue = createLocalVue();
localVue.use(Vuex);
describe('Board List Header Component', () => { describe('Board List Header Component', () => {
let wrapper; let wrapper;
let axiosMock; let store;
beforeEach(() => { const updateListSpy = jest.fn();
window.gon = {};
axiosMock = new AxiosMockAdapter(axios);
axiosMock.onGet(`${TEST_HOST}/lists/1/issues`).reply(200, { issues: [] });
});
afterEach(() => { afterEach(() => {
axiosMock.restore();
wrapper.destroy(); wrapper.destroy();
wrapper = null;
localStorage.clear(); localStorage.clear();
}); });
...@@ -31,45 +26,54 @@ describe('Board List Header Component', () => { ...@@ -31,45 +26,54 @@ describe('Board List Header Component', () => {
listType = ListType.backlog, listType = ListType.backlog,
collapsed = false, collapsed = false,
withLocalStorage = true, withLocalStorage = true,
currentUserId = null,
} = {}) => { } = {}) => {
const boardId = '1'; const boardId = '1';
const listMock = { const listMock = {
...listObj, ...mockLabelList,
list_type: listType, listType,
collapsed, collapsed,
}; };
if (listType === ListType.assignee) { if (listType === ListType.assignee) {
delete listMock.label; delete listMock.label;
listMock.user = {}; listMock.assignee = {};
} }
// Making List reactive
const list = Vue.observable(new List(listMock));
if (withLocalStorage) { if (withLocalStorage) {
localStorage.setItem( localStorage.setItem(
`boards.${boardId}.${list.type}.${list.id}.expanded`, `boards.${boardId}.${listMock.listType}.${listMock.id}.expanded`,
(!collapsed).toString(), (!collapsed).toString(),
); );
} }
store = new Vuex.Store({
state: {},
actions: { updateList: updateListSpy },
getters: {},
});
wrapper = shallowMount(BoardListHeader, { wrapper = shallowMount(BoardListHeader, {
store,
localVue,
propsData: { propsData: {
disabled: false, disabled: false,
list, list: listMock,
}, },
provide: { provide: {
boardId, boardId,
weightFeatureAvailable: false,
currentUserId,
}, },
}); });
}; };
const isCollapsed = () => !wrapper.props().list.isExpanded; const isCollapsed = () => wrapper.vm.list.collapsed;
const isExpanded = () => wrapper.vm.list.isExpanded; const isExpanded = () => !isCollapsed;
const findAddIssueButton = () => wrapper.find({ ref: 'newIssueBtn' }); const findAddIssueButton = () => wrapper.find({ ref: 'newIssueBtn' });
const findTitle = () => wrapper.find('.board-title');
const findCaret = () => wrapper.find('.board-title-caret'); const findCaret = () => wrapper.find('.board-title-caret');
describe('Add issue button', () => { describe('Add issue button', () => {
...@@ -89,6 +93,8 @@ describe('Board List Header Component', () => { ...@@ -89,6 +93,8 @@ describe('Board List Header Component', () => {
}); });
it('has a test for each list type', () => { it('has a test for each list type', () => {
createComponent();
Object.values(ListType).forEach((value) => { Object.values(ListType).forEach((value) => {
expect([...hasAddButton, ...hasNoAddButton]).toContain(value); expect([...hasAddButton, ...hasNoAddButton]).toContain(value);
}); });
...@@ -102,64 +108,80 @@ describe('Board List Header Component', () => { ...@@ -102,64 +108,80 @@ describe('Board List Header Component', () => {
}); });
describe('expanding / collapsing the column', () => { describe('expanding / collapsing the column', () => {
it('does not collapse when clicking the header', () => { it('does not collapse when clicking the header', async () => {
createComponent(); createComponent();
expect(isCollapsed()).toBe(false); expect(isCollapsed()).toBe(false);
wrapper.find('[data-testid="board-list-header"]').trigger('click'); wrapper.find('[data-testid="board-list-header"]').trigger('click');
return wrapper.vm.$nextTick().then(() => { await wrapper.vm.$nextTick();
expect(isCollapsed()).toBe(false);
}); expect(isCollapsed()).toBe(false);
}); });
it('collapses expanded Column when clicking the collapse icon', () => { it('collapses expanded Column when clicking the collapse icon', async () => {
createComponent(); createComponent();
expect(isExpanded()).toBe(true); expect(isCollapsed()).toBe(false);
findCaret().vm.$emit('click'); findCaret().vm.$emit('click');
return wrapper.vm.$nextTick().then(() => { await wrapper.vm.$nextTick();
expect(isCollapsed()).toBe(true);
}); expect(isCollapsed()).toBe(true);
}); });
it('expands collapsed Column when clicking the expand icon', () => { it('expands collapsed Column when clicking the expand icon', async () => {
createComponent({ collapsed: true }); createComponent({ collapsed: true });
expect(isCollapsed()).toBe(true); expect(isCollapsed()).toBe(true);
findCaret().vm.$emit('click'); findCaret().vm.$emit('click');
return wrapper.vm.$nextTick().then(() => { await wrapper.vm.$nextTick();
expect(isCollapsed()).toBe(false);
});
});
it("when logged in it calls list update and doesn't set localStorage", () => { expect(isCollapsed()).toBe(false);
jest.spyOn(List.prototype, 'update'); });
window.gon.current_user_id = 1;
createComponent({ withLocalStorage: false }); it("when logged in it calls list update and doesn't set localStorage", async () => {
createComponent({ withLocalStorage: false, currentUserId: 1 });
findCaret().vm.$emit('click'); findCaret().vm.$emit('click');
await wrapper.vm.$nextTick();
return wrapper.vm.$nextTick().then(() => { expect(updateListSpy).toHaveBeenCalledTimes(1);
expect(wrapper.vm.list.update).toHaveBeenCalledTimes(1); expect(localStorage.getItem(`${wrapper.vm.uniqueKey}.expanded`)).toBe(null);
expect(localStorage.getItem(`${wrapper.vm.uniqueKey}.expanded`)).toBe(null);
});
}); });
it("when logged out it doesn't call list update and sets localStorage", () => { it("when logged out it doesn't call list update and sets localStorage", async () => {
jest.spyOn(List.prototype, 'update');
createComponent(); createComponent();
findCaret().vm.$emit('click'); findCaret().vm.$emit('click');
await wrapper.vm.$nextTick();
return wrapper.vm.$nextTick().then(() => { expect(updateListSpy).not.toHaveBeenCalled();
expect(wrapper.vm.list.update).not.toHaveBeenCalled(); expect(localStorage.getItem(`${wrapper.vm.uniqueKey}.expanded`)).toBe(String(isExpanded()));
expect(localStorage.getItem(`${wrapper.vm.uniqueKey}.expanded`)).toBe(String(isExpanded())); });
}); });
describe('user can drag', () => {
const cannotDragList = [ListType.backlog, ListType.closed];
const canDragList = [ListType.label, ListType.milestone, ListType.assignee];
it.each(cannotDragList)(
'does not have user-can-drag-class so user cannot drag list',
(listType) => {
createComponent({ listType });
expect(findTitle().classes()).not.toContain('user-can-drag');
},
);
it.each(canDragList)('has user-can-drag-class so user can drag list', (listType) => {
createComponent({ listType });
expect(findTitle().classes()).toContain('user-can-drag');
}); });
}); });
}); });
import Vuex from 'vuex'; import Vuex from 'vuex';
import { shallowMount, createLocalVue } from '@vue/test-utils'; import { shallowMount, createLocalVue } from '@vue/test-utils';
import BoardNewIssue from '~/boards/components/board_new_issue_new.vue'; import BoardNewIssue from '~/boards/components/board_new_issue.vue';
import '~/boards/models/list'; import '~/boards/models/list';
import { mockList, mockGroupProjects } from '../mock_data'; import { mockList, mockGroupProjects } from '../mock_data';
......
...@@ -285,7 +285,7 @@ export const setMockEndpoints = (opts = {}) => { ...@@ -285,7 +285,7 @@ export const setMockEndpoints = (opts = {}) => {
export const mockList = { export const mockList = {
id: 'gid://gitlab/List/1', id: 'gid://gitlab/List/1',
title: 'Backlog', title: 'Backlog',
position: null, position: -Infinity,
listType: 'backlog', listType: 'backlog',
collapsed: false, collapsed: false,
label: null, label: null,
......
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