Welcome to mirror list, hosted at ThFree Co, Russian Federation.

milestone_token_spec.js « tokens « filtered_search_bar « components « vue_shared « frontend « spec - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 36e82b39df4335b8a5bb2a55c099ca01a77ba8c3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import {
  GlFilteredSearchToken,
  GlFilteredSearchSuggestion,
  GlFilteredSearchTokenSegment,
  GlDropdownDivider,
} from '@gitlab/ui';
import { mount } from '@vue/test-utils';
import MockAdapter from 'axios-mock-adapter';
import Vue, { nextTick } from 'vue';
import VueApollo from 'vue-apollo';
import createMockApollo from 'helpers/mock_apollo_helper';
import waitForPromises from 'helpers/wait_for_promises';
import { createAlert } from '~/alert';
import axios from '~/lib/utils/axios_utils';
import { sortMilestonesByDueDate } from '~/milestones/utils';

import searchMilestonesQuery from '~/issues/list/queries/search_milestones.query.graphql';
import { DEFAULT_MILESTONES } from '~/vue_shared/components/filtered_search_bar/constants';
import MilestoneToken from '~/vue_shared/components/filtered_search_bar/tokens/milestone_token.vue';
import BaseToken from '~/vue_shared/components/filtered_search_bar/tokens/base_token.vue';

import {
  mockMilestoneToken,
  mockMilestones,
  mockRegularMilestone,
  projectMilestonesResponse,
} from '../mock_data';

Vue.use(VueApollo);

jest.mock('~/alert');
jest.mock('~/milestones/utils');

const defaultStubs = {
  Portal: true,
  GlFilteredSearchSuggestionList: {
    template: '<div></div>',
    methods: {
      getValue: () => '=',
    },
  },
};

const milestonesQueryHandler = jest.fn().mockResolvedValue(projectMilestonesResponse);
const mockApollo = createMockApollo([[searchMilestonesQuery, milestonesQueryHandler]]);

function createComponent(options = {}) {
  const {
    config = { ...mockMilestoneToken, shouldSkipSort: true },
    value = { data: '' },
    active = false,
    stubs = defaultStubs,
  } = options;
  return mount(MilestoneToken, {
    apolloProvider: mockApollo,
    propsData: {
      config,
      value,
      active,
      cursorPosition: 'start',
    },
    provide: {
      portalName: 'fake target',
      alignSuggestions: function fakeAlignSuggestions() {},
      suggestionsListClass: () => 'custom-class',
      termsAsTokens: () => false,
    },
    stubs,
  });
}

