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

ci_variable_shared_spec.js « components « ci_variable_list « ci « frontend « spec - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 6fa1915f3c191d4a4f19a62cad79efb39cb41b9a (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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
import Vue from 'vue';
import VueApollo from 'vue-apollo';
import { GlLoadingIcon, GlTable } from '@gitlab/ui';
import { shallowMount } from '@vue/test-utils';
import { assertProps } from 'helpers/assert_props';
import createMockApollo from 'helpers/mock_apollo_helper';
import waitForPromises from 'helpers/wait_for_promises';
import { createAlert } from '~/alert';
import { resolvers } from '~/ci/ci_variable_list/graphql/settings';

import ciVariableShared from '~/ci/ci_variable_list/components/ci_variable_shared.vue';
import ciVariableSettings from '~/ci/ci_variable_list/components/ci_variable_settings.vue';
import ciVariableTable from '~/ci/ci_variable_list/components/ci_variable_table.vue';
import getProjectEnvironments from '~/ci/ci_variable_list/graphql/queries/project_environments.query.graphql';
import getAdminVariables from '~/ci/ci_variable_list/graphql/queries/variables.query.graphql';
import getGroupVariables from '~/ci/ci_variable_list/graphql/queries/group_variables.query.graphql';
import getProjectVariables from '~/ci/ci_variable_list/graphql/queries/project_variables.query.graphql';

import {
  ENVIRONMENT_QUERY_LIMIT,
  environmentFetchErrorText,
  genericMutationErrorText,
  variableFetchErrorText,
  mapMutationActionToToast,
} from '~/ci/ci_variable_list/constants';

import {
  createGroupProps,
  createInstanceProps,
  createProjectProps,
  createGroupProvide,
  createProjectProvide,
  devName,
  mockProjectEnvironments,
  mockProjectVariables,
  newVariable,
  prodName,
  mockGroupVariables,
  mockAdminVariables,
} from '../mocks';

jest.mock('~/alert');

Vue.use(VueApollo);

const mockProvide = {
  endpoint: '/variables',
  isGroup: false,
  isInheritedGroupVars: false,
  isProject: false,
};

const defaultProps = {
  areScopedVariablesAvailable: true,
  hasEnvScopeQuery: false,
  pageInfo: {},
  hideEnvironmentScope: false,
  refetchAfterMutation: false,
};

describe('Ci Variable Shared Component', () => {
  let wrapper;

  let mockApollo;
  let mockEnvironments;
  let mockMutation;
  let mockAddMutation;
  let mockUpdateMutation;
  let mockDeleteMutation;
  let mockVariables;

  const mockToastShow = jest.fn();

  const findLoadingIcon = () => wrapper.findComponent(GlLoadingIcon);
  const findCiTable = () => wrapper.findComponent(GlTable);
  const findCiSettings = () => wrapper.findComponent(ciVariableSettings);

  // eslint-disable-next-line consistent-return
  function createComponentWithApollo({
    customHandlers = null,
    customResolvers = null,
    isLoading = false,
    props = { ...createProjectProps() },
    provide = {},
  } = {}) {
    const handlers = customHandlers || [
      [getProjectEnvironments, mockEnvironments],
      [getProjectVariables, mockVariables],
    ];

    const mutationResolvers = customResolvers || resolvers;

    mockApollo = createMockApollo(handlers, mutationResolvers);

    wrapper = shallowMount(ciVariableShared, {
      propsData: {
        ...defaultProps,
        ...props,
      },
      provide: {
        ...mockProvide,
        ...provide,
      },
      apolloProvider: mockApollo,
      stubs: { ciVariableSettings, ciVariableTable },
      mocks: {
        $toast: {
          show: mockToastShow,
        },
      },
    });

    if (!isLoading) {
      return waitForPromises();
    }
  }

  beforeEach(() => {
    mockEnvironments = jest.fn();
    mockVariables = jest.fn();
    mockMutation = jest.fn();
    mockAddMutation = jest.fn();
    mockUpdateMutation = jest.fn();
    mockDeleteMutation = jest.fn();
  });

  describe.each`
    isVariablePagesEnabled | text
    ${true}                | ${'enabled'}
    ${false}               | ${'disabled'}
  `('When Pages FF is $text', ({ isVariablePagesEnabled }) => {
    const pagesFeatureFlagProvide = isVariablePagesEnabled
      ? { glFeatures: { ciVariablesPages: true } }
      : {};

    describe('while queries are being fetched', () => {
      beforeEach(() => {
        createComponentWithApollo({ isLoading: true });
      });

      it('shows a loading icon', () => {
        expect(findLoadingIcon().exists()).toBe(true);
        expect(findCiTable().exists()).toBe(false);
      });
    });

    describe('when queries are resolved', () => {
      describe('successfully', () => {
        beforeEach(async () => {
          mockEnvironments.mockResolvedValue(mockProjectEnvironments);
          mockVariables.mockResolvedValue(mockProjectVariables);

          await createComponentWithApollo({
            provide: { ...createProjectProvide(), ...pagesFeatureFlagProvide },
          });
        });

        it('passes down the expected max variable limit as props', () => {
          expect(findCiSettings().props('maxVariableLimit')).toBe(
            mockProjectVariables.data.project.ciVariables.limit,
          );
        });

        it('passes down the expected environments as props', () => {
          expect(findCiSettings().props('environments')).toEqual([prodName, devName]);
        });

        it('passes down the expected variables as props', () => {
          expect(findCiSettings().props('variables')).toEqual(
            mockProjectVariables.data.project.ciVariables.nodes,
          );
        });

        it('createAlert was not called', () => {
          expect(createAlert).not.toHaveBeenCalled();
        });
      });

      describe('with an error for variables', () => {
        beforeEach(async () => {
          mockEnvironments.mockResolvedValue(mockProjectEnvironments);
          mockVariables.mockRejectedValue();

          await createComponentWithApollo({ provide: pagesFeatureFlagProvide });
        });

        it('calls createAlert with the expected error message', () => {
          expect(createAlert).toHaveBeenCalledWith({ message: variableFetchErrorText });
        });
      });

      describe('with an error for environments', () => {
        beforeEach(async () => {
          mockEnvironments.mockRejectedValue();
          mockVariables.mockResolvedValue(mockProjectVariables);

          await createComponentWithApollo({ provide: pagesFeatureFlagProvide });
        });

        it('calls createAlert with the expected error message', () => {
          expect(createAlert).toHaveBeenCalledWith({ message: environmentFetchErrorText });
        });
      });
    });

    describe('environment query', () => {
      describe('when there is an environment key in queryData', () => {
        beforeEach(() => {
          mockEnvironments.mockResolvedValue(mockProjectEnvironments);

          mockVariables.mockResolvedValue(mockProjectVariables);
        });

        it('environments are fetched', async () => {
          await createComponentWithApollo({
            props: { ...createProjectProps() },
            provide: pagesFeatureFlagProvide,
          });

          expect(mockEnvironments).toHaveBeenCalled();
        });

        // applies only to project-level CI variables
        describe('when environment scope is limited', () => {
          beforeEach(async () => {
            await createComponentWithApollo({
              props: { ...createProjectProps() },
              provide: pagesFeatureFlagProvide,
            });
          });

          it('initial query is called with the correct variables', () => {
            expect(mockEnvironments).toHaveBeenCalledWith({
              first: ENVIRONMENT_QUERY_LIMIT,
              fullPath: '/namespace/project/',
              search: '',
            });
          });

          it(`refetches environments when search term is present`, async () => {
            expect(mockEnvironments).toHaveBeenCalledTimes(1);
            expect(mockEnvironments).toHaveBeenCalledWith(expect.objectContaining({ search: '' }));

            await findCiSettings().vm.$emit('search-environment-scope', 'staging');

            expect(mockEnvironments).toHaveBeenCalledTimes(2);
            expect(mockEnvironments).toHaveBeenCalledWith(
              expect.objectContaining({ search: 'staging' }),
            );
          });

          it('does not show loading icon in table while searching for environments', () => {
            findCiSettings().vm.$emit('search-environment-scope', 'staging');

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

      describe("when there isn't an environment key in queryData", () => {
        beforeEach(async () => {
          mockVariables.mockResolvedValue(mockGroupVariables);

          await createComponentWithApollo({
            props: { ...createGroupProps() },
            provide: pagesFeatureFlagProvide,
          });
        });

        it('fetching environments is skipped', () => {
          expect(mockEnvironments).not.toHaveBeenCalled();
        });
      });
    });

    describe('mutations', () => {
      const groupProps = createGroupProps();
      const instanceProps = createInstanceProps();
      const projectProps = createProjectProps();

      let mockMutationMap;

      describe('error handling and feedback', () => {
        beforeEach(async () => {
          mockVariables.mockResolvedValue(mockGroupVariables);
          mockMutation.mockResolvedValue({ ...mockGroupVariables.data, errors: [] });

          await createComponentWithApollo({
            customHandlers: [[getGroupVariables, mockVariables]],
            customResolvers: {
              Mutation: {
                ...resolvers.Mutation,
                addGroupVariable: mockMutation,
                updateGroupVariable: mockMutation,
                deleteGroupVariable: mockMutation,
              },
            },
            props: groupProps,
            provide: pagesFeatureFlagProvide,
          });
        });

        it.each`
          actionName  | event
          ${'add'}    | ${'add-variable'}
          ${'update'} | ${'update-variable'}
          ${'delete'} | ${'delete-variable'}
        `(
          'throws the specific graphql error if present when user performs $actionName variable',
          async ({ event }) => {
            const graphQLErrorMessage = 'There is a problem with this graphQL action';
            mockMutation.mockResolvedValue({
              ...mockGroupVariables.data,
              errors: [graphQLErrorMessage],
            });

            await findCiSettings().vm.$emit(event, newVariable);
            await waitForPromises();

            expect(mockMutation).toHaveBeenCalled();
            expect(createAlert).toHaveBeenCalledWith({ message: graphQLErrorMessage });
          },
        );

        it.each`
          actionName  | event
          ${'add'}    | ${'add-variable'}
          ${'update'} | ${'update-variable'}
          ${'delete'} | ${'delete-variable'}
        `(
          'throws generic error on failure with no graphql errors and user performs $actionName variable',
          async ({ event }) => {
            mockMutation.mockRejectedValue();

            await findCiSettings().vm.$emit(event, newVariable);
            await waitForPromises();

            expect(mockMutation).toHaveBeenCalled();
            expect(createAlert).toHaveBeenCalledWith({ message: genericMutationErrorText });
          },
        );

        it.each`
          actionName  | event
          ${'add'}    | ${'add-variable'}
          ${'update'} | ${'update-variable'}
          ${'delete'} | ${'delete-variable'}
        `(
          'displays toast message after user performs $actionName variable',
          async ({ actionName, event }) => {
            await findCiSettings().vm.$emit(event, newVariable);
            await waitForPromises();

            expect(mockMutation).toHaveBeenCalled();
            expect(mockToastShow).toHaveBeenCalledWith(
              mapMutationActionToToast[actionName](newVariable.key),
            );
          },
        );
      });

      const setupMockMutations = (mockResolvedMutation) => {
        mockAddMutation.mockResolvedValue(mockResolvedMutation);
        mockUpdateMutation.mockResolvedValue(mockResolvedMutation);
        mockDeleteMutation.mockResolvedValue(mockResolvedMutation);

        return {
          add: mockAddMutation,
          update: mockUpdateMutation,
          delete: mockDeleteMutation,
        };
      };

      describe.each`
        scope         | mockVariablesResolvedValue | getVariablesHandler    | addMutationName         | updateMutationName         | deleteMutationName         | props
        ${'instance'} | ${mockVariables}           | ${getAdminVariables}   | ${'addAdminVariable'}   | ${'updateAdminVariable'}   | ${'deleteAdminVariable'}   | ${instanceProps}
        ${'group'}    | ${mockGroupVariables}      | ${getGroupVariables}   | ${'addGroupVariable'}   | ${'updateGroupVariable'}   | ${'deleteGroupVariable'}   | ${groupProps}
        ${'project'}  | ${mockProjectVariables}    | ${getProjectVariables} | ${'addProjectVariable'} | ${'updateProjectVariable'} | ${'deleteProjectVariable'} | ${projectProps}
      `(
        '$scope variable mutations',
        ({
          addMutationName,
          deleteMutationName,
          getVariablesHandler,
          mockVariablesResolvedValue,
          updateMutationName,
          props,
        }) => {
          beforeEach(async () => {
            mockVariables.mockResolvedValue(mockVariablesResolvedValue);
            mockMutationMap = setupMockMutations({ ...mockVariables.data, errors: [] });

            await createComponentWithApollo({
              customHandlers: [[getVariablesHandler, mockVariables]],
              customResolvers: {
                Mutation: {
                  ...resolvers.Mutation,
                  [addMutationName]: mockAddMutation,
                  [updateMutationName]: mockUpdateMutation,
                  [deleteMutationName]: mockDeleteMutation,
                },
              },
              props,
              provide: pagesFeatureFlagProvide,
            });
          });

          it.each`
            actionName  | event
            ${'add'}    | ${'add-variable'}
            ${'update'} | ${'update-variable'}
            ${'delete'} | ${'delete-variable'}
          `(
            'calls the right mutation when user performs $actionName variable',
            async ({ event, actionName }) => {
              await findCiSettings().vm.$emit(event, newVariable);
              await waitForPromises();

              expect(mockMutationMap[actionName]).toHaveBeenCalledWith(
                expect.anything(),
                {
                  endpoint: mockProvide.endpoint,
                  fullPath: props.fullPath,
                  id: props.id,
                  variable: newVariable,
                },
                expect.anything(),
                expect.anything(),
              );
            },
          );
        },
      );

      describe('without fullpath and ID props', () => {
        beforeEach(async () => {
          mockMutation.mockResolvedValue({ ...mockAdminVariables.data, errors: [] });
          mockVariables.mockResolvedValue(mockAdminVariables);

          await createComponentWithApollo({
            customHandlers: [[getAdminVariables, mockVariables]],
            customResolvers: {
              Mutation: {
                ...resolvers.Mutation,
                addAdminVariable: mockMutation,
              },
            },
            props: createInstanceProps(),
            provide: pagesFeatureFlagProvide,
          });
        });

        it('does not pass fullPath and ID to the mutation', async () => {
          await findCiSettings().vm.$emit('add-variable', newVariable);
          await waitForPromises();

          expect(mockMutation).toHaveBeenCalledWith(
            expect.anything(),
            {
              endpoint: mockProvide.endpoint,
              variable: newVariable,
            },
            expect.anything(),
            expect.anything(),
          );
        });
      });
    });

    describe('Props', () => {
      const mockGroupCiVariables = mockGroupVariables.data.group.ciVariables;
      const mockProjectCiVariables = mockProjectVariables.data.project.ciVariables;

      describe('in a specific context as', () => {
        it.each`
          name          | mockVariablesValue      | mockEnvironmentsValue      | withEnvironments | expectedEnvironments | propsFn                | provideFn               | mutation             | maxVariableLimit
          ${'project'}  | ${mockProjectVariables} | ${mockProjectEnvironments} | ${true}          | ${['prod', 'dev']}   | ${createProjectProps}  | ${createProjectProvide} | ${null}              | ${mockProjectCiVariables.limit}
          ${'group'}    | ${mockGroupVariables}   | ${[]}                      | ${false}         | ${[]}                | ${createGroupProps}    | ${createGroupProvide}   | ${getGroupVariables} | ${mockGroupCiVariables.limit}
          ${'instance'} | ${mockAdminVariables}   | ${[]}                      | ${false}         | ${[]}                | ${createInstanceProps} | ${() => {}}             | ${getAdminVariables} | ${0}
        `(
          'passes down all the required props when its a $name component',
          async ({
            mutation,
            maxVariableLimit,
            mockVariablesValue,
            mockEnvironmentsValue,
            withEnvironments,
            expectedEnvironments,
            propsFn,
            provideFn,
          }) => {
            const props = propsFn();
            const provide = provideFn();

            mockVariables.mockResolvedValue(mockVariablesValue);

            if (withEnvironments) {
              mockEnvironments.mockResolvedValue(mockEnvironmentsValue);
            }

            let customHandlers = null;

            if (mutation) {
              customHandlers = [[mutation, mockVariables]];
            }

            await createComponentWithApollo({
              customHandlers,
              props,
              provide: { ...provide, ...pagesFeatureFlagProvide },
            });

            expect(findCiSettings().props()).toEqual({
              areEnvironmentsLoading: false,
              areScopedVariablesAvailable: wrapper.props().areScopedVariablesAvailable,
              hideEnvironmentScope: defaultProps.hideEnvironmentScope,
              hasEnvScopeQuery: props.hasEnvScopeQuery,
              pageInfo: defaultProps.pageInfo,
              isLoading: false,
              maxVariableLimit,
              variables: wrapper.props().queryData.ciVariables.lookup(mockVariablesValue.data)
                ?.nodes,
              entity: props.entity,
              environments: expectedEnvironments,
            });
          },
        );
      });

      describe('refetchAfterMutation', () => {
        it.each`
          bool     | text                                | timesQueryCalled
          ${true}  | ${'refetches the variables'}        | ${2}
          ${false} | ${'does not refetch the variables'} | ${1}
        `('when $bool it $text', async ({ bool, timesQueryCalled }) => {
          mockMutation.mockResolvedValue({ ...mockAdminVariables.data, errors: [] });
          mockVariables.mockResolvedValue(mockAdminVariables);

          await createComponentWithApollo({
            customHandlers: [[getAdminVariables, mockVariables]],
            customResolvers: {
              Mutation: {
                ...resolvers.Mutation,
                addAdminVariable: mockMutation,
              },
            },
            props: { ...createInstanceProps(), refetchAfterMutation: bool },
            provide: pagesFeatureFlagProvide,
          });

          await findCiSettings().vm.$emit('add-variable', newVariable);
          await waitForPromises();

          expect(mockVariables).toHaveBeenCalledTimes(timesQueryCalled);
        });
      });

      describe('Validators', () => {
        describe('queryData', () => {
          let error;

          beforeEach(() => {
            mockVariables.mockResolvedValue(mockGroupVariables);
          });

          it('will mount component with right data', async () => {
            try {
              await createComponentWithApollo({
                customHandlers: [[getGroupVariables, mockVariables]],
                props: { ...createGroupProps() },
                provide: pagesFeatureFlagProvide,
              });
            } catch (e) {
              error = e;
            } finally {
              expect(wrapper.exists()).toBe(true);
              expect(error).toBeUndefined();
            }
          });

          it('report custom validator error on wrong data', () => {
            expect(() =>
              assertProps(
                ciVariableShared,
                { ...defaultProps, ...createGroupProps(), queryData: { wrongKey: {} } },
                { provide: mockProvide },
              ),
            ).toThrow('custom validator check failed for prop');
          });
        });

        describe('mutationData', () => {
          let error;

          beforeEach(() => {
            mockVariables.mockResolvedValue(mockGroupVariables);
          });

          it('will mount component with right data', async () => {
            try {
              await createComponentWithApollo({
                props: { ...createGroupProps() },
                provide: pagesFeatureFlagProvide,
              });
            } catch (e) {
              error = e;
            } finally {
              expect(wrapper.exists()).toBe(true);
              expect(error).toBeUndefined();
            }
          });

          it('report custom validator error on wrong data', () => {
            expect(() =>
              assertProps(
                ciVariableShared,
                { ...defaultProps, ...createGroupProps(), mutationData: { wrongKey: {} } },
                { provide: { ...mockProvide, ...pagesFeatureFlagProvide } },
              ),
            ).toThrow('custom validator check failed for prop');
          });
        });
      });
    });
  });
});