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

client_spec.js « observability « frontend « spec - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: e3196861659b9b303a6bd9601ce30d2f1371be23 (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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
import MockAdapter from 'axios-mock-adapter';
import * as Sentry from '~/sentry/sentry_browser_wrapper';
import { buildClient } from '~/observability/client';
import axios from '~/lib/utils/axios_utils';
import { logError } from '~/lib/logger';
import { DEFAULT_SORTING_OPTION, SORTING_OPTIONS } from '~/observability/constants';

jest.mock('~/lib/utils/axios_utils');
jest.mock('~/sentry/sentry_browser_wrapper');
jest.mock('~/lib/logger');

describe('buildClient', () => {
  let client;
  let axiosMock;

  const tracingUrl = 'https://example.com/tracing';
  const tracingAnalyticsUrl = 'https://example.com/tracing/analytics';
  const provisioningUrl = 'https://example.com/provisioning';
  const servicesUrl = 'https://example.com/services';
  const operationsUrl = 'https://example.com/services/$SERVICE_NAME$/operations';
  const metricsUrl = 'https://example.com/metrics';
  const metricsSearchUrl = 'https://example.com/metrics/search';
  const FETCHING_TRACES_ERROR = 'traces are missing/invalid in the response';

  const apiConfig = {
    tracingUrl,
    tracingAnalyticsUrl,
    provisioningUrl,
    servicesUrl,
    operationsUrl,
    metricsUrl,
    metricsSearchUrl,
  };

  const getQueryParam = () => decodeURIComponent(axios.get.mock.calls[0][1].params.toString());

  beforeEach(() => {
    axiosMock = new MockAdapter(axios);
    jest.spyOn(axios, 'get');

    client = buildClient(apiConfig);
  });

  afterEach(() => {
    axiosMock.restore();
  });

  const expectErrorToBeReported = (e) => {
    expect(Sentry.captureException).toHaveBeenCalledWith(e);
    expect(logError).toHaveBeenCalledWith(e);
  };

  describe('buildClient', () => {
    it('throws is option is missing', () => {
      expect(() => buildClient()).toThrow(new Error('No options object provided'));
    });
    it.each(Object.keys(apiConfig))('throws if %s is missing', (param) => {
      const e = new Error(`${param} param must be a string`);

      expect(() =>
        buildClient({
          ...apiConfig,
          [param]: undefined,
        }),
      ).toThrow(e);
    });
  });

  describe('isObservabilityEnabled', () => {
    it('returns true if requests succeedes', async () => {
      axiosMock.onGet(provisioningUrl).reply(200, {
        status: 'ready',
      });

      const enabled = await client.isObservabilityEnabled();

      expect(enabled).toBe(true);
    });

    it('returns false if response is 404', async () => {
      axiosMock.onGet(provisioningUrl).reply(404);

      const enabled = await client.isObservabilityEnabled();

      expect(enabled).toBe(false);
    });

    // we currently ignore the 'status' payload and just check if the request was successful
    // We might improve this as part of https://gitlab.com/gitlab-org/opstrace/opstrace/-/issues/2315
    it('returns true for any status', async () => {
      axiosMock.onGet(provisioningUrl).reply(200, {
        status: 'not ready',
      });

      const enabled = await client.isObservabilityEnabled();

      expect(enabled).toBe(true);
    });

    it('throws in case of any non-404 error', async () => {
      axiosMock.onGet(provisioningUrl).reply(500);

      const e = 'Request failed with status code 500';
      await expect(client.isObservabilityEnabled()).rejects.toThrow(e);
      expectErrorToBeReported(new Error(e));
    });

    it('throws in case of unexpected response', async () => {
      axiosMock.onGet(provisioningUrl).reply(200, {});

      const e = 'Failed to check provisioning';
      await expect(client.isObservabilityEnabled()).rejects.toThrow(e);
      expectErrorToBeReported(new Error(e));
    });
  });

  describe('enableObservability', () => {
    it('makes a PUT request to the provisioning URL', async () => {
      let putConfig;
      axiosMock.onPut(provisioningUrl).reply((config) => {
        putConfig = config;
        return [200];
      });

      await client.enableObservability();

      expect(putConfig.withCredentials).toBe(true);
    });

    it('reports an error if the req fails', async () => {
      axiosMock.onPut(provisioningUrl).reply(401);

      const e = 'Request failed with status code 401';

      await expect(client.enableObservability()).rejects.toThrow(e);
      expectErrorToBeReported(new Error(e));
    });
  });

  describe('fetchTrace', () => {
    it('fetches the trace from the tracing URL', async () => {
      const mockTrace = {
        trace_id: 'trace-1',
        duration_nano: 3000,
        spans: [{ duration_nano: 1000 }, { duration_nano: 2000 }],
      };
      axiosMock.onGet(`${tracingUrl}/trace-1`).reply(200, mockTrace);

      const result = await client.fetchTrace('trace-1');

      expect(axios.get).toHaveBeenCalledTimes(1);
      expect(axios.get).toHaveBeenCalledWith(`${tracingUrl}/trace-1`, {
        withCredentials: true,
      });
      expect(result).toEqual(mockTrace);
    });

    it('rejects if trace id is missing', () => {
      return expect(client.fetchTrace()).rejects.toThrow('traceId is required.');
    });
  });

  describe('fetchTraces', () => {
    it('fetches traces from the tracing URL', async () => {
      const mockResponse = {
        traces: [
          {
            trace_id: 'trace-1',
            duration_nano: 3000,
            spans: [{ duration_nano: 1000 }, { duration_nano: 2000 }],
          },
          { trace_id: 'trace-2', duration_nano: 3000, spans: [{ duration_nano: 2000 }] },
        ],
      };

      axiosMock.onGet(tracingUrl).reply(200, mockResponse);

      const result = await client.fetchTraces();

      expect(axios.get).toHaveBeenCalledTimes(1);
      expect(axios.get).toHaveBeenCalledWith(tracingUrl, {
        withCredentials: true,
        params: expect.any(URLSearchParams),
      });
      expect(result).toEqual(mockResponse);
    });

    it('rejects if traces are missing', async () => {
      axiosMock.onGet(tracingUrl).reply(200, {});

      await expect(client.fetchTraces()).rejects.toThrow(FETCHING_TRACES_ERROR);
      expectErrorToBeReported(new Error(FETCHING_TRACES_ERROR));
    });

    it('rejects if traces are invalid', async () => {
      axiosMock.onGet(tracingUrl).reply(200, { traces: 'invalid' });

      await expect(client.fetchTraces()).rejects.toThrow(FETCHING_TRACES_ERROR);
      expectErrorToBeReported(new Error(FETCHING_TRACES_ERROR));
    });

    describe('sort order', () => {
      beforeEach(() => {
        axiosMock.onGet(tracingUrl).reply(200, {
          traces: [],
        });
      });
      it('appends sort param if specified', async () => {
        await client.fetchTraces({ sortBy: SORTING_OPTIONS.DURATION_DESC });

        expect(getQueryParam()).toBe(`sort=${SORTING_OPTIONS.DURATION_DESC}`);
      });

      it('defaults to DEFAULT_SORTING_OPTION if no sortBy param is specified', async () => {
        await client.fetchTraces();

        expect(getQueryParam()).toBe(`sort=${DEFAULT_SORTING_OPTION}`);
      });

      it('defaults to timestamp_desc if sortBy param is not an accepted value', async () => {
        await client.fetchTraces({ sortBy: 'foo-bar' });

        expect(getQueryParam()).toBe(`sort=${SORTING_OPTIONS.TIMESTAMP_DESC}`);
      });
    });

    describe('query filter', () => {
      beforeEach(() => {
        axiosMock.onGet(tracingUrl).reply(200, {
          traces: [],
        });
      });

      it('does not set any query param without filters', async () => {
        await client.fetchTraces();

        expect(getQueryParam()).toBe(`sort=${SORTING_OPTIONS.TIMESTAMP_DESC}`);
      });

      it('appends page_token if specified', async () => {
        await client.fetchTraces({ pageToken: 'page-token' });

        expect(getQueryParam()).toContain('page_token=page-token');
      });

      it('appends page_size if specified', async () => {
        await client.fetchTraces({ pageSize: 10 });

        expect(getQueryParam()).toContain('page_size=10');
      });

      it('converts filter to proper query params', async () => {
        await client.fetchTraces({
          filters: {
            durationMs: [
              { operator: '>', value: '100' },
              { operator: '<', value: '1000' },
            ],
            operation: [
              { operator: '=', value: 'op' },
              { operator: '!=', value: 'not-op' },
            ],
            service: [
              { operator: '=', value: 'service' },
              { operator: '!=', value: 'not-service' },
            ],
            period: [{ operator: '=', value: '5m' }],
            status: [
              { operator: '=', value: 'ok' },
              { operator: '!=', value: 'error' },
            ],
            traceId: [
              { operator: '=', value: 'trace-id' },
              { operator: '!=', value: 'not-trace-id' },
            ],
            attribute: [{ operator: '=', value: 'name1=value1' }],
          },
        });
        expect(getQueryParam()).toContain(
          'gt[duration_nano]=100000000&lt[duration_nano]=1000000000' +
            '&operation=op&not[operation]=not-op' +
            '&service_name=service&not[service_name]=not-service' +
            '&period=5m' +
            '&trace_id=trace-id&not[trace_id]=not-trace-id' +
            '&attr_name=name1&attr_value=value1' +
            '&status=ok&not[status]=error',
        );
      });
      describe('date range time filter', () => {
        it('handles custom date range period filter', async () => {
          await client.fetchTraces({
            filters: {
              period: [{ operator: '=', value: '2023-01-01 - 2023-02-01' }],
            },
          });
          expect(getQueryParam()).not.toContain('period=');
          expect(getQueryParam()).toContain(
            'start_time=2023-01-01T00:00:00.000Z&end_time=2023-02-01T00:00:00.000Z',
          );
        });

        it.each([
          'invalid - 2023-02-01',
          '2023-02-01 - invalid',
          'invalid - invalid',
          '2023-01-01 / 2023-02-01',
          '2023-01-01 2023-02-01',
          '2023-01-01 - 2023-02-01 - 2023-02-01',
        ])('ignore invalid values', async (val) => {
          await client.fetchTraces({
            filters: {
              period: [{ operator: '=', value: val }],
            },
          });

          expect(getQueryParam()).not.toContain('start_time=');
          expect(getQueryParam()).not.toContain('end_time=');
          expect(getQueryParam()).not.toContain('period=');
        });
      });

      it('handles repeated params', async () => {
        await client.fetchTraces({
          filters: {
            operation: [
              { operator: '=', value: 'op' },
              { operator: '=', value: 'op2' },
            ],
          },
        });
        expect(getQueryParam()).toContain('operation=op&operation=op2');
      });

      it('ignores unsupported filters', async () => {
        await client.fetchTraces({
          filters: {
            unsupportedFilter: [{ operator: '=', value: 'foo' }],
          },
        });

        expect(getQueryParam()).toBe(`sort=${SORTING_OPTIONS.TIMESTAMP_DESC}`);
      });

      it('ignores empty filters', async () => {
        await client.fetchTraces({
          filters: {
            durationMs: null,
            traceId: undefined,
          },
        });

        expect(getQueryParam()).toBe(`sort=${SORTING_OPTIONS.TIMESTAMP_DESC}`);
      });

      it('ignores non-array filters', async () => {
        await client.fetchTraces({
          filters: {
            traceId: { operator: '=', value: 'foo' },
          },
        });

        expect(getQueryParam()).toBe(`sort=${SORTING_OPTIONS.TIMESTAMP_DESC}`);
      });

      it('ignores unsupported operators', async () => {
        await client.fetchTraces({
          filters: {
            durationMs: [
              { operator: '*', value: 'foo' },
              { operator: '=', value: 'foo' },
              { operator: '!=', value: 'foo' },
            ],
            operation: [
              { operator: '>', value: 'foo' },
              { operator: '<', value: 'foo' },
            ],
            service: [
              { operator: '>', value: 'foo' },
              { operator: '<', value: 'foo' },
            ],
            period: [{ operator: '!=', value: 'foo' }],
            traceId: [
              { operator: '>', value: 'foo' },
              { operator: '<', value: 'foo' },
            ],
          },
        });

        expect(getQueryParam()).toBe(`sort=${SORTING_OPTIONS.TIMESTAMP_DESC}`);
      });
    });
  });

  describe('fetchTracesAnalytics', () => {
    it('fetches analytics from the tracesAnalytics URL', async () => {
      const mockResponse = {
        results: [
          {
            Interval: 1705039800,
            count: 5,
            p90_duration_nano: 50613502867,
            p95_duration_nano: 50613502867,
            p75_duration_nano: 49756727928,
            p50_duration_nano: 41610120929,
            error_count: 324,
            trace_rate: 2.576111111111111,
            error_rate: 0.09,
          },
        ],
      };

      axiosMock.onGet(tracingAnalyticsUrl).reply(200, mockResponse);

      const result = await client.fetchTracesAnalytics();

      expect(axios.get).toHaveBeenCalledTimes(1);
      expect(axios.get).toHaveBeenCalledWith(tracingAnalyticsUrl, {
        withCredentials: true,
        params: expect.any(URLSearchParams),
      });
      expect(result).toEqual(mockResponse.results);
    });

    it('returns empty array if analytics are missing', async () => {
      axiosMock.onGet(tracingAnalyticsUrl).reply(200, {});

      expect(await client.fetchTracesAnalytics()).toEqual([]);
    });

    describe('query filter', () => {
      beforeEach(() => {
        axiosMock.onGet(tracingAnalyticsUrl).reply(200, {
          results: [],
        });
      });

      it('does not set any query param without filters', async () => {
        await client.fetchTracesAnalytics();

        expect(getQueryParam()).toBe(``);
      });

      it('converts filter to proper query params', async () => {
        await client.fetchTracesAnalytics({
          filters: {
            durationMs: [
              { operator: '>', value: '100' },
              { operator: '<', value: '1000' },
            ],
            operation: [
              { operator: '=', value: 'op' },
              { operator: '!=', value: 'not-op' },
            ],
            service: [
              { operator: '=', value: 'service' },
              { operator: '!=', value: 'not-service' },
            ],
            period: [{ operator: '=', value: '5m' }],
            status: [
              { operator: '=', value: 'ok' },
              { operator: '!=', value: 'error' },
            ],
            traceId: [
              { operator: '=', value: 'trace-id' },
              { operator: '!=', value: 'not-trace-id' },
            ],
            attribute: [{ operator: '=', value: 'name1=value1' }],
          },
        });
        expect(getQueryParam()).toContain(
          'gt[duration_nano]=100000000&lt[duration_nano]=1000000000' +
            '&operation=op&not[operation]=not-op' +
            '&service_name=service&not[service_name]=not-service' +
            '&period=5m' +
            '&trace_id=trace-id&not[trace_id]=not-trace-id' +
            '&attr_name=name1&attr_value=value1' +
            '&status=ok&not[status]=error',
        );
      });
      describe('date range time filter', () => {
        it('handles custom date range period filter', async () => {
          await client.fetchTracesAnalytics({
            filters: {
              period: [{ operator: '=', value: '2023-01-01 - 2023-02-01' }],
            },
          });
          expect(getQueryParam()).not.toContain('period=');
          expect(getQueryParam()).toContain(
            'start_time=2023-01-01T00:00:00.000Z&end_time=2023-02-01T00:00:00.000Z',
          );
        });

        it.each([
          'invalid - 2023-02-01',
          '2023-02-01 - invalid',
          'invalid - invalid',
          '2023-01-01 / 2023-02-01',
          '2023-01-01 2023-02-01',
          '2023-01-01 - 2023-02-01 - 2023-02-01',
        ])('ignore invalid values', async (val) => {
          await client.fetchTracesAnalytics({
            filters: {
              period: [{ operator: '=', value: val }],
            },
          });

          expect(getQueryParam()).not.toContain('start_time=');
          expect(getQueryParam()).not.toContain('end_time=');
          expect(getQueryParam()).not.toContain('period=');
        });
      });

      it('handles repeated params', async () => {
        await client.fetchTracesAnalytics({
          filters: {
            operation: [
              { operator: '=', value: 'op' },
              { operator: '=', value: 'op2' },
            ],
          },
        });
        expect(getQueryParam()).toContain('operation=op&operation=op2');
      });

      it('ignores unsupported filters', async () => {
        await client.fetchTracesAnalytics({
          filters: {
            unsupportedFilter: [{ operator: '=', value: 'foo' }],
          },
        });

        expect(getQueryParam()).toBe(``);
      });

      it('ignores empty filters', async () => {
        await client.fetchTracesAnalytics({
          filters: {
            durationMs: null,
          },
        });

        expect(getQueryParam()).toBe(``);
      });

      it('ignores non-array filters', async () => {
        await client.fetchTracesAnalytics({
          filters: {
            traceId: { operator: '=', value: 'foo' },
          },
        });

        expect(getQueryParam()).toBe(``);
      });

      it('ignores unsupported operators', async () => {
        await client.fetchTracesAnalytics({
          filters: {
            durationMs: [
              { operator: '*', value: 'foo' },
              { operator: '=', value: 'foo' },
              { operator: '!=', value: 'foo' },
            ],
            operation: [
              { operator: '>', value: 'foo' },
              { operator: '<', value: 'foo' },
            ],
            service: [
              { operator: '>', value: 'foo' },
              { operator: '<', value: 'foo' },
            ],
            period: [{ operator: '!=', value: 'foo' }],
            traceId: [
              { operator: '>', value: 'foo' },
              { operator: '<', value: 'foo' },
            ],
          },
        });

        expect(getQueryParam()).toBe(``);
      });
    });
  });

  describe('fetchServices', () => {
    it('fetches services from the services URL', async () => {
      const mockResponse = {
        services: [{ name: 'service-1' }, { name: 'service-2' }],
      };

      axiosMock.onGet(servicesUrl).reply(200, mockResponse);

      const result = await client.fetchServices();

      expect(axios.get).toHaveBeenCalledTimes(1);
      expect(axios.get).toHaveBeenCalledWith(servicesUrl, {
        withCredentials: true,
      });
      expect(result).toEqual(mockResponse.services);
    });

    it('rejects if services are missing', async () => {
      axiosMock.onGet(servicesUrl).reply(200, {});

      const e = 'failed to fetch services. invalid response';
      await expect(client.fetchServices()).rejects.toThrow(e);
      expectErrorToBeReported(new Error(e));
    });
  });

  describe('fetchOperations', () => {
    const serviceName = 'test-service';
    const parsedOperationsUrl = `https://example.com/services/${serviceName}/operations`;

    it('fetches operations from the operations URL', async () => {
      const mockResponse = {
        operations: [{ name: 'operation-1' }, { name: 'operation-2' }],
      };

      axiosMock.onGet(parsedOperationsUrl).reply(200, mockResponse);

      const result = await client.fetchOperations(serviceName);

      expect(axios.get).toHaveBeenCalledTimes(1);
      expect(axios.get).toHaveBeenCalledWith(parsedOperationsUrl, {
        withCredentials: true,
      });
      expect(result).toEqual(mockResponse.operations);
    });

    it('rejects if serviceName is missing', async () => {
      const e = 'fetchOperations() - serviceName is required.';
      await expect(client.fetchOperations()).rejects.toThrow(e);
      expectErrorToBeReported(new Error(e));
    });

    it('rejects if operationUrl does not contain $SERVICE_NAME$', async () => {
      client = buildClient({
        ...apiConfig,
        operationsUrl: 'something',
      });
      const e = 'fetchOperations() - operationsUrl must contain $SERVICE_NAME$';
      await expect(client.fetchOperations(serviceName)).rejects.toThrow(e);
      expectErrorToBeReported(new Error(e));
    });

    it('rejects if operations are missing', async () => {
      axiosMock.onGet(parsedOperationsUrl).reply(200, {});

      const e = 'failed to fetch operations. invalid response';
      await expect(client.fetchOperations(serviceName)).rejects.toThrow(e);
      expectErrorToBeReported(new Error(e));
    });
  });

  describe('fetchMetrics', () => {
    const FETCHING_METRICS_ERROR = 'metrics are missing/invalid in the response';

    it('fetches metrics from the metrics URL', async () => {
      const mockResponse = {
        metrics: [
          { name: 'metric A', description: 'a counter metric called A', type: 'COUNTER' },
          { name: 'metric B', description: 'a gauge metric called B', type: 'GAUGE' },
        ],
      };

      axiosMock.onGet(metricsUrl).reply(200, mockResponse);

      const result = await client.fetchMetrics();

      expect(axios.get).toHaveBeenCalledTimes(1);
      expect(axios.get).toHaveBeenCalledWith(metricsUrl, {
        withCredentials: true,
        params: expect.any(URLSearchParams),
      });
      expect(result).toEqual(mockResponse);
    });

    describe('query filter', () => {
      beforeEach(() => {
        axiosMock.onGet(metricsUrl).reply(200, {
          metrics: [],
        });
      });

      it('does not set any query param without filters', async () => {
        await client.fetchMetrics();

        expect(getQueryParam()).toBe('');
      });

      it('sets the start_with query param based on the search filter', async () => {
        await client.fetchMetrics({
          filters: { search: [{ value: 'foo' }, { value: 'bar' }, { value: ' ' }] },
        });
        expect(getQueryParam()).toBe('starts_with=foo+bar');
      });

      it('ignores empty search', async () => {
        await client.fetchMetrics({
          filters: {
            search: [{ value: ' ' }, { value: '' }, { value: null }, { value: undefined }],
          },
        });
        expect(getQueryParam()).toBe('');
      });

      it('ignores unsupported filters', async () => {
        await client.fetchMetrics({
          filters: {
            unsupportedFilter: [{ operator: '=', value: 'foo' }],
          },
        });

        expect(getQueryParam()).toBe('');
      });

      it('ignores non-array search filters', async () => {
        await client.fetchMetrics({
          filters: {
            search: { value: 'foo' },
          },
        });

        expect(getQueryParam()).toBe('');
      });

      it('adds the search limit param if specified with the search filter', async () => {
        await client.fetchMetrics({
          filters: { search: [{ value: 'foo' }] },
          limit: 50,
        });
        expect(getQueryParam()).toBe('starts_with=foo&limit=50');
      });

      it('does not add the search limit param if the search filter is missing', async () => {
        await client.fetchMetrics({
          limit: 50,
        });
        expect(getQueryParam()).toBe('');
      });

      it('does not add the search limit param if the search filter is empty', async () => {
        await client.fetchMetrics({
          limit: 50,
          search: [{ value: ' ' }, { value: '' }, { value: null }, { value: undefined }],
        });
        expect(getQueryParam()).toBe('');
      });
    });

    it('rejects if metrics are missing', async () => {
      axiosMock.onGet(metricsUrl).reply(200, {});

      await expect(client.fetchMetrics()).rejects.toThrow(FETCHING_METRICS_ERROR);
      expectErrorToBeReported(new Error(FETCHING_METRICS_ERROR));
    });

    it('rejects if metrics are invalid', async () => {
      axiosMock.onGet(metricsUrl).reply(200, { traces: 'invalid' });

      await expect(client.fetchMetrics()).rejects.toThrow(FETCHING_METRICS_ERROR);
      expectErrorToBeReported(new Error(FETCHING_METRICS_ERROR));
    });
  });

  describe('fetchMetric', () => {
    it('fetches the metric from the API', async () => {
      const data = { results: [] };
      axiosMock.onGet(metricsSearchUrl).reply(200, data);

      const result = await client.fetchMetric('name', 'type');

      expect(axios.get).toHaveBeenCalledTimes(1);
      expect(axios.get).toHaveBeenCalledWith(metricsSearchUrl, {
        withCredentials: true,
        params: new URLSearchParams({ mname: 'name', mtype: 'type' }),
      });
      expect(result).toEqual(data.results);
    });

    it('rejects if results is missing from the response', async () => {
      axiosMock.onGet(metricsSearchUrl).reply(200, {});
      const e = 'metrics are missing/invalid in the response';

      await expect(client.fetchMetric('name', 'type')).rejects.toThrow(e);
      expectErrorToBeReported(new Error(e));
    });

    it('rejects if metric name is missing', async () => {
      const e = 'fetchMetric() - metric name is required.';
      await expect(client.fetchMetric()).rejects.toThrow(e);
      expectErrorToBeReported(new Error(e));
    });

    it('rejects if metric type is missing', async () => {
      const e = 'fetchMetric() - metric type is required.';
      await expect(client.fetchMetric('name')).rejects.toThrow(e);
      expectErrorToBeReported(new Error(e));
    });
  });
});