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

environment_form_spec.js « environments « frontend « spec - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 803207bcce8744b414156314355ee1c7d6ee4cd4 (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
import { GlLoadingIcon, GlAlert } from '@gitlab/ui';
import Vue from 'vue';
import VueApollo from 'vue-apollo';
import waitForPromises from 'helpers/wait_for_promises';
import { mountExtended } from 'helpers/vue_test_utils_helper';
import EnvironmentForm from '~/environments/components/environment_form.vue';
import getUserAuthorizedAgents from '~/environments/graphql/queries/user_authorized_agents.query.graphql';
import createMockApollo from '../__helpers__/mock_apollo_helper';
import { mockKasTunnelUrl } from './mock_data';

jest.mock('~/lib/utils/csrf');

const DEFAULT_PROPS = {
  environment: { name: '', externalUrl: '' },
  title: 'environment',
  cancelPath: '/cancel',
};

const PROVIDE = {
  protectedEnvironmentSettingsPath: '/projects/not_real/settings/ci_cd',
  kasTunnelUrl: mockKasTunnelUrl,
};
const userAccessAuthorizedAgents = [
  { agent: { id: '1', name: 'agent-1' } },
  { agent: { id: '2', name: 'agent-2' } },
];

describe('~/environments/components/form.vue', () => {
  let wrapper;

  const getNamespacesQueryResult = jest
    .fn()
    .mockReturnValue([{ metadata: { name: 'default' } }, { metadata: { name: 'agent' } }]);

  const createWrapper = (propsData = {}, options = {}) =>
    mountExtended(EnvironmentForm, {
      provide: PROVIDE,
      ...options,
      propsData: {
        ...DEFAULT_PROPS,
        ...propsData,
      },
    });

  const createWrapperWithApollo = ({
    propsData = {},
    kubernetesNamespaceForEnvironment = false,
    queryResult = null,
  } = {}) => {
    Vue.use(VueApollo);

    const requestHandlers = [
      [
        getUserAuthorizedAgents,
        jest.fn().mockResolvedValue({
          data: {
            project: {
              id: '1',
              userAccessAuthorizedAgents: { nodes: userAccessAuthorizedAgents },
            },
          },
        }),
      ],
    ];

    const mockResolvers = {
      Query: {
        k8sNamespaces: queryResult || getNamespacesQueryResult,
      },
    };

    return mountExtended(EnvironmentForm, {
      provide: {
        ...PROVIDE,
        glFeatures: {
          kubernetesNamespaceForEnvironment,
        },
      },
      propsData: {
        ...DEFAULT_PROPS,
        ...propsData,
      },
      apolloProvider: createMockApollo(requestHandlers, mockResolvers),
    });
  };

  const findAgentSelector = () => wrapper.findByTestId('agent-selector');
  const findNamespaceSelector = () => wrapper.findByTestId('namespace-selector');
  const findAlert = () => wrapper.findComponent(GlAlert);

  const selectAgent = async () => {
    findAgentSelector().vm.$emit('shown');
    await waitForPromises();
    await findAgentSelector().vm.$emit('select', '2');
  };

  describe('default', () => {
    beforeEach(() => {
      wrapper = createWrapper();
    });

    it('links to documentation regarding environments', () => {
      const link = wrapper.findByRole('link', { name: 'More information.' });
      expect(link.attributes('href')).toBe('/help/ci/environments/index.md');
    });

    it('links the cancel button to the cancel path', () => {
      const cancel = wrapper.findByRole('link', { name: 'Cancel' });

      expect(cancel.attributes('href')).toBe(DEFAULT_PROPS.cancelPath);
    });

    describe('name input', () => {
      let name;

      beforeEach(() => {
        name = wrapper.findByLabelText('Name');
      });

      it('should emit changes to the name', async () => {
        await name.setValue('test');
        await name.trigger('blur');

        expect(wrapper.emitted('change')).toEqual([[{ name: 'test', externalUrl: '' }]]);
      });

      it('should validate that the name is required', async () => {
        await name.setValue('');
        await name.trigger('blur');

        expect(wrapper.findByText('This field is required').exists()).toBe(true);
        expect(name.attributes('aria-invalid')).toBe('true');
      });
    });

    describe('url input', () => {
      let url;

      beforeEach(() => {
        url = wrapper.findByLabelText('External URL');
      });

      it('should emit changes to the url', async () => {
        await url.setValue('https://example.com');
        await url.trigger('blur');

        expect(wrapper.emitted('change')).toEqual([
          [{ name: '', externalUrl: 'https://example.com' }],
        ]);
      });

      it('should validate that the url is required', async () => {
        await url.setValue('example.com');
        await url.trigger('blur');

        expect(wrapper.findByText('The URL should start with http:// or https://').exists()).toBe(
          true,
        );
        expect(url.attributes('aria-invalid')).toBe('true');
      });
    });

    it('submits when the form does', async () => {
      await wrapper.findByRole('form', { title: 'environment' }).trigger('submit');

      expect(wrapper.emitted('submit')).toEqual([[]]);
    });
  });

  it('shows a loading icon while loading', () => {
    wrapper = createWrapper({ loading: true });
    expect(wrapper.findComponent(GlLoadingIcon).exists()).toBe(true);
  });

  describe('when a new environment is being created', () => {
    beforeEach(() => {
      wrapper = createWrapper({
        environment: {
          name: '',
          externalUrl: '',
        },
      });
    });

    it('renders an enabled "Name" field', () => {
      const nameInput = wrapper.findByLabelText('Name');

      expect(nameInput.attributes().disabled).toBeUndefined();
      expect(nameInput.element.value).toBe('');
    });

    it('renders an "External URL" field', () => {
      const urlInput = wrapper.findByLabelText('External URL');

      expect(urlInput.element.value).toBe('');
    });

    it('does not show protected environment documentation', () => {
      expect(wrapper.findByRole('link', { name: 'Protected environments' }).exists()).toBe(false);
    });
  });

  describe('when no protected environment link is provided', () => {
    beforeEach(() => {
      wrapper = createWrapper({
        provide: {},
      });
    });

    it('does not show protected environment documentation', () => {
      expect(wrapper.findByRole('link', { name: 'Protected environments' }).exists()).toBe(false);
    });
  });

  describe('when an existing environment is being edited', () => {
    beforeEach(() => {
      wrapper = createWrapper({
        environment: {
          id: 1,
          name: 'test',
          externalUrl: 'https://example.com',
        },
      });
    });

    it('renders a disabled "Name" field', () => {
      const nameInput = wrapper.findByLabelText('Name');

      expect(nameInput.attributes().disabled).toBe('disabled');
      expect(nameInput.element.value).toBe('test');
    });

    it('renders an "External URL" field', () => {
      const urlInput = wrapper.findByLabelText('External URL');

      expect(urlInput.element.value).toBe('https://example.com');
    });

    it('renders an agent selector listbox', () => {
      expect(findAgentSelector().props()).toMatchObject({
        searchable: true,
        toggleText: EnvironmentForm.i18n.agentHelpText,
        headerText: EnvironmentForm.i18n.agentHelpText,
        resetButtonLabel: EnvironmentForm.i18n.reset,
        loading: false,
        items: [],
      });
    });
  });

  describe('agent selector', () => {
    beforeEach(() => {
      wrapper = createWrapperWithApollo();
    });

    it('sets the items prop of the agent selector after fetching the list', async () => {
      findAgentSelector().vm.$emit('shown');
      await waitForPromises();

      expect(findAgentSelector().props('items')).toEqual([
        { value: '1', text: 'agent-1' },
        { value: '2', text: 'agent-2' },
      ]);
    });

    it('sets the loading prop of the agent selector while fetching the list', async () => {
      await findAgentSelector().vm.$emit('shown');
      expect(findAgentSelector().props('loading')).toBe(true);

      await waitForPromises();

      expect(findAgentSelector().props('loading')).toBe(false);
    });

    it('filters the agent list on user search', async () => {
      findAgentSelector().vm.$emit('shown');
      await waitForPromises();
      await findAgentSelector().vm.$emit('search', 'agent-2');

      expect(findAgentSelector().props('items')).toEqual([{ value: '2', text: 'agent-2' }]);
    });

    it('updates agent selector field with the name of selected agent', async () => {
      await selectAgent();

      expect(findAgentSelector().props('toggleText')).toBe('agent-2');
    });

    it('emits changes to the clusterAgentId', async () => {
      await selectAgent();

      expect(wrapper.emitted('change')).toEqual([
        [{ name: '', externalUrl: '', clusterAgentId: '2', kubernetesNamespace: null }],
      ]);
    });
  });

  describe('namespace selector', () => {
    it("doesn't render namespace selector if `kubernetesNamespaceForEnvironment` feature flag is disabled", () => {
      wrapper = createWrapperWithApollo();
      expect(findNamespaceSelector().exists()).toBe(false);
    });

    describe('when `kubernetesNamespaceForEnvironment` feature flag is enabled', () => {
      beforeEach(() => {
        wrapper = createWrapperWithApollo({
          kubernetesNamespaceForEnvironment: true,
        });
      });

      it("doesn't render namespace selector by default", () => {
        expect(findNamespaceSelector().exists()).toBe(false);
      });

      describe('when the agent was selected', () => {
        beforeEach(async () => {
          await selectAgent();
        });

        it('renders namespace selector', () => {
          expect(findNamespaceSelector().exists()).toBe(true);
        });

        it('requests the kubernetes namespaces with the correct configuration', async () => {
          const configuration = {
            basePath: mockKasTunnelUrl.replace(/\/$/, ''),
            baseOptions: {
              headers: {
                'GitLab-Agent-Id': 2,
              },
              withCredentials: true,
            },
          };

          await waitForPromises();

          expect(getNamespacesQueryResult).toHaveBeenCalledWith(
            {},
            { configuration },
            expect.anything(),
            expect.anything(),
          );
        });

        it('sets the loading prop while fetching the list', async () => {
          expect(findNamespaceSelector().props('loading')).toBe(true);

          await waitForPromises();

          expect(findNamespaceSelector().props('loading')).toBe(false);
        });

        it('renders a list of available namespaces', async () => {
          await waitForPromises();

          expect(findNamespaceSelector().props('items')).toEqual([
            { text: 'default', value: 'default' },
            { text: 'agent', value: 'agent' },
          ]);
        });

        it('filters the namespaces list on user search', async () => {
          await waitForPromises();
          await findNamespaceSelector().vm.$emit('search', 'default');

          expect(findNamespaceSelector().props('items')).toEqual([
            { value: 'default', text: 'default' },
          ]);
        });

        it('updates namespace selector field with the name of selected namespace', async () => {
          await waitForPromises();
          await findNamespaceSelector().vm.$emit('select', 'agent');

          expect(findNamespaceSelector().props('toggleText')).toBe('agent');
        });

        it('emits changes to the kubernetesNamespace', async () => {
          await waitForPromises();
          await findNamespaceSelector().vm.$emit('select', 'agent');

          expect(wrapper.emitted('change')[1]).toEqual([
            { name: '', externalUrl: '', kubernetesNamespace: 'agent' },
          ]);
        });

        it('clears namespace selector when another agent was selected', async () => {
          await waitForPromises();
          await findNamespaceSelector().vm.$emit('select', 'agent');

          expect(findNamespaceSelector().props('toggleText')).toBe('agent');

          await findAgentSelector().vm.$emit('select', '1');
          expect(findNamespaceSelector().props('toggleText')).toBe(
            EnvironmentForm.i18n.namespaceHelpText,
          );
        });
      });

      describe('when cannot connect to the cluster', () => {
        const error = new Error('Error from the cluster_client API');

        beforeEach(async () => {
          wrapper = createWrapperWithApollo({
            kubernetesNamespaceForEnvironment: true,
            queryResult: jest.fn().mockRejectedValueOnce(error),
          });

          await selectAgent();
          await waitForPromises();
        });

        it("doesn't render the namespace selector", () => {
          expect(findNamespaceSelector().exists()).toBe(false);
        });

        it('renders an alert', () => {
          expect(findAlert().text()).toBe('Error from the cluster_client API');
        });
      });
    });
  });

  describe('when environment has an associated agent', () => {
    const environmentWithAgent = {
      ...DEFAULT_PROPS.environment,
      clusterAgent: { id: '1', name: 'agent-1' },
      clusterAgentId: '1',
    };
    beforeEach(() => {
      wrapper = createWrapperWithApollo({
        propsData: { environment: environmentWithAgent },
        kubernetesNamespaceForEnvironment: true,
      });
    });

    it('updates agent selector field with the name of the associated agent', () => {
      expect(findAgentSelector().props('toggleText')).toBe('agent-1');
    });

    it('renders namespace selector', async () => {
      await waitForPromises();
      expect(findNamespaceSelector().exists()).toBe(true);
    });

    it('renders a list of available namespaces', async () => {
      await waitForPromises();

      expect(findNamespaceSelector().props('items')).toEqual([
        { text: 'default', value: 'default' },
        { text: 'agent', value: 'agent' },
      ]);
    });
  });

  describe('when environment has an associated kubernetes namespace', () => {
    const environmentWithAgentAndNamespace = {
      ...DEFAULT_PROPS.environment,
      clusterAgent: { id: '1', name: 'agent-1' },
      clusterAgentId: '1',
      kubernetesNamespace: 'default',
    };
    beforeEach(() => {
      wrapper = createWrapperWithApollo({
        propsData: { environment: environmentWithAgentAndNamespace },
        kubernetesNamespaceForEnvironment: true,
      });
    });

    it('updates namespace selector with the name of the associated namespace', async () => {
      await waitForPromises();
      expect(findNamespaceSelector().props('toggleText')).toBe('default');
    });
  });
});