summaryrefslogtreecommitdiff
path: root/spec/frontend/security_configuration/components/training_provider_list_spec.js
blob: 18c9ada6bde9c189265f9e8333416f69a901629a (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
import * as Sentry from '@sentry/browser';
import { GlAlert, GlLink, GlToggle, GlCard, GlSkeletonLoader } from '@gitlab/ui';
import { shallowMount } from '@vue/test-utils';
import Vue from 'vue';
import VueApollo from 'vue-apollo';
import createMockApollo from 'helpers/mock_apollo_helper';
import { mockTracking, unmockTracking } from 'helpers/tracking_helper';
import {
  TRACK_TOGGLE_TRAINING_PROVIDER_ACTION,
  TRACK_TOGGLE_TRAINING_PROVIDER_LABEL,
} from '~/security_configuration/constants';
import TrainingProviderList from '~/security_configuration/components/training_provider_list.vue';
import securityTrainingProvidersQuery from '~/security_configuration/graphql/security_training_providers.query.graphql';
import configureSecurityTrainingProvidersMutation from '~/security_configuration/graphql/configure_security_training_providers.mutation.graphql';
import dismissUserCalloutMutation from '~/graphql_shared/mutations/dismiss_user_callout.mutation.graphql';
import waitForPromises from 'helpers/wait_for_promises';
import {
  dismissUserCalloutResponse,
  dismissUserCalloutErrorResponse,
  securityTrainingProviders,
  securityTrainingProvidersResponse,
  updateSecurityTrainingProvidersResponse,
  updateSecurityTrainingProvidersErrorResponse,
  testProjectPath,
  textProviderIds,
} from '../mock_data';

Vue.use(VueApollo);

describe('TrainingProviderList component', () => {
  let wrapper;
  let apolloProvider;

  const createApolloProvider = ({ handlers = [] } = {}) => {
    const defaultHandlers = [
      [
        securityTrainingProvidersQuery,
        jest.fn().mockResolvedValue(securityTrainingProvidersResponse),
      ],
      [
        configureSecurityTrainingProvidersMutation,
        jest.fn().mockResolvedValue(updateSecurityTrainingProvidersResponse),
      ],
    ];

    // make sure we don't have any duplicate handlers to avoid 'Request handler already defined for query` errors
    const mergedHandlers = [...new Map([...defaultHandlers, ...handlers])];

    apolloProvider = createMockApollo(mergedHandlers);
  };

  const createComponent = () => {
    wrapper = shallowMount(TrainingProviderList, {
      provide: {
        projectFullPath: testProjectPath,
      },
      apolloProvider,
    });
  };

  const waitForQueryToBeLoaded = () => waitForPromises();
  const waitForMutationToBeLoaded = waitForQueryToBeLoaded;

  const findCards = () => wrapper.findAllComponents(GlCard);
  const findLinks = () => wrapper.findAllComponents(GlLink);
  const findToggles = () => wrapper.findAllComponents(GlToggle);
  const findFirstToggle = () => findToggles().at(0);
  const findLoader = () => wrapper.findComponent(GlSkeletonLoader);
  const findErrorAlert = () => wrapper.findComponent(GlAlert);

  const toggleFirstProvider = () => findFirstToggle().vm.$emit('change', textProviderIds[0]);

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

  describe('when loading', () => {
    beforeEach(() => {
      const pendingHandler = () => new Promise(() => {});

      createApolloProvider({
        handlers: [[securityTrainingProvidersQuery, pendingHandler]],
      });
      createComponent();
    });

    it('shows the loader', () => {
      expect(findLoader().exists()).toBe(true);
    });

    it('does not show the cards', () => {
      expect(findCards().exists()).toBe(false);
    });
  });

  describe('with a successful response', () => {
    beforeEach(() => {
      createApolloProvider({
        handlers: [
          [dismissUserCalloutMutation, jest.fn().mockResolvedValue(dismissUserCalloutResponse)],
        ],
        resolvers: {
          Mutation: {
            configureSecurityTrainingProviders: () => ({
              errors: [],
              securityTrainingProviders: [],
            }),
          },
        },
      });

      createComponent();
    });

    describe('basic structure', () => {
      beforeEach(async () => {
        await waitForQueryToBeLoaded();
      });

      it('renders correct amount of cards', () => {
        expect(findCards()).toHaveLength(securityTrainingProviders.length);
      });

      securityTrainingProviders.forEach(({ name, description, url, isEnabled }, index) => {
        it(`shows the name for card ${index}`, () => {
          expect(findCards().at(index).text()).toContain(name);
        });

        it(`shows the description for card ${index}`, () => {
          expect(findCards().at(index).text()).toContain(description);
        });

        it(`shows the learn more link for card ${index}`, () => {
          expect(findLinks().at(index).attributes()).toEqual({
            target: '_blank',
            href: url,
          });
        });

        it(`shows the toggle with the correct value for card ${index}`, () => {
          expect(findToggles().at(index).props('value')).toEqual(isEnabled);
        });

        it('does not show loader when query is populated', () => {
          expect(findLoader().exists()).toBe(false);
        });
      });
    });

    describe('storing training provider settings', () => {
      beforeEach(async () => {
        jest.spyOn(apolloProvider.defaultClient, 'mutate');

        await waitForQueryToBeLoaded();

        await toggleFirstProvider();
      });

      it.each`
        loading  | wait     | desc
        ${true}  | ${false} | ${'enables loading of GlToggle when mutation is called'}
        ${false} | ${true}  | ${'disables loading of GlToggle when mutation is complete'}
      `('$desc', async ({ loading, wait }) => {
        if (wait) {
          await waitForMutationToBeLoaded();
        }
        expect(findFirstToggle().props('isLoading')).toBe(loading);
      });

      it('calls mutation when toggle is changed', () => {
        expect(apolloProvider.defaultClient.mutate).toHaveBeenCalledWith(
          expect.objectContaining({
            mutation: configureSecurityTrainingProvidersMutation,
            variables: {
              input: {
                providerId: textProviderIds[0],
                isEnabled: true,
                isPrimary: false,
                projectPath: testProjectPath,
              },
            },
          }),
        );
      });

      it('dismisses the callout when the feature gets first enabled', async () => {
        // wait for configuration update mutation to complete
        await waitForMutationToBeLoaded();

        // both the config and dismiss mutations have been called
        expect(apolloProvider.defaultClient.mutate).toHaveBeenCalledTimes(2);
        expect(apolloProvider.defaultClient.mutate).toHaveBeenNthCalledWith(
          2,
          expect.objectContaining({
            mutation: dismissUserCalloutMutation,
            variables: {
              input: {
                featureName: 'security_training_feature_promotion',
              },
            },
          }),
        );

        toggleFirstProvider();
        await waitForMutationToBeLoaded();

        // the config mutation has been called again but not the dismiss mutation
        expect(apolloProvider.defaultClient.mutate).toHaveBeenCalledTimes(3);
        expect(apolloProvider.defaultClient.mutate).toHaveBeenNthCalledWith(
          3,
          expect.objectContaining({
            mutation: configureSecurityTrainingProvidersMutation,
          }),
        );
      });
    });

    describe('metrics', () => {
      let trackingSpy;

      beforeEach(() => {
        trackingSpy = mockTracking(undefined, wrapper.element, jest.spyOn);
      });

      afterEach(() => {
        unmockTracking();
      });

      it('tracks when a provider gets toggled', () => {
        expect(trackingSpy).not.toHaveBeenCalled();

        toggleFirstProvider();

        // Note: Ideally we also want to test that the tracking event is called correctly when a
        // provider gets disabled, but that's a bit tricky to do with the current implementation
        // Once https://gitlab.com/gitlab-org/gitlab/-/issues/348985 and https://gitlab.com/gitlab-org/gitlab/-/merge_requests/79492
        // are merged this will be much easer to do and should be tackled then.
        expect(trackingSpy).toHaveBeenCalledWith(undefined, TRACK_TOGGLE_TRAINING_PROVIDER_ACTION, {
          property: securityTrainingProviders[0].id,
          label: TRACK_TOGGLE_TRAINING_PROVIDER_LABEL,
          extra: {
            providerIsEnabled: true,
          },
        });
      });
    });
  });

  describe('with errors', () => {
    const expectErrorAlertToExist = () => {
      expect(findErrorAlert().props()).toMatchObject({
        dismissible: false,
        variant: 'danger',
      });
    };

    describe('when fetching training providers', () => {
      beforeEach(async () => {
        createApolloProvider({
          handlers: [[securityTrainingProvidersQuery, jest.fn().mockRejectedValue()]],
        });
        createComponent();

        await waitForQueryToBeLoaded();
      });

      it('shows an non-dismissible error alert', () => {
        expectErrorAlertToExist();
      });

      it('shows an error description', () => {
        expect(findErrorAlert().text()).toBe(TrainingProviderList.i18n.providerQueryErrorMessage);
      });
    });

    describe('when storing training provider configurations', () => {
      beforeEach(async () => {
        createApolloProvider({
          handlers: [
            [
              configureSecurityTrainingProvidersMutation,
              jest.fn().mockReturnValue(updateSecurityTrainingProvidersErrorResponse),
            ],
          ],
        });
        createComponent();

        await waitForQueryToBeLoaded();
        toggleFirstProvider();
        await waitForMutationToBeLoaded();
      });

      it('shows an non-dismissible error alert', () => {
        expectErrorAlertToExist();
      });

      it('shows an error description', () => {
        expect(findErrorAlert().text()).toBe(TrainingProviderList.i18n.configMutationErrorMessage);
      });
    });

    describe.each`
      errorType          | mutationHandler
      ${'backend error'} | ${jest.fn().mockReturnValue(dismissUserCalloutErrorResponse)}
      ${'network error'} | ${jest.fn().mockRejectedValue()}
    `('when dismissing the callout and a "$errorType" happens', ({ mutationHandler }) => {
      beforeEach(async () => {
        jest.spyOn(Sentry, 'captureException').mockImplementation();

        createApolloProvider({
          handlers: [[dismissUserCalloutMutation, mutationHandler]],
          resolvers: {
            Mutation: {
              configureSecurityTrainingProviders: () => ({
                errors: [],
                securityTrainingProviders: [],
              }),
            },
          },
        });
        createComponent();

        await waitForQueryToBeLoaded();
        toggleFirstProvider();
      });

      it('logs the error to sentry', async () => {
        expect(Sentry.captureException).not.toHaveBeenCalled();

        await waitForMutationToBeLoaded();

        expect(Sentry.captureException).toHaveBeenCalled();
      });
    });
  });
});