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

utils_spec.js « super_sidebar « frontend « spec - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 85f45de06bac861480a34541ca9f7cc18629bae5 (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
import * as Sentry from '@sentry/browser';
import MockAdapter from 'axios-mock-adapter';
import {
  getTopFrequentItems,
  trackContextAccess,
  getItemsFromLocalStorage,
  removeItemFromLocalStorage,
  ariaCurrent,
} from '~/super_sidebar/utils';
import axios from '~/lib/utils/axios_utils';
import { useLocalStorageSpy } from 'helpers/local_storage_helper';
import AccessorUtilities from '~/lib/utils/accessor';
import { FREQUENT_ITEMS, FIFTEEN_MINUTES_IN_MS } from '~/frequent_items/constants';
import { HTTP_STATUS_OK } from '~/lib/utils/http_status';
import waitForPromises from 'helpers/wait_for_promises';
import { unsortedFrequentItems, sortedFrequentItems } from '../frequent_items/mock_data';
import { cachedFrequentProjects } from './mock_data';

jest.mock('@sentry/browser');

useLocalStorageSpy();

describe('Super sidebar utils spec', () => {
  describe('getTopFrequentItems', () => {
    const maxItems = 3;

    it.each([undefined, null])('returns empty array if `items` is %s', (items) => {
      const result = getTopFrequentItems(items);

      expect(result.length).toBe(0);
    });

    it('returns the requested amount of items', () => {
      const result = getTopFrequentItems(unsortedFrequentItems, maxItems);

      expect(result.length).toBe(maxItems);
    });

    it('sorts frequent items in order of frequency and lastAccessedOn', () => {
      const result = getTopFrequentItems(unsortedFrequentItems, maxItems);
      const expectedResult = sortedFrequentItems.slice(0, maxItems);

      expect(result).toEqual(expectedResult);
    });
  });

  describe('trackContextAccess', () => {
    useLocalStorageSpy();

    let axiosMock;

    const username = 'root';
    const trackVisitsPath = '/-/track_visits';
    const context = {
      namespace: 'groups',
      item: { id: 1 },
    };
    const storageKey = `${username}/frequent-${context.namespace}`;

    beforeEach(() => {
      gon.features = { serverSideFrecentNamespaces: true };
      axiosMock = new MockAdapter(axios);
      axiosMock.onPost(trackVisitsPath).reply(HTTP_STATUS_OK);
    });

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

    it('returns `false` if local storage is not available', () => {
      jest.spyOn(AccessorUtilities, 'canUseLocalStorage').mockReturnValue(false);

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

    it('creates a new item if it does not exist in the local storage', () => {
      trackContextAccess(username, context, trackVisitsPath);

      expect(window.localStorage.setItem).toHaveBeenCalledWith(
        storageKey,
        JSON.stringify([
          {
            id: 1,
            frequency: 1,
            lastAccessedOn: Date.now(),
          },
        ]),
      );
    });

    it('sends a POST request to persist the visit in the DB', async () => {
      expect(axiosMock.history.post).toHaveLength(0);

      trackContextAccess(username, context, trackVisitsPath);
      await waitForPromises();

      expect(axiosMock.history.post).toHaveLength(1);
      expect(axiosMock.history.post[0].url).toBe(trackVisitsPath);
    });

    it('does not send a POST request when the serverSideFrecentNamespaces feature flag is disabled', async () => {
      gon.features = { serverSideFrecentNamespaces: false };
      trackContextAccess(username, context, trackVisitsPath);
      await waitForPromises();

      expect(axiosMock.history.post).toHaveLength(0);
    });

    it('updates existing item frequency/access time if it was persisted to the local storage over 15 minutes ago', () => {
      window.localStorage.setItem(
        storageKey,
        JSON.stringify([
          {
            id: 1,
            frequency: 2,
            lastAccessedOn: Date.now() - FIFTEEN_MINUTES_IN_MS - 1,
          },
        ]),
      );
      trackContextAccess(username, context, trackVisitsPath);

      expect(window.localStorage.setItem).toHaveBeenCalledWith(
        storageKey,
        JSON.stringify([
          {
            id: 1,
            frequency: 3,
            lastAccessedOn: Date.now(),
          },
        ]),
      );
    });

    it('leaves item frequency/access time as is if it was persisted to the local storage under 15 minutes ago, and does not send a POST request', () => {
      const jsonString = JSON.stringify([
        {
          id: 1,
          frequency: 2,
          lastAccessedOn: Date.now() - FIFTEEN_MINUTES_IN_MS,
        },
      ]);
      window.localStorage.setItem(storageKey, jsonString);

      expect(window.localStorage.setItem).toHaveBeenCalledTimes(1);
      expect(window.localStorage.setItem).toHaveBeenCalledWith(storageKey, jsonString);

      trackContextAccess(username, context, trackVisitsPath);

      expect(window.localStorage.setItem).toHaveBeenCalledTimes(3);
      expect(window.localStorage.setItem).toHaveBeenLastCalledWith(storageKey, jsonString);

      expect(axiosMock.history.post).toHaveLength(0);
    });

    it('always updates stored item metadata', () => {
      window.localStorage.setItem(
        storageKey,
        JSON.stringify([
          {
            id: 1,
            frequency: 2,
            lastAccessedOn: Date.now(),
          },
        ]),
      );

      trackContextAccess(username, {
        ...context,
        item: {
          ...context.item,
          avatarUrl: '/group.png',
        },
      });

      expect(window.localStorage.setItem).toHaveBeenCalledWith(
        storageKey,
        JSON.stringify([
          {
            id: 1,
            avatarUrl: '/group.png',
            frequency: 2,
            lastAccessedOn: Date.now(),
          },
        ]),
      );
    });

    it('replaces the least popular item in the local storage once the persisted items limit has been hit', () => {
      // Add the maximum amount of items to the local storage, in increasing popularity
      const storedItems = Array.from({ length: FREQUENT_ITEMS.MAX_COUNT }).map((_, i) => ({
        id: i + 1,
        frequency: i + 1,
        lastAccessedOn: Date.now(),
      }));
      // The first item is considered the least popular one as it has the lowest frequency (1)
      const [leastPopularItem] = storedItems;
      // Persist the list to the local storage
      const jsonString = JSON.stringify(storedItems);
      window.localStorage.setItem(storageKey, jsonString);
      // Track some new item that hasn't been visited yet
      const newItem = {
        id: FREQUENT_ITEMS.MAX_COUNT + 1,
      };
      trackContextAccess(
        username,
        {
          namespace: 'groups',
          item: newItem,
        },
        trackVisitsPath,
      );
      // Finally, retrieve the final data from the local storage
      const finallyStoredItems = JSON.parse(window.localStorage.getItem(storageKey));

      expect(finallyStoredItems).not.toEqual(expect.arrayContaining([leastPopularItem]));
      expect(finallyStoredItems).toEqual(
        expect.arrayContaining([
          expect.objectContaining({
            id: newItem.id,
            frequency: 1,
          }),
        ]),
      );
    });
  });

  describe('getItemsFromLocalStorage', () => {
    const storageKey = 'mockStorageKey';
    const maxItems = 5;
    const storedItems = JSON.parse(cachedFrequentProjects);

    beforeEach(() => {
      window.localStorage.setItem(storageKey, cachedFrequentProjects);
    });

    describe('when localStorage cannot be accessed', () => {
      beforeEach(() => {
        jest.spyOn(AccessorUtilities, 'canUseLocalStorage').mockReturnValue(false);
      });

      it('returns an empty array', () => {
        const items = getItemsFromLocalStorage({ storageKey, maxItems });
        expect(items).toEqual([]);
      });
    });

    describe('when localStorage contains parseable data', () => {
      it('returns an array of items limited by max items', () => {
        const items = getItemsFromLocalStorage({ storageKey, maxItems });
        expect(items.length).toEqual(maxItems);

        items.forEach((item) => {
          expect(storedItems).toContainEqual(item);
        });
      });

      it('returns all items if max items is large', () => {
        const items = getItemsFromLocalStorage({ storageKey, maxItems: 1 });
        expect(items.length).toEqual(1);

        expect(storedItems).toContainEqual(items[0]);
      });
    });

    describe('when localStorage contains unparseable data', () => {
      let items;

      beforeEach(() => {
        window.localStorage.setItem(storageKey, 'unparseable');
        items = getItemsFromLocalStorage({ storageKey, maxItems });
      });

      it('logs an error to Sentry', () => {
        expect(Sentry.captureException).toHaveBeenCalled();
      });

      it('returns an empty array', () => {
        expect(items).toEqual([]);
      });
    });
  });

  describe('removeItemFromLocalStorage', () => {
    const storageKey = 'mockStorageKey';
    const originalStoredItems = JSON.parse(cachedFrequentProjects);

    beforeEach(() => {
      window.localStorage.setItem(storageKey, cachedFrequentProjects);
    });

    describe('when given an item to delete', () => {
      let items;
      let modifiedStoredItems;

      beforeEach(() => {
        items = removeItemFromLocalStorage({ storageKey, item: { id: 3 } });
        modifiedStoredItems = JSON.parse(window.localStorage.getItem(storageKey));
      });

      it('removes the item from localStorage', () => {
        expect(modifiedStoredItems.length).toBe(originalStoredItems.length - 1);
        expect(modifiedStoredItems).not.toContainEqual(originalStoredItems[2]);
      });

      it('returns the resulting stored structure', () => {
        expect(items).toEqual(modifiedStoredItems);
      });
    });

    describe('when given an unknown item to delete', () => {
      let items;
      let modifiedStoredItems;

      beforeEach(() => {
        items = removeItemFromLocalStorage({ storageKey, item: { id: 'does-not-exist' } });
        modifiedStoredItems = JSON.parse(window.localStorage.getItem(storageKey));
      });

      it('does not change the stored value', () => {
        expect(modifiedStoredItems).toEqual(originalStoredItems);
      });

      it('returns the stored structure', () => {
        expect(items).toEqual(originalStoredItems);
      });
    });

    describe('when localStorage has unparseable data', () => {
      let items;

      beforeEach(() => {
        window.localStorage.setItem(storageKey, 'unparseable');
        items = removeItemFromLocalStorage({ storageKey, item: { id: 3 } });
      });

      it('logs an error to Sentry', () => {
        expect(Sentry.captureException).toHaveBeenCalled();
      });

      it('returns an empty array', () => {
        expect(items).toEqual([]);
      });
    });
  });

  describe('ariaCurrent', () => {
    it.each`
      isActive | expected
      ${true}  | ${'page'}
      ${false} | ${null}
    `('returns `$expected` when `isActive` is `$isActive`', ({ isActive, expected }) => {
      expect(ariaCurrent(isActive)).toBe(expected);
    });
  });
});