summaryrefslogtreecommitdiff
path: root/spec/frontend/incidents/components/incidents_list_spec.js
blob: 9ed0294e87657757de6807ce8bf01912d39abd6f (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
import { GlAlert, GlLoadingIcon, GlTable, GlAvatar, GlEmptyState } from '@gitlab/ui';
import { mount } from '@vue/test-utils';
import { nextTick } from 'vue';
import { extendedWrapper } from 'helpers/vue_test_utils_helper';
import IncidentsList from '~/incidents/components/incidents_list.vue';
import {
  I18N,
  TH_CREATED_AT_TEST_ID,
  TH_SEVERITY_TEST_ID,
  TH_PUBLISHED_TEST_ID,
  TH_INCIDENT_SLA_TEST_ID,
  trackIncidentCreateNewOptions,
  trackIncidentListViewsOptions,
} from '~/incidents/constants';
import { visitUrl, joinPaths, mergeUrlParams } from '~/lib/utils/url_utility';
import SeverityToken from '~/sidebar/components/severity/severity.vue';
import Tracking from '~/tracking';
import TimeAgoTooltip from '~/vue_shared/components/time_ago_tooltip.vue';
import mockIncidents from '../mocks/incidents.json';

jest.mock('~/lib/utils/url_utility', () => ({
  visitUrl: jest.fn().mockName('visitUrlMock'),
  joinPaths: jest.requireActual('~/lib/utils/url_utility').joinPaths,
  mergeUrlParams: jest.fn(),
  setUrlParams: jest.fn(),
  updateHistory: jest.fn(),
}));
jest.mock('~/tracking');

describe('Incidents List', () => {
  let wrapper;
  const newIssuePath = 'namespace/project/-/issues/new';
  const emptyListSvgPath = '/assets/empty.svg';
  const incidentTemplateName = 'incident';
  const incidentType = 'incident';
  const incidentsCount = {
    opened: 24,
    closed: 10,
    all: 26,
  };

  const findTable = () => wrapper.find(GlTable);
  const findTableRows = () => wrapper.findAll('table tbody tr');
  const findAlert = () => wrapper.find(GlAlert);
  const findLoader = () => wrapper.find(GlLoadingIcon);
  const findTimeAgo = () => wrapper.findAll(TimeAgoTooltip);
  const findAssignees = () => wrapper.findAll('[data-testid="incident-assignees"]');
  const findCreateIncidentBtn = () => wrapper.find('[data-testid="createIncidentBtn"]');
  const findClosedIcon = () => wrapper.findAll("[data-testid='incident-closed']");
  const findEmptyState = () => wrapper.find(GlEmptyState);
  const findSeverity = () => wrapper.findAll(SeverityToken);
  const findEscalationStatus = () => wrapper.findAll('[data-testid="incident-escalation-status"]');
  const findIncidentLink = () => wrapper.findByTestId('incident-link');

  function mountComponent({ data = {}, loading = false, provide = {} } = {}) {
    wrapper = extendedWrapper(
      mount(IncidentsList, {
        data() {
          return {
            incidents: [],
            incidentsCount: {},
            ...data,
          };
        },
        mocks: {
          $apollo: {
            queries: {
              incidents: {
                loading,
              },
            },
          },
        },
        provide: {
          projectPath: '/project/path',
          newIssuePath,
          incidentTemplateName,
          incidentType,
          issuePath: '/project/issues',
          publishedAvailable: true,
          emptyListSvgPath,
          textQuery: '',
          authorUsernameQuery: '',
          assigneeUsernameQuery: '',
          slaFeatureAvailable: true,
          canCreateIncident: true,
          incidentEscalationsAvailable: true,
          ...provide,
        },
        stubs: {
          GlButton: true,
          GlAvatar: true,
          GlEmptyState: true,
          ServiceLevelAgreementCell: true,
        },
      }),
    );
  }

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

  it('shows the loading state', () => {
    mountComponent({
      loading: true,
    });
    expect(findLoader().exists()).toBe(true);
  });

  describe('empty state', () => {
    const {
      emptyState: { title, emptyClosedTabTitle, description, cannotCreateIncidentDescription },
    } = I18N;

    it.each`
      statusFilter | all  | closed | expectedTitle          | canCreateIncident | expectedDescription
      ${'all'}     | ${2} | ${1}   | ${title}               | ${true}           | ${description}
      ${'open'}    | ${2} | ${0}   | ${title}               | ${true}           | ${description}
      ${'closed'}  | ${0} | ${0}   | ${title}               | ${true}           | ${description}
      ${'closed'}  | ${2} | ${0}   | ${emptyClosedTabTitle} | ${true}           | ${undefined}
      ${'all'}     | ${2} | ${1}   | ${title}               | ${false}          | ${cannotCreateIncidentDescription}
    `(
      `when active tab is $statusFilter and there are $all incidents in total and $closed closed incidents, the empty state
      has title: $expectedTitle and description: $expectedDescription`,
      ({ statusFilter, all, closed, expectedTitle, expectedDescription, canCreateIncident }) => {
        mountComponent({
          data: { incidents: { list: [] }, incidentsCount: { all, closed }, statusFilter },
          provide: { canCreateIncident },
          loading: false,
        });
        expect(findEmptyState().exists()).toBe(true);
        expect(findEmptyState().attributes('title')).toBe(expectedTitle);
        expect(findEmptyState().attributes('description')).toBe(expectedDescription);
      },
    );
  });

  it('shows error state', () => {
    mountComponent({
      data: { incidents: { list: [] }, incidentsCount: { all: 0 }, errored: true },
      loading: false,
    });
    expect(findTable().text()).toContain(I18N.noIncidents);
    expect(findAlert().exists()).toBe(true);
  });

  describe('Incident Management list', () => {
    beforeEach(() => {
      mountComponent({
        data: { incidents: { list: mockIncidents }, incidentsCount },
        loading: false,
      });
    });

    it('renders rows based on provided data', () => {
      expect(findTableRows().length).toBe(mockIncidents.length);
    });

    it('renders a createdAt with timeAgo component per row', () => {
      expect(findTimeAgo().length).toBe(mockIncidents.length);
    });

    it('renders a link to the incident as the incident title', () => {
      const { title, iid } = mockIncidents[0];
      const link = findIncidentLink();

      expect(link.text()).toBe(title);
      expect(link.attributes('href')).toContain(`issues/incident/${iid}`);
    });

    describe('Assignees', () => {
      it('shows Unassigned when there are no assignees', () => {
        expect(findAssignees().at(0).text()).toBe(I18N.unassigned);
      });

      it('renders an avatar component when there is an assignee', () => {
        const avatar = findAssignees().at(1).find(GlAvatar);
        const { src, label } = avatar.attributes();
        const { name, avatarUrl } = mockIncidents[1].assignees.nodes[0];

        expect(avatar.exists()).toBe(true);
        expect(label).toBe(name);
        expect(src).toBe(avatarUrl);
      });

      it('renders a closed icon for closed incidents', () => {
        expect(findClosedIcon().length).toBe(
          mockIncidents.filter(({ state }) => state === 'closed').length,
        );
      });
    });

    it('renders severity per row', () => {
      expect(findSeverity().length).toBe(mockIncidents.length);
    });

    describe('Escalation status', () => {
      it('renders escalation status per row', () => {
        expect(findEscalationStatus().length).toBe(mockIncidents.length);

        const actualStatuses = findEscalationStatus().wrappers.map((status) => status.text());
        expect(actualStatuses).toEqual([
          'Triggered',
          'Acknowledged',
          'Resolved',
          I18N.noEscalationStatus,
        ]);
      });

      describe('when feature is disabled', () => {
        beforeEach(() => {
          mountComponent({
            data: { incidents: { list: mockIncidents }, incidentsCount },
            provide: { incidentEscalationsAvailable: false },
            loading: false,
          });
        });

        it('is absent if feature flag is disabled', () => {
          expect(findEscalationStatus().length).toBe(0);
        });
      });
    });

    it('contains a link to the incident details page', async () => {
      findTableRows().at(0).trigger('click');
      expect(visitUrl).toHaveBeenCalledWith(
        joinPaths(`/project/issues/incident`, mockIncidents[0].iid),
      );
    });
  });

  describe('Create Incident', () => {
    beforeEach(() => {
      mountComponent({
        data: { incidents: { list: mockIncidents }, incidentsCount: {} },
        loading: false,
      });
    });

    it('shows the button linking to new incidents page with pre-filled incident template when clicked', () => {
      expect(findCreateIncidentBtn().exists()).toBe(true);
      findCreateIncidentBtn().trigger('click');
      expect(mergeUrlParams).toHaveBeenCalledWith(
        { issuable_template: incidentTemplateName, 'issue[issue_type]': incidentType },
        newIssuePath,
      );
    });

    it('sets button loading on click', async () => {
      findCreateIncidentBtn().vm.$emit('click');
      await nextTick();
      expect(findCreateIncidentBtn().attributes('loading')).toBe('true');
    });

    it("doesn't show the button when list is empty", () => {
      mountComponent({
        data: { incidents: { list: [] }, incidentsCount: {} },
        loading: false,
      });
      expect(findCreateIncidentBtn().exists()).toBe(false);
    });

    it("doesn't show the button when user does not have incident creation permissions", () => {
      mountComponent({
        data: { incidents: { list: mockIncidents }, incidentsCount: {} },
        provide: { canCreateIncident: false },
        loading: false,
      });
      expect(findCreateIncidentBtn().exists()).toBe(false);
    });

    it('should track create new incident button', async () => {
      findCreateIncidentBtn().vm.$emit('click');
      await nextTick();
      expect(Tracking.event).toHaveBeenCalled();
    });
  });

  describe('sorting the incident list by column', () => {
    beforeEach(() => {
      mountComponent({
        data: { incidents: { list: mockIncidents }, incidentsCount },
        loading: false,
      });
    });

    const descSort = 'descending';
    const ascSort = 'ascending';
    const noneSort = 'none';

    it.each`
      description        | selector                   | initialSort | firstSort   | nextSort
      ${'creation date'} | ${TH_CREATED_AT_TEST_ID}   | ${descSort} | ${ascSort}  | ${descSort}
      ${'severity'}      | ${TH_SEVERITY_TEST_ID}     | ${noneSort} | ${descSort} | ${ascSort}
      ${'publish date'}  | ${TH_PUBLISHED_TEST_ID}    | ${noneSort} | ${descSort} | ${ascSort}
      ${'due date'}      | ${TH_INCIDENT_SLA_TEST_ID} | ${noneSort} | ${ascSort}  | ${descSort}
    `(
      'updates sort with new direction when sorting by $description',
      async ({ selector, initialSort, firstSort, nextSort }) => {
        const [[attr, value]] = Object.entries(selector);
        const columnHeader = () => wrapper.find(`[${attr}="${value}"]`);
        expect(columnHeader().attributes('aria-sort')).toBe(initialSort);
        columnHeader().trigger('click');
        await nextTick();
        expect(columnHeader().attributes('aria-sort')).toBe(firstSort);
        columnHeader().trigger('click');
        await nextTick();
        expect(columnHeader().attributes('aria-sort')).toBe(nextSort);
      },
    );
  });

  describe('Snowplow tracking', () => {
    beforeEach(() => {
      mountComponent({
        data: { incidents: { list: mockIncidents }, incidentsCount: {} },
        loading: false,
      });
    });

    it('should track incident list views', () => {
      const { category, action } = trackIncidentListViewsOptions;
      expect(Tracking.event).toHaveBeenCalledWith(category, action);
    });

    it('should track incident creation events', async () => {
      findCreateIncidentBtn().vm.$emit('click');
      await nextTick();
      const { category, action } = trackIncidentCreateNewOptions;
      expect(Tracking.event).toHaveBeenCalledWith(category, action);
    });
  });
});