summaryrefslogtreecommitdiff
path: root/spec/frontend/notifications/components/custom_notifications_modal_spec.js
blob: 70749557e617afe724160590617e974a5fa1ae9b (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
import { GlSprintf, GlModal, GlFormGroup, GlFormCheckbox, GlLoadingIcon } from '@gitlab/ui';
import { shallowMount } from '@vue/test-utils';
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import { nextTick } from 'vue';
import { extendedWrapper } from 'helpers/vue_test_utils_helper';
import waitForPromises from 'helpers/wait_for_promises';
import { HTTP_STATUS_NOT_FOUND, HTTP_STATUS_OK } from '~/lib/utils/http_status';
import CustomNotificationsModal from '~/notifications/components/custom_notifications_modal.vue';
import { i18n } from '~/notifications/constants';

const mockNotificationSettingsResponses = {
  default: {
    level: 'custom',
    events: {
      new_release: true,
      new_note: false,
    },
  },
  updated: {
    level: 'custom',
    events: {
      new_release: true,
      new_note: true,
    },
  },
};

const mockToastShow = jest.fn();

describe('CustomNotificationsModal', () => {
  let wrapper;
  let mockAxios;

  function createComponent(options = {}) {
    const { injectedProperties = {}, props = {} } = options;
    return extendedWrapper(
      shallowMount(CustomNotificationsModal, {
        props: {
          ...props,
        },
        provide: {
          ...injectedProperties,
        },
        mocks: {
          $toast: {
            show: mockToastShow,
          },
        },
        stubs: {
          GlModal,
          GlFormGroup,
          GlFormCheckbox,
        },
      }),
    );
  }

  const findModalBodyDescription = () => wrapper.findComponent(GlSprintf);
  const findAllCheckboxes = () => wrapper.findAllComponents(GlFormCheckbox);
  const findCheckboxAt = (index) => findAllCheckboxes().at(index);

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

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

  describe('template', () => {
    beforeEach(() => {
      wrapper = createComponent();
    });

    it('displays the body title and the body message', () => {
      expect(wrapper.findByTestId('modalBodyTitle').text()).toBe(
        i18n.customNotificationsModal.bodyTitle,
      );
      expect(findModalBodyDescription().attributes('message')).toContain(
        i18n.customNotificationsModal.bodyMessage,
      );
    });

    describe('checkbox items', () => {
      beforeEach(async () => {
        wrapper = createComponent();

        // setData usage is discouraged. See https://gitlab.com/groups/gitlab-org/-/epics/7330 for details
        // eslint-disable-next-line no-restricted-syntax
        wrapper.setData({
          events: [
            { id: 'new_release', enabled: true, name: 'New release', loading: false },
            { id: 'new_note', enabled: false, name: 'New note', loading: true },
          ],
        });

        await nextTick();
      });

      it.each`
        index | eventId          | eventName        | enabled  | loading
        ${0}  | ${'new_release'} | ${'New release'} | ${true}  | ${false}
        ${1}  | ${'new_note'}    | ${'New note'}    | ${false} | ${true}
      `(
        'renders a checkbox for "$eventName" with checked=$enabled',
        async ({ index, eventName, enabled, loading }) => {
          const checkbox = findCheckboxAt(index);
          expect(checkbox.text()).toContain(eventName);
          expect(checkbox.vm.$attrs.checked).toBe(enabled);
          expect(checkbox.findComponent(GlLoadingIcon).exists()).toBe(loading);
        },
      );
    });
  });

  describe('API calls', () => {
    describe('load notification settings', () => {
      beforeEach(() => {
        jest.spyOn(axios, 'get');
      });

      it.each`
        projectId | groupId | endpointUrl                                   | notificationType | condition
        ${1}      | ${null} | ${'/api/v4/projects/1/notification_settings'} | ${'project'}     | ${'a projectId is given'}
        ${null}   | ${1}    | ${'/api/v4/groups/1/notification_settings'}   | ${'group'}       | ${'a groupId is given'}
        ${null}   | ${null} | ${'/api/v4/notification_settings'}            | ${'global'}      | ${'neither projectId nor groupId are given'}
      `(
        'requests $notificationType notification settings when $condition',
        async ({ projectId, groupId, endpointUrl }) => {
          const injectedProperties = {
            projectId,
            groupId,
          };

          mockAxios
            .onGet(endpointUrl)
            .reply(HTTP_STATUS_OK, mockNotificationSettingsResponses.default);

          wrapper = createComponent({ injectedProperties });

          wrapper.findComponent(GlModal).vm.$emit('show');

          await waitForPromises();

          expect(axios.get).toHaveBeenCalledWith(endpointUrl);
        },
      );

      it('updates the loading state and the events property', async () => {
        const endpointUrl = '/api/v4/notification_settings';

        mockAxios
          .onGet(endpointUrl)
          .reply(HTTP_STATUS_OK, mockNotificationSettingsResponses.default);

        wrapper = createComponent();

        wrapper.findComponent(GlModal).vm.$emit('show');
        expect(wrapper.vm.isLoading).toBe(true);

        await waitForPromises();

        expect(axios.get).toHaveBeenCalledWith(endpointUrl);
        expect(wrapper.vm.isLoading).toBe(false);
        expect(wrapper.vm.events).toEqual([
          { id: 'new_release', enabled: true, name: 'New release', loading: false },
          { id: 'new_note', enabled: false, name: 'New note', loading: false },
        ]);
      });

      it('shows a toast message when the request fails', async () => {
        mockAxios.onGet('/api/v4/notification_settings').reply(HTTP_STATUS_NOT_FOUND, {});
        wrapper = createComponent();

        wrapper.findComponent(GlModal).vm.$emit('show');

        await waitForPromises();

        expect(mockToastShow).toHaveBeenCalledWith(
          'An error occurred while loading the notification settings. Please try again.',
        );
      });
    });

    describe('update notification settings', () => {
      beforeEach(() => {
        jest.spyOn(axios, 'put');
      });

      it.each`
        projectId | groupId | endpointUrl                                   | notificationType | condition
        ${1}      | ${null} | ${'/api/v4/projects/1/notification_settings'} | ${'project'}     | ${'a projectId is given'}
        ${null}   | ${1}    | ${'/api/v4/groups/1/notification_settings'}   | ${'group'}       | ${'a groupId is given'}
        ${null}   | ${null} | ${'/api/v4/notification_settings'}            | ${'global'}      | ${'neither projectId nor groupId are given'}
      `(
        'updates the $notificationType notification settings when $condition and the user clicks the checkbox',
        async ({ projectId, groupId, endpointUrl }) => {
          mockAxios
            .onGet(endpointUrl)
            .reply(HTTP_STATUS_OK, mockNotificationSettingsResponses.default);

          mockAxios
            .onPut(endpointUrl)
            .reply(HTTP_STATUS_OK, mockNotificationSettingsResponses.updated);

          const injectedProperties = {
            projectId,
            groupId,
          };

          wrapper = createComponent({ injectedProperties });

          // setData usage is discouraged. See https://gitlab.com/groups/gitlab-org/-/epics/7330 for details
          // eslint-disable-next-line no-restricted-syntax
          wrapper.setData({
            events: [
              { id: 'new_release', enabled: true, name: 'New release', loading: false },
              { id: 'new_note', enabled: false, name: 'New note', loading: false },
            ],
          });

          await nextTick();

          findCheckboxAt(1).vm.$emit('change', true);

          await waitForPromises();

          expect(axios.put).toHaveBeenCalledWith(endpointUrl, {
            new_note: true,
          });

          expect(wrapper.vm.events).toEqual([
            { id: 'new_release', enabled: true, name: 'New release', loading: false },
            { id: 'new_note', enabled: true, name: 'New note', loading: false },
          ]);
        },
      );

      it('shows a toast message when the request fails', async () => {
        mockAxios.onPut('/api/v4/notification_settings').reply(HTTP_STATUS_NOT_FOUND, {});
        wrapper = createComponent();

        // setData usage is discouraged. See https://gitlab.com/groups/gitlab-org/-/epics/7330 for details
        // eslint-disable-next-line no-restricted-syntax
        wrapper.setData({
          events: [
            { id: 'new_release', enabled: true, name: 'New release', loading: false },
            { id: 'new_note', enabled: false, name: 'New note', loading: false },
          ],
        });

        await nextTick();

        findCheckboxAt(1).vm.$emit('change', true);

        await waitForPromises();

        expect(mockToastShow).toHaveBeenCalledWith(
          'An error occurred while updating the notification settings. Please try again.',
        );
      });
    });
  });
});