describe('MilestoneToken', () => {
  let mock;
  let wrapper;

  const findBaseToken = () => wrapper.findComponent(BaseToken);
  const triggerFetchMilestones = (searchTerm = null) => {
    findBaseToken().vm.$emit('fetch-suggestions', searchTerm);
    return waitForPromises();
  };

  beforeEach(() => {
    mock = new MockAdapter(axios);
    wrapper = createComponent();
  });

  afterEach(() => {
    mock.restore();
  });

  describe('methods', () => {
    describe('fetchMilestones', () => {
      it('sets loading state', async () => {
        wrapper = createComponent({
          config: {
            fetchMilestones: jest.fn().mockResolvedValue(new Promise(() => {})),
          },
        });
        await nextTick();

        expect(findBaseToken().props('suggestionsLoading')).toBe(true);
      });

      describe('when config.shouldSkipSort is true', () => {
        it('does not call sortMilestonesByDueDate', async () => {
          wrapper = createComponent({
            config: {
              shouldSkipSort: true,
              fetchMilestones: jest.fn().mockResolvedValue({ data: mockMilestones }),
            },
          });

          await triggerFetchMilestones();

          expect(sortMilestonesByDueDate).toHaveBeenCalledTimes(0);
        });
      });

      describe('default - when fetchMilestones function is not provided in config', () => {
        beforeEach(() => {
          wrapper = createComponent({});
          return triggerFetchMilestones();
        });

        it('calls searchMilestonesQuery to fetch milestones', () => {
          expect(milestonesQueryHandler).toHaveBeenCalledWith({
            fullPath: mockMilestoneToken.fullPath,
            isProject: mockMilestoneToken.isProject,
            search: null,
          });
        });

        it('calls searchMilestonesQuery with search parameter when provided', async () => {
          const searchTerm = 'foo';

          await triggerFetchMilestones(searchTerm);

          expect(milestonesQueryHandler).toHaveBeenCalledWith({
            fullPath: mockMilestoneToken.fullPath,
            isProject: mockMilestoneToken.isProject,
            search: searchTerm,
          });
        });
      });

      describe('when request is successful', () => {
        const searchTerm = 'foo';

        beforeEach(() => {
          wrapper = createComponent({
            config: {
              shouldSkipSort: false,
              fetchMilestones: jest.fn().mockResolvedValue({ data: mockMilestones }),
            },
          });
          return triggerFetchMilestones(searchTerm);
        });

        it('calls `config.fetchMilestones` with provided searchTerm param', () => {
          expect(findBaseToken().props('config').fetchMilestones).toHaveBeenCalledWith(searchTerm);
        });

        it('sets response to `milestones`', () => {
          expect(sortMilestonesByDueDate).toHaveBeenCalled();
          expect(findBaseToken().props('suggestions')).toEqual(mockMilestones);
        });
      });

      describe('when request fails', () => {
        beforeEach(() => {
          wrapper = createComponent({
            config: {
              fetchMilestones: jest.fn().mockRejectedValue({}),
            },
          });
          return triggerFetchMilestones();
        });

        it('calls `createAlert`', () => {
          expect(createAlert).toHaveBeenCalledWith({
            message: 'There was a problem fetching milestones.',
          });
        });

        it('sets `loading` to false when request completes', () => {
          expect(findBaseToken().props('suggestionsLoading')).toBe(false);
        });
      });
    });
  });

  describe('template', () => {
    const defaultMilestones = [
      { text: 'foo', value: 'foo' },
      { text: 'bar', value: 'baz' },
    ];

    beforeEach(() => {
      wrapper = createComponent({
        value: { data: `"${mockRegularMilestone.title}"` },
        config: {
          initialMilestones: mockMilestones,
        },
      });
    });

    it('renders gl-filtered-search-token component', () => {
      expect(wrapper.findComponent(GlFilteredSearchToken).exists()).toBe(true);
    });

    it('renders token item when value is selected', () => {
      const tokenSegments = wrapper.findAllComponents(GlFilteredSearchTokenSegment);

      expect(tokenSegments).toHaveLength(3); // Milestone, =, '%"4.0"'
      expect(tokenSegments.at(2).text()).toBe(`%${mockRegularMilestone.title}`); // "4.0 RC1"
    });

    it('renders provided defaultMilestones as suggestions', async () => {
      wrapper = createComponent({
        active: true,
        config: { ...mockMilestoneToken, defaultMilestones },
        stubs: { Portal: true },
      });
      const tokenSegments = wrapper.findAllComponents(GlFilteredSearchTokenSegment);
      const suggestionsSegment = tokenSegments.at(2);
      suggestionsSegment.vm.$emit('activate');
      await nextTick();

      const suggestions = wrapper.findAllComponents(GlFilteredSearchSuggestion);

      expect(suggestions).toHaveLength(defaultMilestones.length);
      defaultMilestones.forEach((milestone, index) => {
        expect(suggestions.at(index).text()).toBe(milestone.text);
      });
    });

    it('does not render divider when no defaultMilestones', async () => {
      wrapper = createComponent({
        active: true,
        config: { ...mockMilestoneToken, defaultMilestones: [] },
        stubs: { Portal: true },
      });
      const tokenSegments = wrapper.findAllComponents(GlFilteredSearchTokenSegment);
      const suggestionsSegment = tokenSegments.at(2);
      suggestionsSegment.vm.$emit('activate');
      await nextTick();

      expect(wrapper.findComponent(GlFilteredSearchSuggestion).exists()).toBe(false);
      expect(wrapper.findComponent(GlDropdownDivider).exists()).toBe(false);
    });

    it('renders `DEFAULT_MILESTONES` as default suggestions', async () => {
      wrapper = createComponent({
        active: true,
        config: { ...mockMilestoneToken },
        stubs: { Portal: true },
      });
      const tokenSegments = wrapper.findAllComponents(GlFilteredSearchTokenSegment);
      const suggestionsSegment = tokenSegments.at(2);
      suggestionsSegment.vm.$emit('activate');
      await nextTick();

      const suggestions = wrapper.findAllComponents(GlFilteredSearchSuggestion);

      expect(suggestions).toHaveLength(DEFAULT_MILESTONES.length);
      DEFAULT_MILESTONES.forEach((milestone, index) => {
        expect(suggestions.at(index).text()).toBe(milestone.text);
      });
    });

    describe('when getActiveMilestones is called and milestones is empty', () => {
      beforeEach(() => {
        wrapper = createComponent({
          active: true,
          config: { ...mockMilestoneToken, defaultMilestones: DEFAULT_MILESTONES },
        });
      });

      it('finds the correct value from the activeToken', () => {
        DEFAULT_MILESTONES.forEach(({ value, title }) => {
          const activeToken = findBaseToken().props('getActiveTokenValue')([], value);

          expect(activeToken.title).toEqual(title);
        });
      });
    });
  });
});