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

pipeline_schedules_form_spec.js « components « pipeline_schedules « ci « frontend « spec - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: bb48d4dc38dcc18f6e72af6c896ab4a6cb0f4507 (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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
import MockAdapter from 'axios-mock-adapter';
import { GlForm, GlLoadingIcon } from '@gitlab/ui';
import Vue, { nextTick } from 'vue';
import VueApollo from 'vue-apollo';
import createMockApollo from 'helpers/mock_apollo_helper';
import { shallowMountExtended, mountExtended } from 'helpers/vue_test_utils_helper';
import waitForPromises from 'helpers/wait_for_promises';
import axios from '~/lib/utils/axios_utils';
import { visitUrl } from '~/lib/utils/url_utility';
import { createAlert } from '~/alert';
import PipelineSchedulesForm from '~/ci/pipeline_schedules/components/pipeline_schedules_form.vue';
import RefSelector from '~/ref/components/ref_selector.vue';
import { REF_TYPE_BRANCHES, REF_TYPE_TAGS } from '~/ref/constants';
import TimezoneDropdown from '~/vue_shared/components/timezone_dropdown/timezone_dropdown.vue';
import IntervalPatternInput from '~/pages/projects/pipeline_schedules/shared/components/interval_pattern_input.vue';
import createPipelineScheduleMutation from '~/ci/pipeline_schedules/graphql/mutations/create_pipeline_schedule.mutation.graphql';
import updatePipelineScheduleMutation from '~/ci/pipeline_schedules/graphql/mutations/update_pipeline_schedule.mutation.graphql';
import getPipelineSchedulesQuery from '~/ci/pipeline_schedules/graphql/queries/get_pipeline_schedules.query.graphql';
import { timezoneDataFixture } from '../../../vue_shared/components/timezone_dropdown/helpers';
import {
  createScheduleMutationResponse,
  updateScheduleMutationResponse,
  mockSinglePipelineScheduleNode,
} from '../mock_data';

Vue.use(VueApollo);

jest.mock('~/alert');
jest.mock('~/lib/utils/url_utility', () => ({
  visitUrl: jest.fn(),
  joinPaths: jest.fn().mockReturnValue(''),
  queryToObject: jest.fn().mockReturnValue({ id: '1' }),
}));

const {
  data: {
    project: {
      pipelineSchedules: { nodes },
    },
  },
} = mockSinglePipelineScheduleNode;

const schedule = nodes[0];
const variables = schedule.variables.nodes;

describe('Pipeline schedules form', () => {
  let wrapper;
  const defaultBranch = 'main';
  const projectId = '1';
  const cron = '';
  const dailyLimit = '';

  const querySuccessHandler = jest.fn().mockResolvedValue(mockSinglePipelineScheduleNode);
  const queryFailedHandler = jest.fn().mockRejectedValue(new Error('GraphQL error'));

  const createMutationHandlerSuccess = jest.fn().mockResolvedValue(createScheduleMutationResponse);
  const createMutationHandlerFailed = jest.fn().mockRejectedValue(new Error('GraphQL error'));
  const updateMutationHandlerSuccess = jest.fn().mockResolvedValue(updateScheduleMutationResponse);
  const updateMutationHandlerFailed = jest.fn().mockRejectedValue(new Error('GraphQL error'));

  const createMockApolloProvider = (
    requestHandlers = [[createPipelineScheduleMutation, createMutationHandlerSuccess]],
  ) => {
    return createMockApollo(requestHandlers);
  };

  const createComponent = (mountFn = shallowMountExtended, editing = false, requestHandlers) => {
    wrapper = mountFn(PipelineSchedulesForm, {
      propsData: {
        timezoneData: timezoneDataFixture,
        refParam: 'master',
        editing,
      },
      provide: {
        fullPath: 'gitlab-org/gitlab',
        projectId,
        defaultBranch,
        dailyLimit,
        settingsLink: '',
        schedulesPath: '/root/ci-project/-/pipeline_schedules',
      },
      apolloProvider: createMockApolloProvider(requestHandlers),
    });
  };

  const findForm = () => wrapper.findComponent(GlForm);
  const findDescription = () => wrapper.findByTestId('schedule-description');
  const findIntervalComponent = () => wrapper.findComponent(IntervalPatternInput);
  const findTimezoneDropdown = () => wrapper.findComponent(TimezoneDropdown);
  const findRefSelector = () => wrapper.findComponent(RefSelector);
  const findSubmitButton = () => wrapper.findByTestId('schedule-submit-button');
  const findCancelButton = () => wrapper.findByTestId('schedule-cancel-button');
  const findLoadingIcon = () => wrapper.findComponent(GlLoadingIcon);
  // Variables
  const findVariableRows = () => wrapper.findAllByTestId('ci-variable-row');
  const findKeyInputs = () => wrapper.findAllByTestId('pipeline-form-ci-variable-key');
  const findValueInputs = () => wrapper.findAllByTestId('pipeline-form-ci-variable-value');
  const findRemoveIcons = () => wrapper.findAllByTestId('remove-ci-variable-row');

  const addVariableToForm = () => {
    const input = findKeyInputs().at(0);
    input.element.value = 'test_var_2';
    input.trigger('change');
  };

  describe('Form elements', () => {
    beforeEach(() => {
      createComponent();
    });

    it('displays form', () => {
      expect(findForm().exists()).toBe(true);
    });

    it('displays the description input', () => {
      expect(findDescription().exists()).toBe(true);
    });

    it('displays the interval pattern component', () => {
      const intervalPattern = findIntervalComponent();

      expect(intervalPattern.exists()).toBe(true);
      expect(intervalPattern.props()).toMatchObject({
        initialCronInterval: cron,
        dailyLimit,
        sendNativeErrors: false,
      });
    });

    it('displays the Timezone dropdown', () => {
      const timezoneDropdown = findTimezoneDropdown();

      expect(timezoneDropdown.exists()).toBe(true);
      expect(timezoneDropdown.props()).toMatchObject({
        value: '',
        name: 'schedule-timezone',
        timezoneData: timezoneDataFixture,
      });
    });

    it('displays the branch/tag selector', () => {
      const refSelector = findRefSelector();

      expect(refSelector.exists()).toBe(true);
      expect(refSelector.props()).toMatchObject({
        enabledRefTypes: [REF_TYPE_BRANCHES, REF_TYPE_TAGS],
        value: defaultBranch,
        projectId,
        translations: { dropdownHeader: 'Select target branch or tag' },
        useSymbolicRefNames: true,
        state: true,
        name: '',
      });
    });

    it('displays the submit and cancel buttons', () => {
      expect(findSubmitButton().exists()).toBe(true);
      expect(findCancelButton().exists()).toBe(true);
      expect(findCancelButton().attributes('href')).toBe('/root/ci-project/-/pipeline_schedules');
    });
  });

  describe('CI variables', () => {
    let mock;

    beforeEach(() => {
      // mock is needed when we fully mount
      // downstream components request needs to be mocked
      mock = new MockAdapter(axios);
      createComponent(mountExtended);
    });

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

    it('creates blank variable on input change event', async () => {
      expect(findVariableRows()).toHaveLength(1);

      addVariableToForm();

      await nextTick();

      expect(findVariableRows()).toHaveLength(2);
      expect(findKeyInputs().at(1).element.value).toBe('');
      expect(findValueInputs().at(1).element.value).toBe('');
    });

    it('does not display remove icon for last row', async () => {
      addVariableToForm();

      await nextTick();

      expect(findRemoveIcons()).toHaveLength(1);
    });

    it('removes ci variable row on remove icon button click', async () => {
      addVariableToForm();

      await nextTick();

      expect(findVariableRows()).toHaveLength(2);

      findRemoveIcons().at(0).trigger('click');

      await nextTick();

      expect(findVariableRows()).toHaveLength(1);
    });
  });

  describe('Button text', () => {
    it.each`
      editing  | expectedText
      ${true}  | ${'Edit pipeline schedule'}
      ${false} | ${'Create pipeline schedule'}
    `(
      'button text is $expectedText when editing is $editing',
      async ({ editing, expectedText }) => {
        createComponent(shallowMountExtended, editing, [
          [getPipelineSchedulesQuery, querySuccessHandler],
        ]);

        await waitForPromises();

        expect(findSubmitButton().text()).toBe(expectedText);
      },
    );
  });

  describe('Schedule creation', () => {
    it('when creating a schedule the query is not called', () => {
      createComponent();

      expect(querySuccessHandler).not.toHaveBeenCalled();
    });

    it('does not show loading state when creating new schedule', () => {
      createComponent();

      expect(findLoadingIcon().exists()).toBe(false);
    });

    describe('schedule creation success', () => {
      let mock;

      beforeEach(() => {
        // mock is needed when we fully mount
        // downstream components request needs to be mocked
        mock = new MockAdapter(axios);
        createComponent(mountExtended);
      });

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

      it('creates pipeline schedule', async () => {
        findDescription().element.value = 'My schedule';
        findDescription().trigger('change');

        findTimezoneDropdown().vm.$emit('input', {
          formattedTimezone: '[UTC-4] Eastern Time (US & Canada)',
          identifier: 'America/New_York',
        });

        findIntervalComponent().vm.$emit('cronValue', '0 16 * * *');

        addVariableToForm();

        findSubmitButton().vm.$emit('click');

        await waitForPromises();

        expect(createMutationHandlerSuccess).toHaveBeenCalledWith({
          input: {
            active: true,
            cron: '0 16 * * *',
            cronTimezone: 'America/New_York',
            description: 'My schedule',
            projectPath: 'gitlab-org/gitlab',
            ref: 'main',
            variables: [
              {
                key: 'test_var_2',
                value: '',
                variableType: 'ENV_VAR',
              },
            ],
          },
        });
        expect(visitUrl).toHaveBeenCalledWith('/root/ci-project/-/pipeline_schedules');
        expect(createAlert).not.toHaveBeenCalled();
      });
    });

    describe('schedule creation failure', () => {
      beforeEach(() => {
        createComponent(shallowMountExtended, false, [
          [createPipelineScheduleMutation, createMutationHandlerFailed],
        ]);
      });

      it('shows error for failed pipeline schedule creation', async () => {
        findSubmitButton().vm.$emit('click');

        await waitForPromises();

        expect(createAlert).toHaveBeenCalledWith({
          message: 'An error occurred while creating the pipeline schedule.',
        });
      });
    });
  });

  describe('Schedule editing', () => {
    let mock;

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

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

    it('shows loading state when editing', async () => {
      createComponent(shallowMountExtended, true, [
        [getPipelineSchedulesQuery, querySuccessHandler],
      ]);

      expect(findLoadingIcon().exists()).toBe(true);

      await waitForPromises();

      expect(findLoadingIcon().exists()).toBe(false);
    });

    describe('schedule fetch success', () => {
      it('fetches schedule and sets form data correctly', async () => {
        createComponent(mountExtended, true, [[getPipelineSchedulesQuery, querySuccessHandler]]);

        expect(querySuccessHandler).toHaveBeenCalled();

        await waitForPromises();

        expect(findDescription().element.value).toBe(schedule.description);
        expect(findIntervalComponent().props('initialCronInterval')).toBe(schedule.cron);
        expect(findTimezoneDropdown().props('value')).toBe(schedule.cronTimezone);
        expect(findRefSelector().props('value')).toBe(schedule.ref);
        expect(findVariableRows()).toHaveLength(3);
        expect(findKeyInputs().at(0).element.value).toBe(variables[0].key);
        expect(findKeyInputs().at(1).element.value).toBe(variables[1].key);
        expect(findValueInputs().at(0).element.value).toBe(variables[0].value);
        expect(findValueInputs().at(1).element.value).toBe(variables[1].value);
      });
    });

    it('schedule fetch failure', async () => {
      createComponent(shallowMountExtended, true, [
        [getPipelineSchedulesQuery, queryFailedHandler],
      ]);

      await waitForPromises();

      expect(createAlert).toHaveBeenCalledWith({
        message: 'An error occurred while trying to fetch the pipeline schedule.',
      });
    });

    it('edit schedule success', async () => {
      createComponent(mountExtended, true, [
        [getPipelineSchedulesQuery, querySuccessHandler],
        [updatePipelineScheduleMutation, updateMutationHandlerSuccess],
      ]);

      await waitForPromises();

      findDescription().element.value = 'Updated schedule';
      findDescription().trigger('change');

      findIntervalComponent().vm.$emit('cronValue', '0 22 16 * *');

      // Ensures variable is sent with destroy property set true
      findRemoveIcons().at(0).vm.$emit('click');

      findSubmitButton().vm.$emit('click');

      await waitForPromises();

      expect(updateMutationHandlerSuccess).toHaveBeenCalledWith({
        input: {
          active: schedule.active,
          cron: '0 22 16 * *',
          cronTimezone: schedule.cronTimezone,
          id: schedule.id,
          ref: schedule.ref,
          description: 'Updated schedule',
          variables: [
            {
              destroy: true,
              id: variables[0].id,
              key: variables[0].key,
              value: variables[0].value,
              variableType: variables[0].variableType,
            },
            {
              destroy: false,
              id: variables[1].id,
              key: variables[1].key,
              value: variables[1].value,
              variableType: variables[1].variableType,
            },
          ],
        },
      });
    });

    it('edit schedule failure', async () => {
      createComponent(shallowMountExtended, true, [
        [getPipelineSchedulesQuery, querySuccessHandler],
        [updatePipelineScheduleMutation, updateMutationHandlerFailed],
      ]);

      await waitForPromises();

      findSubmitButton().vm.$emit('click');

      await waitForPromises();

      expect(createAlert).toHaveBeenCalledWith({
        message: 'An error occurred while updating the pipeline schedule.',
      });
    });
  });
});