summaryrefslogtreecommitdiff
path: root/spec/frontend/error_tracking/components/error_details_spec.js
blob: 4273da6c735a8e7df4f1b85832eb6c1eb7e7f25d (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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
import {
  GlButton,
  GlLoadingIcon,
  GlLink,
  GlBadge,
  GlFormInput,
  GlAlert,
  GlSprintf,
} from '@gitlab/ui';
import { shallowMount } from '@vue/test-utils';
import Vue, { nextTick } from 'vue';
import Vuex from 'vuex';
import { severityLevel, severityLevelVariant, errorStatus } from '~/error_tracking/constants';
import ErrorDetails from '~/error_tracking/components/error_details.vue';
import Stacktrace from '~/error_tracking/components/stacktrace.vue';
import {
  trackClickErrorLinkToSentryOptions,
  trackErrorDetailsViewsOptions,
  trackErrorStatusUpdateOptions,
} from '~/error_tracking/utils';
import createFlash from '~/flash';
import { __ } from '~/locale';
import Tracking from '~/tracking';

jest.mock('~/flash');

Vue.use(Vuex);

describe('ErrorDetails', () => {
  let store;
  let wrapper;
  let actions;
  let getters;
  let mocks;
  const externalUrl = 'https://sentry.io/organizations/test-sentry-nk/issues/1/?project=1';

  const findInput = (name) => {
    const inputs = wrapper.findAll(GlFormInput).filter((c) => c.attributes('name') === name);
    return inputs.length ? inputs.at(0) : inputs;
  };

  const findUpdateIgnoreStatusButton = () =>
    wrapper.find('[data-testid="update-ignore-status-btn"]');
  const findUpdateResolveStatusButton = () =>
    wrapper.find('[data-testid="update-resolve-status-btn"]');
  const findExternalUrl = () => wrapper.find('[data-testid="external-url-link"]');
  const findAlert = () => wrapper.find(GlAlert);

  function mountComponent() {
    wrapper = shallowMount(ErrorDetails, {
      stubs: { GlButton, GlSprintf },
      store,
      mocks,
      propsData: {
        issueId: '123',
        projectPath: '/root/gitlab-test',
        listPath: '/error_tracking',
        issueUpdatePath: '/123',
        issueStackTracePath: '/stacktrace',
        projectIssuesPath: '/test-project/issues/',
        csrfToken: 'fakeToken',
      },
    });
  }

  beforeEach(() => {
    actions = {
      startPollingStacktrace: () => {},
      updateIgnoreStatus: jest.fn().mockResolvedValue({}),
      updateResolveStatus: jest.fn().mockResolvedValue({ closed_issue_iid: 1 }),
    };

    getters = {
      sentryUrl: () => 'sentry.io',
      stacktrace: () => [{ context: [1, 2], lineNo: 53, filename: 'index.js' }],
    };

    const state = {
      stacktraceData: {},
      loadingStacktrace: true,
      errorStatus: '',
    };

    store = new Vuex.Store({
      modules: {
        details: {
          namespaced: true,
          actions,
          state,
          getters,
        },
      },
    });

    const query = jest.fn();
    mocks = {
      $apollo: {
        query,
        queries: {
          error: {
            loading: true,
            stopPolling: jest.fn(),
            setOptions: jest.fn(),
          },
        },
      },
    };
  });

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

  describe('loading', () => {
    beforeEach(() => {
      mountComponent();
    });

    it('should show spinner while loading', () => {
      expect(wrapper.find(GlLoadingIcon).exists()).toBe(true);
      expect(wrapper.find(GlLink).exists()).toBe(false);
      expect(wrapper.find(Stacktrace).exists()).toBe(false);
    });
  });

  describe('sentry response timeout', () => {
    const initTime = 300000;
    const endTime = initTime + 10000;

    beforeEach(() => {
      mocks.$apollo.queries.error.loading = false;
      jest.spyOn(Date, 'now').mockReturnValue(initTime);
      mountComponent();
    });

    it('when before timeout, still shows loading', async () => {
      Date.now.mockReturnValue(endTime - 1);

      wrapper.vm.onNoApolloResult();

      await nextTick();
      expect(wrapper.find(GlLoadingIcon).exists()).toBe(true);
      expect(createFlash).not.toHaveBeenCalled();
      expect(mocks.$apollo.queries.error.stopPolling).not.toHaveBeenCalled();
    });

    it('when timeout is hit and no apollo result, stops loading and shows flash', async () => {
      Date.now.mockReturnValue(endTime + 1);

      wrapper.vm.onNoApolloResult();

      await nextTick();
      expect(wrapper.find(GlLoadingIcon).exists()).toBe(false);
      expect(wrapper.find(GlLink).exists()).toBe(false);
      expect(createFlash).toHaveBeenCalledWith({
        message: 'Could not connect to Sentry. Refresh the page to try again.',
        type: 'warning',
      });
      expect(mocks.$apollo.queries.error.stopPolling).toHaveBeenCalled();
    });
  });

  describe('Error details', () => {
    beforeEach(() => {
      mocks.$apollo.queries.error.loading = false;
      mountComponent();
      // setData usage is discouraged. See https://gitlab.com/groups/gitlab-org/-/epics/7330 for details
      // eslint-disable-next-line no-restricted-syntax
      wrapper.setData({
        error: {
          id: 'gid://gitlab/Gitlab::ErrorTracking::DetailedError/129381',
          sentryId: 129381,
          title: 'Issue title',
          externalUrl: 'http://sentry.gitlab.net/gitlab',
          firstSeen: '2017-05-26T13:32:48Z',
          lastSeen: '2018-05-26T13:32:48Z',
          count: 12,
          userCount: 2,
        },
        stacktraceData: {
          date_received: '2020-05-20',
        },
      });
    });

    it('should show Sentry error details without stacktrace', () => {
      expect(wrapper.find(GlLink).exists()).toBe(true);
      expect(wrapper.find(GlLoadingIcon).exists()).toBe(true);
      expect(wrapper.find(Stacktrace).exists()).toBe(false);
      expect(wrapper.find(GlBadge).exists()).toBe(false);
      expect(wrapper.findAll(GlButton)).toHaveLength(3);
    });

    describe('unsafe chars for culprit field', () => {
      const findReportedText = () => wrapper.find('[data-qa-selector="reported_text"]');
      const culprit = '<script>console.log("surprise!")</script>';
      beforeEach(() => {
        store.state.details.loadingStacktrace = false;
        // setData usage is discouraged. See https://gitlab.com/groups/gitlab-org/-/epics/7330 for details
        // eslint-disable-next-line no-restricted-syntax
        wrapper.setData({
          error: {
            culprit,
          },
        });
      });

      it('should not convert interpolated text to html entities', () => {
        expect(findReportedText().findAll('script').length).toEqual(0);
        expect(findReportedText().findAll('strong').length).toEqual(1);
      });

      it('should render text instead of converting to html entities', () => {
        expect(findReportedText().text()).toContain(culprit);
      });
    });

    describe('Badges', () => {
      it('should show language and error level badges', async () => {
        // setData usage is discouraged. See https://gitlab.com/groups/gitlab-org/-/epics/7330 for details
        // eslint-disable-next-line no-restricted-syntax
        wrapper.setData({
          error: {
            tags: { level: 'error', logger: 'ruby' },
          },
        });
        await nextTick();
        expect(wrapper.findAll(GlBadge).length).toBe(2);
      });

      it('should NOT show the badge if the tag is not present', async () => {
        // setData usage is discouraged. See https://gitlab.com/groups/gitlab-org/-/epics/7330 for details
        // eslint-disable-next-line no-restricted-syntax
        wrapper.setData({
          error: {
            tags: { level: 'error' },
          },
        });
        await nextTick();
        expect(wrapper.findAll(GlBadge).length).toBe(1);
      });

      it.each(Object.keys(severityLevel))(
        'should set correct severity level variant for %s badge',
        async (level) => {
          // setData usage is discouraged. See https://gitlab.com/groups/gitlab-org/-/epics/7330 for details
          // eslint-disable-next-line no-restricted-syntax
          wrapper.setData({
            error: {
              tags: { level: severityLevel[level] },
            },
          });
          await nextTick();
          expect(wrapper.find(GlBadge).props('variant')).toEqual(
            severityLevelVariant[severityLevel[level]],
          );
        },
      );

      it('should fallback for ERROR severityLevelVariant when severityLevel is unknown', async () => {
        // setData usage is discouraged. See https://gitlab.com/groups/gitlab-org/-/epics/7330 for details
        // eslint-disable-next-line no-restricted-syntax
        wrapper.setData({
          error: {
            tags: { level: 'someNewErrorLevel' },
          },
        });
        await nextTick();
        expect(wrapper.find(GlBadge).props('variant')).toEqual(
          severityLevelVariant[severityLevel.ERROR],
        );
      });
    });

    describe('Stacktrace', () => {
      it('should show stacktrace', async () => {
        store.state.details.loadingStacktrace = false;
        await nextTick();
        expect(wrapper.find(GlLoadingIcon).exists()).toBe(false);
        expect(wrapper.find(Stacktrace).exists()).toBe(true);
        expect(findAlert().exists()).toBe(false);
      });

      it('should NOT show stacktrace if no entries and show Alert message', async () => {
        store.state.details.loadingStacktrace = false;
        store.getters = { 'details/sentryUrl': () => 'sentry.io', 'details/stacktrace': () => [] };
        await nextTick();
        expect(wrapper.find(GlLoadingIcon).exists()).toBe(false);
        expect(wrapper.find(Stacktrace).exists()).toBe(false);
        expect(findAlert().text()).toBe('No stack trace for this error');
      });
    });

    describe('When a user clicks the create issue button', () => {
      it('should send sentry_issue_identifier', () => {
        const sentryErrorIdInput = findInput(
          'issue[sentry_issue_attributes][sentry_issue_identifier]',
        );
        expect(sentryErrorIdInput.attributes('value')).toBe('129381');
      });

      it('should set the form values with title and description', () => {
        const csrfTokenInput = findInput('authenticity_token');
        const issueTitleInput = findInput('issue[title]');
        const issueDescriptionInput = wrapper.find('input[name="issue[description]"]');
        expect(csrfTokenInput.attributes('value')).toBe('fakeToken');
        expect(issueTitleInput.attributes('value')).toContain(wrapper.vm.issueTitle);
        expect(issueDescriptionInput.attributes('value')).toContain(wrapper.vm.issueDescription);
      });

      it('should submit the form', () => {
        window.HTMLFormElement.prototype.submit = () => {};
        const submitSpy = jest.spyOn(wrapper.vm.$refs.sentryIssueForm, 'submit');
        wrapper.find('[data-qa-selector="create_issue_button"]').vm.$emit('click');
        expect(submitSpy).toHaveBeenCalled();
        submitSpy.mockRestore();
      });
    });

    describe('Status update', () => {
      afterEach(() => {
        actions.updateIgnoreStatus.mockClear();
        actions.updateResolveStatus.mockClear();
      });

      describe('when error is unresolved', () => {
        beforeEach(async () => {
          store.state.details.errorStatus = errorStatus.UNRESOLVED;

          await nextTick();
        });

        it('displays Ignore and Resolve buttons', () => {
          expect(findUpdateIgnoreStatusButton().text()).toBe(__('Ignore'));
          expect(findUpdateResolveStatusButton().text()).toBe(__('Resolve'));
        });

        it('marks error as ignored when ignore button is clicked', () => {
          findUpdateIgnoreStatusButton().vm.$emit('click');
          expect(actions.updateIgnoreStatus.mock.calls[0][1]).toEqual(
            expect.objectContaining({ status: errorStatus.IGNORED }),
          );
        });

        it('marks error as resolved when resolve button is clicked', () => {
          findUpdateResolveStatusButton().vm.$emit('click');
          expect(actions.updateResolveStatus.mock.calls[0][1]).toEqual(
            expect.objectContaining({ status: errorStatus.RESOLVED }),
          );
        });
      });

      describe('when error is ignored', () => {
        beforeEach(async () => {
          store.state.details.errorStatus = errorStatus.IGNORED;

          await nextTick();
        });

        it('displays Undo Ignore and Resolve buttons', () => {
          expect(findUpdateIgnoreStatusButton().text()).toBe(__('Undo ignore'));
          expect(findUpdateResolveStatusButton().text()).toBe(__('Resolve'));
        });

        it('marks error as unresolved when ignore button is clicked', () => {
          findUpdateIgnoreStatusButton().vm.$emit('click');
          expect(actions.updateIgnoreStatus.mock.calls[0][1]).toEqual(
            expect.objectContaining({ status: errorStatus.UNRESOLVED }),
          );
        });

        it('marks error as resolved when resolve button is clicked', () => {
          findUpdateResolveStatusButton().vm.$emit('click');
          expect(actions.updateResolveStatus.mock.calls[0][1]).toEqual(
            expect.objectContaining({ status: errorStatus.RESOLVED }),
          );
        });
      });

      describe('when error is resolved', () => {
        beforeEach(async () => {
          store.state.details.errorStatus = errorStatus.RESOLVED;

          await nextTick();
        });

        it('displays Ignore and Unresolve buttons', () => {
          expect(findUpdateIgnoreStatusButton().text()).toBe(__('Ignore'));
          expect(findUpdateResolveStatusButton().text()).toBe(__('Unresolve'));
        });

        it('marks error as ignored when ignore button is clicked', () => {
          findUpdateIgnoreStatusButton().vm.$emit('click');
          expect(actions.updateIgnoreStatus.mock.calls[0][1]).toEqual(
            expect.objectContaining({ status: errorStatus.IGNORED }),
          );
        });

        it('marks error as unresolved when unresolve button is clicked', () => {
          findUpdateResolveStatusButton().vm.$emit('click');
          expect(actions.updateResolveStatus.mock.calls[0][1]).toEqual(
            expect.objectContaining({ status: errorStatus.UNRESOLVED }),
          );
        });

        it('should show alert with closed issueId', async () => {
          const closedIssueId = 123;
          // setData usage is discouraged. See https://gitlab.com/groups/gitlab-org/-/epics/7330 for details
          // eslint-disable-next-line no-restricted-syntax
          wrapper.setData({
            isAlertVisible: true,
            closedIssueId,
          });

          await nextTick();
          expect(findAlert().exists()).toBe(true);
          expect(findAlert().text()).toContain(`#${closedIssueId}`);
        });
      });
    });

    describe('GitLab issue link', () => {
      const gitlabIssuePath = 'https://gitlab.example.com/issues/1';
      const findGitLabLink = () => wrapper.find(`[href="${gitlabIssuePath}"]`);
      const findCreateIssueButton = () => wrapper.find('[data-qa-selector="create_issue_button"]');
      const findViewIssueButton = () => wrapper.find('[data-qa-selector="view_issue_button"]');

      describe('is present', () => {
        beforeEach(() => {
          // setData usage is discouraged. See https://gitlab.com/groups/gitlab-org/-/epics/7330 for details
          // eslint-disable-next-line no-restricted-syntax
          wrapper.setData({
            error: {
              gitlabIssuePath,
            },
          });
        });

        it('should display the View issue button', () => {
          expect(findViewIssueButton().exists()).toBe(true);
        });

        it('should display the issue link', () => {
          expect(findGitLabLink().exists()).toBe(true);
        });

        it('should not display a create issue button', () => {
          expect(findCreateIssueButton().exists()).toBe(false);
        });
      });

      describe('is not present', () => {
        beforeEach(() => {
          // setData usage is discouraged. See https://gitlab.com/groups/gitlab-org/-/epics/7330 for details
          // eslint-disable-next-line no-restricted-syntax
          wrapper.setData({
            error: {
              gitlabIssuePath: null,
            },
          });
        });

        it('should not display the View issue button', () => {
          expect(findViewIssueButton().exists()).toBe(false);
        });

        it('should not display an issue link', () => {
          expect(findGitLabLink().exists()).toBe(false);
        });

        it('should display the create issue button', () => {
          expect(findCreateIssueButton().exists()).toBe(true);
        });
      });
    });

    describe('GitLab commit link', () => {
      const gitlabCommit = '7975be0116940bf2ad4321f79d02a55c5f7779aa';
      const gitlabCommitPath =
        '/gitlab-org/gitlab-test/commit/7975be0116940bf2ad4321f79d02a55c5f7779aa';
      const findGitLabCommitLink = () => wrapper.find(`[href$="${gitlabCommitPath}"]`);

      it('should display a link', async () => {
        mocks.$apollo.queries.error.loading = false;
        // setData usage is discouraged. See https://gitlab.com/groups/gitlab-org/-/epics/7330 for details
        // eslint-disable-next-line no-restricted-syntax
        wrapper.setData({
          error: {
            gitlabCommit,
            gitlabCommitPath,
          },
        });
        await nextTick();
        expect(findGitLabCommitLink().exists()).toBe(true);
      });

      it('should not display a link', async () => {
        mocks.$apollo.queries.error.loading = false;
        // setData usage is discouraged. See https://gitlab.com/groups/gitlab-org/-/epics/7330 for details
        // eslint-disable-next-line no-restricted-syntax
        wrapper.setData({
          error: {
            gitlabCommit: null,
          },
        });
        await nextTick();
        expect(findGitLabCommitLink().exists()).toBe(false);
      });
    });

    describe('Release links', () => {
      const firstReleaseVersion = '7975be01';
      const firstCommitLink = '/gitlab/-/commit/7975be01';
      const firstReleaseLink = '/sentry/releases/7975be01';
      const findFirstCommitLink = () => wrapper.find(`[href$="${firstCommitLink}"]`);
      const findFirstReleaseLink = () => wrapper.find(`[href$="${firstReleaseLink}"]`);

      const lastReleaseVersion = '6ca5a5c1';
      const lastCommitLink = '/gitlab/-/commit/6ca5a5c1';
      const lastReleaseLink = '/sentry/releases/6ca5a5c1';
      const findLastCommitLink = () => wrapper.find(`[href$="${lastCommitLink}"]`);
      const findLastReleaseLink = () => wrapper.find(`[href$="${lastReleaseLink}"]`);

      it('should display links to Sentry', async () => {
        mocks.$apollo.queries.error.loading = false;
        // setData usage is discouraged. See https://gitlab.com/groups/gitlab-org/-/epics/7330 for details
        // eslint-disable-next-line no-restricted-syntax
        await wrapper.setData({
          error: {
            firstReleaseVersion,
            lastReleaseVersion,
            externalBaseUrl: '/sentry',
          },
        });

        expect(findFirstReleaseLink().exists()).toBe(true);
        expect(findLastReleaseLink().exists()).toBe(true);
        expect(findFirstCommitLink().exists()).toBe(false);
        expect(findLastCommitLink().exists()).toBe(false);
      });

      it('should display links to GitLab when integrated', async () => {
        mocks.$apollo.queries.error.loading = false;
        // setData usage is discouraged. See https://gitlab.com/groups/gitlab-org/-/epics/7330 for details
        // eslint-disable-next-line no-restricted-syntax
        await wrapper.setData({
          error: {
            firstReleaseVersion,
            lastReleaseVersion,
            integrated: true,
            externalBaseUrl: '/gitlab',
          },
        });

        expect(findFirstCommitLink().exists()).toBe(true);
        expect(findLastCommitLink().exists()).toBe(true);
        expect(findFirstReleaseLink().exists()).toBe(false);
        expect(findLastReleaseLink().exists()).toBe(false);
      });
    });
  });

  describe('Snowplow tracking', () => {
    beforeEach(() => {
      jest.spyOn(Tracking, 'event');
      mocks.$apollo.queries.error.loading = false;
      mountComponent();
      // setData usage is discouraged. See https://gitlab.com/groups/gitlab-org/-/epics/7330 for details
      // eslint-disable-next-line no-restricted-syntax
      wrapper.setData({
        error: { externalUrl },
      });
    });

    it('should track detail page views', () => {
      const { category, action } = trackErrorDetailsViewsOptions;
      expect(Tracking.event).toHaveBeenCalledWith(category, action);
    });

    it('should track IGNORE status update', async () => {
      Tracking.event.mockClear();
      await findUpdateIgnoreStatusButton().trigger('click');
      const { category, action } = trackErrorStatusUpdateOptions('ignored');
      expect(Tracking.event).toHaveBeenCalledWith(category, action);
    });

    it('should track RESOLVE status update', async () => {
      Tracking.event.mockClear();
      await findUpdateResolveStatusButton().trigger('click');
      const { category, action } = trackErrorStatusUpdateOptions('resolved');
      expect(Tracking.event).toHaveBeenCalledWith(category, action);
    });

    it('should track external Sentry link views', async () => {
      Tracking.event.mockClear();
      await findExternalUrl().trigger('click');
      const { category, action, label, property } = trackClickErrorLinkToSentryOptions(externalUrl);
      expect(Tracking.event).toHaveBeenCalledWith(category, action, { label, property });
    });
  });
});