summaryrefslogtreecommitdiff
path: root/spec/frontend/ci_variable_list/components/ci_variable_modal_spec.js
blob: e5019e3261eeb9708aafeeabdd2f079eabc6ebf4 (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
import { GlButton, GlFormInput } from '@gitlab/ui';
import { mockTracking } from 'helpers/tracking_helper';
import { shallowMountExtended, mountExtended } from 'helpers/vue_test_utils_helper';
import CiEnvironmentsDropdown from '~/ci_variable_list/components/ci_environments_dropdown.vue';
import CiVariableModal from '~/ci_variable_list/components/ci_variable_modal.vue';
import {
  ADD_VARIABLE_ACTION,
  AWS_ACCESS_KEY_ID,
  EDIT_VARIABLE_ACTION,
  EVENT_LABEL,
  EVENT_ACTION,
  ENVIRONMENT_SCOPE_LINK_TITLE,
  instanceString,
} from '~/ci_variable_list/constants';
import { mockVariablesWithScopes } from '../mocks';
import ModalStub from '../stubs';

describe('Ci variable modal', () => {
  let wrapper;
  let trackingSpy;

  const maskableRegex = '^[a-zA-Z0-9_+=/@:.~-]{8,}$';
  const mockVariables = mockVariablesWithScopes(instanceString);

  const defaultProvide = {
    awsLogoSvgPath: '/logo',
    awsTipCommandsLink: '/tips',
    awsTipDeployLink: '/deploy',
    awsTipLearnLink: '/learn-link',
    containsVariableReferenceLink: '/reference',
    environmentScopeLink: '/help/environments',
    isProtectedByDefault: false,
    maskedEnvironmentVariablesLink: '/variables-link',
    maskableRegex,
    protectedEnvironmentVariablesLink: '/protected-link',
  };

  const defaultProps = {
    areScopedVariablesAvailable: true,
    environments: [],
    mode: ADD_VARIABLE_ACTION,
    selectedVariable: {},
    variable: [],
  };

  const createComponent = ({ mountFn = shallowMountExtended, props = {}, provide = {} } = {}) => {
    wrapper = mountFn(CiVariableModal, {
      attachTo: document.body,
      provide: { ...defaultProvide, ...provide },
      propsData: {
        ...defaultProps,
        ...props,
      },
      stubs: {
        GlModal: ModalStub,
      },
    });
  };

  const findCiEnvironmentsDropdown = () => wrapper.find(CiEnvironmentsDropdown);
  const findReferenceWarning = () => wrapper.findByTestId('contains-variable-reference');
  const findModal = () => wrapper.find(ModalStub);
  const findAWSTip = () => wrapper.findByTestId('aws-guidance-tip');
  const findAddorUpdateButton = () => wrapper.findByTestId('ciUpdateOrAddVariableBtn');
  const deleteVariableButton = () =>
    findModal()
      .findAll(GlButton)
      .wrappers.find((button) => button.props('variant') === 'danger');
  const findProtectedVariableCheckbox = () =>
    wrapper.findByTestId('ci-variable-protected-checkbox');
  const findMaskedVariableCheckbox = () => wrapper.findByTestId('ci-variable-masked-checkbox');
  const findValueField = () => wrapper.find('#ci-variable-value');
  const findEnvScopeLink = () => wrapper.findByTestId('environment-scope-link');
  const findEnvScopeInput = () => wrapper.findByTestId('environment-scope').find(GlFormInput);

  afterEach(() => {
    wrapper.destroy();
  });

  describe('Adding a variable', () => {
    describe('when no key/value pair are present', () => {
      beforeEach(() => {
        createComponent();
      });

      it('shows the submit button as disabled ', () => {
        expect(findAddorUpdateButton().attributes('disabled')).toBe('true');
      });
    });

    describe('when a key/value pair is present', () => {
      beforeEach(() => {
        createComponent({ props: { selectedVariable: mockVariables[0] } });
      });

      it('shows the submit button as enabled ', () => {
        expect(findAddorUpdateButton().attributes('disabled')).toBeUndefined();
      });
    });

    describe('events', () => {
      const [currentVariable] = mockVariables;

      beforeEach(() => {
        createComponent({ props: { selectedVariable: currentVariable } });
        jest.spyOn(wrapper.vm, '$emit');
      });

      it('Dispatches `add-variable` action on submit', () => {
        findAddorUpdateButton().vm.$emit('click');
        expect(wrapper.emitted('add-variable')).toEqual([[currentVariable]]);
      });

      it('Dispatches the `hideModal` event when dismissing', () => {
        findModal().vm.$emit('hidden');
        expect(wrapper.emitted('hideModal')).toEqual([[]]);
      });
    });
  });

  describe('when protected by default', () => {
    describe('when adding a new variable', () => {
      beforeEach(() => {
        createComponent({ provide: { isProtectedByDefault: true } });
        findModal().vm.$emit('shown');
      });

      it('updates the protected value to true', () => {
        expect(findProtectedVariableCheckbox().attributes('data-is-protected-checked')).toBe(
          'true',
        );
      });
    });

    describe('when editing a variable', () => {
      beforeEach(() => {
        createComponent({
          provide: { isProtectedByDefault: false },
          props: {
            selectedVariable: {},
            mode: EDIT_VARIABLE_ACTION,
          },
        });
        findModal().vm.$emit('shown');
      });

      it('keeps the value as false', async () => {
        expect(
          findProtectedVariableCheckbox().attributes('data-is-protected-checked'),
        ).toBeUndefined();
      });
    });
  });

  describe('Adding a new non-AWS variable', () => {
    beforeEach(() => {
      const [variable] = mockVariables;
      createComponent({ mountFn: mountExtended, props: { selectedVariable: variable } });
    });

    it('does not show AWS guidance tip', () => {
      const tip = findAWSTip();
      expect(tip.exists()).toBe(true);
      expect(tip.isVisible()).toBe(false);
    });
  });

  describe('Adding a new AWS variable', () => {
    beforeEach(() => {
      const [variable] = mockVariables;
      const AWSKeyVariable = {
        ...variable,
        key: AWS_ACCESS_KEY_ID,
        value: 'AKIAIOSFODNN7EXAMPLEjdhy',
      };
      createComponent({ mountFn: mountExtended, props: { selectedVariable: AWSKeyVariable } });
    });

    it('shows AWS guidance tip', () => {
      const tip = findAWSTip();
      expect(tip.exists()).toBe(true);
      expect(tip.isVisible()).toBe(true);
    });
  });

  describe('Reference warning when adding a variable', () => {
    describe('with a $ character', () => {
      beforeEach(() => {
        const [variable] = mockVariables;
        const variableWithDollarSign = {
          ...variable,
          value: 'valueWith$',
        };
        createComponent({
          mountFn: mountExtended,
          props: { selectedVariable: variableWithDollarSign },
        });
      });

      it(`renders the variable reference warning`, () => {
        expect(findReferenceWarning().exists()).toBe(true);
      });
    });

    describe('without a $ character', () => {
      beforeEach(() => {
        const [variable] = mockVariables;
        createComponent({
          mountFn: mountExtended,
          props: { selectedVariable: variable },
        });
      });

      it(`does not render the variable reference warning`, () => {
        expect(findReferenceWarning().exists()).toBe(false);
      });
    });
  });

  describe('Editing a variable', () => {
    const [variable] = mockVariables;

    beforeEach(() => {
      createComponent({ props: { selectedVariable: variable, mode: EDIT_VARIABLE_ACTION } });
      jest.spyOn(wrapper.vm, '$emit');
    });

    it('button text is Update variable when updating', () => {
      expect(findAddorUpdateButton().text()).toBe('Update variable');
    });

    it('Update variable button dispatches updateVariable with correct variable', () => {
      findAddorUpdateButton().vm.$emit('click');
      expect(wrapper.emitted('update-variable')).toEqual([[variable]]);
    });

    it('Propagates the `hideModal` event', () => {
      findModal().vm.$emit('hidden');
      expect(wrapper.emitted('hideModal')).toEqual([[]]);
    });

    it('dispatches `delete-variable` with correct variable to delete', () => {
      deleteVariableButton().vm.$emit('click');
      expect(wrapper.emitted('delete-variable')).toEqual([[variable]]);
    });
  });

  describe('Environment scope', () => {
    describe('when feature is available', () => {
      it('renders the environment dropdown', () => {
        createComponent({
          mountFn: mountExtended,
          props: {
            areScopedVariablesAvailable: true,
          },
        });

        expect(findCiEnvironmentsDropdown().exists()).toBe(true);
        expect(findCiEnvironmentsDropdown().isVisible()).toBe(true);
      });

      it('renders a link to documentation on scopes', () => {
        createComponent({ mountFn: mountExtended });

        const link = findEnvScopeLink();

        expect(link.attributes('title')).toBe(ENVIRONMENT_SCOPE_LINK_TITLE);
        expect(link.attributes('href')).toBe(defaultProvide.environmentScopeLink);
      });
    });

    describe('when feature is not available', () => {
      it('disables the dropdown', () => {
        createComponent({
          mountFn: mountExtended,
          props: {
            areScopedVariablesAvailable: false,
          },
        });

        expect(findCiEnvironmentsDropdown().exists()).toBe(false);
        expect(findEnvScopeInput().attributes('readonly')).toBe('readonly');
      });
    });
  });

  describe('Validations', () => {
    const maskError = 'This variable can not be masked.';

    describe('when the mask state is invalid', () => {
      beforeEach(async () => {
        const [variable] = mockVariables;
        const invalidMaskVariable = {
          ...variable,
          value: 'd:;',
          masked: false,
        };
        createComponent({
          mountFn: mountExtended,
          props: { selectedVariable: invalidMaskVariable },
        });
        trackingSpy = mockTracking(undefined, wrapper.element, jest.spyOn);
        await findMaskedVariableCheckbox().trigger('click');
      });

      it('disables the submit button', () => {
        expect(findAddorUpdateButton().attributes('disabled')).toBe('disabled');
      });

      it('shows the correct error text', () => {
        expect(findModal().text()).toContain(maskError);
      });

      it('sends the correct tracking event', () => {
        expect(trackingSpy).toHaveBeenCalledWith(undefined, EVENT_ACTION, {
          label: EVENT_LABEL,
          property: ';',
        });
      });
    });

    describe.each`
      value                 | masked   | eventSent | trackingErrorProperty
      ${'secretValue'}      | ${false} | ${0}      | ${null}
      ${'short'}            | ${true}  | ${0}      | ${null}
      ${'dollar$ign'}       | ${false} | ${1}      | ${'$'}
      ${'dollar$ign'}       | ${true}  | ${1}      | ${'$'}
      ${'unsupported|char'} | ${true}  | ${1}      | ${'|'}
      ${'unsupported|char'} | ${false} | ${0}      | ${null}
    `('Adding a new variable', ({ value, masked, eventSent, trackingErrorProperty }) => {
      beforeEach(async () => {
        const [variable] = mockVariables;
        const invalidKeyVariable = {
          ...variable,
          value: '',
          masked: false,
        };
        createComponent({
          mountFn: mountExtended,
          props: { selectedVariable: invalidKeyVariable },
        });
        trackingSpy = mockTracking(undefined, wrapper.element, jest.spyOn);
        await findValueField().vm.$emit('input', value);
        if (masked) {
          await findMaskedVariableCheckbox().trigger('click');
        }
      });

      it(`${
        eventSent > 0 ? 'sends the correct' : 'does not send the'
      } variable validation tracking event with ${value}`, () => {
        expect(trackingSpy).toHaveBeenCalledTimes(eventSent);

        if (eventSent > 0) {
          expect(trackingSpy).toHaveBeenCalledWith(undefined, EVENT_ACTION, {
            label: EVENT_LABEL,
            property: trackingErrorProperty,
          });
        }
      });
    });

    describe('when masked variable has acceptable value', () => {
      beforeEach(() => {
        const [variable] = mockVariables;
        const validMaskandKeyVariable = {
          ...variable,
          key: AWS_ACCESS_KEY_ID,
          value: '12345678',
          masked: true,
        };
        createComponent({
          mountFn: mountExtended,
          props: { selectedVariable: validMaskandKeyVariable },
        });
      });

      it('does not disable the submit button', () => {
        expect(findAddorUpdateButton().attributes('disabled')).toBeUndefined();
      });
    });
  });
});