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

import_project_members_modal_spec.js « components « invite_members « frontend « spec - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 4fac21f7a576cda4e85bac88120eccb771d2d3d1 (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
import { GlFormGroup, GlSprintf, GlModal, GlCollapse, GlIcon } from '@gitlab/ui';
import MockAdapter from 'axios-mock-adapter';
import { nextTick } from 'vue';
import { createWrapper } from '@vue/test-utils';
import { BV_HIDE_MODAL } from '~/lib/utils/constants';
import { stubComponent } from 'helpers/stub_component';
import { shallowMountExtended } from 'helpers/vue_test_utils_helper';
import waitForPromises from 'helpers/wait_for_promises';
import { mockTracking, unmockTracking } from 'helpers/tracking_helper';
import * as ProjectsApi from '~/api/projects_api';
import eventHub from '~/invite_members/event_hub';
import ImportProjectMembersModal from '~/invite_members/components/import_project_members_modal.vue';
import ProjectSelect from '~/invite_members/components/project_select.vue';
import axios from '~/lib/utils/axios_utils';
import { HTTP_STATUS_CREATED } from '~/lib/utils/http_status';

import {
  displaySuccessfulInvitationAlert,
  reloadOnInvitationSuccess,
} from '~/invite_members/utils/trigger_successful_invite_alert';

import {
  EXPANDED_ERRORS,
  IMPORT_PROJECT_MEMBERS_MODAL_TRACKING_CATEGORY,
  IMPORT_PROJECT_MEMBERS_MODAL_TRACKING_LABEL,
} from '~/invite_members/constants';
import {
  IMPORT_PROJECT_MEMBERS_PATH,
  importProjectMembersApiResponse,
} from '../mock_data/api_responses';

jest.mock('~/invite_members/utils/trigger_successful_invite_alert');

let wrapper;
let mock;
let trackingSpy;

const projectId = '1';
const projectName = 'test name';
const projectToBeImported = { id: '2' };
const $toast = {
  show: jest.fn(),
};

const expectTracking = (action) =>
  expect(trackingSpy).toHaveBeenCalledWith(IMPORT_PROJECT_MEMBERS_MODAL_TRACKING_CATEGORY, action, {
    label: IMPORT_PROJECT_MEMBERS_MODAL_TRACKING_LABEL,
    category: IMPORT_PROJECT_MEMBERS_MODAL_TRACKING_CATEGORY,
    property: undefined,
  });

const triggerOpenModal = async () => {
  eventHub.$emit('openProjectMembersModal');
  await nextTick();
};

const createComponent = ({ props = {} } = {}) => {
  wrapper = shallowMountExtended(ImportProjectMembersModal, {
    propsData: {
      projectId,
      projectName,
      ...props,
    },
    stubs: {
      GlModal: stubComponent(GlModal, {
        template:
          '<div><slot name="modal-title"></slot><slot></slot><slot name="modal-footer"></slot></div>',
      }),
      GlSprintf,
      GlFormGroup: stubComponent(GlFormGroup, {
        props: ['state', 'invalidFeedback'],
      }),
    },
    mocks: {
      $toast,
    },
  });

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

beforeEach(() => {
  gon.api_version = 'v4';
  mock = new MockAdapter(axios);
});

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

describe('ImportProjectMembersModal', () => {
  const findGlModal = () => wrapper.findComponent(GlModal);
  const findIntroText = () => wrapper.findComponent({ ref: 'modalIntro' }).text();
  const clickImportButton = () => findGlModal().vm.$emit('primary', { preventDefault: jest.fn() });
  const closeModal = () => findGlModal().vm.$emit('hidden', { preventDefault: jest.fn() });
  const findFormGroup = () => wrapper.findByTestId('form-group');
  const formGroupInvalidFeedback = () => findFormGroup().props('invalidFeedback');
  const formGroupErrorState = () => findFormGroup().props('state');
  const findProjectSelect = () => wrapper.findComponent(ProjectSelect);
  const findMemberErrorAlert = () => wrapper.findByTestId('alert-member-error');
  const findMoreInviteErrorsButton = () => wrapper.findByTestId('accordion-button');
  const findAccordion = () => wrapper.findComponent(GlCollapse);
  const findErrorsIcon = () => wrapper.findComponent(GlIcon);
  const findMemberErrorMessage = (element) =>
    `@${Object.keys(importProjectMembersApiResponse.EXPANDED_IMPORT_ERRORS.message)[element]}: ${
      Object.values(importProjectMembersApiResponse.EXPANDED_IMPORT_ERRORS.message)[element]
    }`;

  describe('rendering the modal', () => {
    beforeEach(() => {
      createComponent();
    });

    it('renders the modal with the correct title', () => {
      expect(findGlModal().props('title')).toBe('Import members from another project');
    });

    it('renders the Cancel button text correctly', () => {
      expect(findGlModal().props('actionCancel')).toMatchObject({
        text: 'Cancel',
      });
    });

    it('renders the Import button text correctly', () => {
      expect(findGlModal().props('actionPrimary')).toMatchObject({
        text: 'Import project members',
        attributes: {
          variant: 'confirm',
          disabled: true,
          loading: false,
        },
      });
    });

    it('renders the modal intro text correctly', () => {
      expect(findIntroText()).toBe("You're importing members to the test name project.");
    });

    it('sets isLoading to true when the Invite button is clicked', async () => {
      clickImportButton();

      await nextTick();

      expect(findGlModal().props('actionPrimary').attributes.loading).toBe(true);
    });

    it('tracks render', async () => {
      await triggerOpenModal();

      expectTracking('render');
    });

    it('tracks cancel', () => {
      findGlModal().vm.$emit('cancel');

      expectTracking('click_cancel');
    });

    it('tracks close', () => {
      findGlModal().vm.$emit('close');

      expectTracking('click_x');
    });
  });

  describe('submitting the import', () => {
    it('prevents closing', () => {
      const evt = { preventDefault: jest.fn() };
      createComponent();

      findGlModal().vm.$emit('primary', evt);

      expect(evt.preventDefault).toHaveBeenCalledTimes(1);
    });

    describe('when the import is successful with reloadPageOnSubmit', () => {
      beforeEach(() => {
        createComponent({
          props: { reloadPageOnSubmit: true },
        });

        findProjectSelect().vm.$emit('input', projectToBeImported);

        jest.spyOn(ProjectsApi, 'importProjectMembers').mockResolvedValue();

        clickImportButton();
      });

      it('calls displaySuccessfulInvitationAlert on mount', () => {
        expect(displaySuccessfulInvitationAlert).toHaveBeenCalled();
      });

      it('calls reloadOnInvitationSuccess', () => {
        expect(reloadOnInvitationSuccess).toHaveBeenCalled();
      });

      it('does not display the successful toastMessage', () => {
        expect($toast.show).not.toHaveBeenCalledWith(
          'Successfully imported',
          wrapper.vm.$options.toastOptions,
        );
      });

      it('tracks successful import', () => {
        expectTracking('invite_successful');
      });
    });

    describe('when the import is successful', () => {
      beforeEach(() => {
        createComponent();

        findProjectSelect().vm.$emit('input', projectToBeImported);

        jest.spyOn(ProjectsApi, 'importProjectMembers').mockResolvedValue();

        clickImportButton();
      });

      it('calls Api importProjectMembers', () => {
        expect(ProjectsApi.importProjectMembers).toHaveBeenCalledWith(
          projectId,
          projectToBeImported.id,
        );
      });

      it('displays the successful toastMessage', () => {
        expect($toast.show).toHaveBeenCalledWith(
          'Successfully imported',
          wrapper.vm.$options.toastOptions,
        );
      });

      it('hides the modal', () => {
        const rootWrapper = createWrapper(wrapper.vm.$root);

        expect(rootWrapper.emitted(BV_HIDE_MODAL)).toHaveLength(1);
      });

      it('does not call displaySuccessfulInvitationAlert on mount', () => {
        expect(displaySuccessfulInvitationAlert).not.toHaveBeenCalled();
      });

      it('does not call reloadOnInvitationSuccess', () => {
        expect(reloadOnInvitationSuccess).not.toHaveBeenCalled();
      });

      it('sets isLoading to false after success', () => {
        expect(findGlModal().props('actionPrimary').attributes.loading).toBe(false);
      });

      it('tracks successful import', () => {
        expectTracking('invite_successful');
      });
    });

    describe('when the import fails due to generic api error', () => {
      beforeEach(async () => {
        createComponent();

        findProjectSelect().vm.$emit('input', projectToBeImported);

        jest
          .spyOn(ProjectsApi, 'importProjectMembers')
          .mockRejectedValue({ response: { data: { success: false } } });

        clickImportButton();
        await waitForPromises();
      });

      it('displays the generic error message', () => {
        expect(formGroupInvalidFeedback()).toBe('Unable to import project members');
        expect(formGroupErrorState()).toBe(false);
      });

      it('sets isLoading to false after error', () => {
        expect(findGlModal().props('actionPrimary').attributes.loading).toBe(false);
      });

      it('clears the error when the modal is closed with an error', async () => {
        expect(formGroupInvalidFeedback()).toBe('Unable to import project members');
        expect(formGroupErrorState()).toBe(false);

        closeModal();

        await nextTick();

        expect(formGroupInvalidFeedback()).toBe('');
        expect(formGroupErrorState()).not.toBe(false);
      });
    });

    describe('when the import fails with member import errors', () => {
      const mockInvitationsApi = (code, data) => {
        mock.onPost(IMPORT_PROJECT_MEMBERS_PATH).reply(code, data);
      };

      beforeEach(() => {
        createComponent();
        findProjectSelect().vm.$emit('input', projectToBeImported);
      });

      it('displays the error alert', async () => {
        mockInvitationsApi(
          HTTP_STATUS_CREATED,
          importProjectMembersApiResponse.NO_COLLAPSE_IMPORT_ERRORS,
        );

        clickImportButton();
        await waitForPromises();

        expect(findMemberErrorAlert().props('title')).toContain(
          'The following 2 out of 2 members could not be added',
        );
        expect(findMemberErrorAlert().text()).toContain(findMemberErrorMessage(0));
        expect(findMemberErrorAlert().text()).toContain(findMemberErrorMessage(1));
      });

      it('displays collapse when there are more than 2 errors', async () => {
        mockInvitationsApi(
          HTTP_STATUS_CREATED,
          importProjectMembersApiResponse.EXPANDED_IMPORT_ERRORS,
        );

        clickImportButton();
        await waitForPromises();

        expect(findAccordion().exists()).toBe(true);
        expect(findMoreInviteErrorsButton().text()).toContain('Show more (2)');
      });

      it('toggles the collapse on click', async () => {
        mockInvitationsApi(
          HTTP_STATUS_CREATED,
          importProjectMembersApiResponse.EXPANDED_IMPORT_ERRORS,
        );

        clickImportButton();
        await waitForPromises();

        expect(findMoreInviteErrorsButton().text()).toContain('Show more (2)');
        expect(findErrorsIcon().attributes('class')).not.toContain('gl-rotate-180');
        expect(findAccordion().attributes('visible')).toBeUndefined();

        await findMoreInviteErrorsButton().vm.$emit('click');

        expect(findMoreInviteErrorsButton().text()).toContain(EXPANDED_ERRORS);
        expect(findErrorsIcon().attributes('class')).toContain('gl-rotate-180');
        expect(findAccordion().attributes('visible')).toBeDefined();

        await findMoreInviteErrorsButton().vm.$emit('click');

        expect(findMoreInviteErrorsButton().text()).toContain('Show more (2)');
      });

      it("doesn't display collapse when there are 2 or less errors", async () => {
        mockInvitationsApi(
          HTTP_STATUS_CREATED,
          importProjectMembersApiResponse.NO_COLLAPSE_IMPORT_ERRORS,
        );

        clickImportButton();
        await waitForPromises();

        expect(findAccordion().exists()).toBe(false);
        expect(findMoreInviteErrorsButton().exists()).toBe(false);
      });
    });
  });
});