summaryrefslogtreecommitdiff
path: root/spec/javascripts/filtered_search/services/recent_searches_service_spec.js
blob: 2a58fb3a7df087cddcfe24762f5fe6c60e1b4e0c (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
import RecentSearchesService from '~/filtered_search/services/recent_searches_service';

describe('RecentSearchesService', () => {
  let service;

  beforeEach(() => {
    service = new RecentSearchesService();
    window.localStorage.removeItem(service.localStorageKey);
  });

  describe('fetch', () => {
    it('should default to empty array', (done) => {
      const fetchItemsPromise = service.fetch();

      fetchItemsPromise
        .then((items) => {
          expect(items).toEqual([]);
          done();
        })
        .catch((err) => {
          done.fail('Shouldn\'t reject with empty localStorage key', err);
        });
    });

    it('should reject when unable to parse', (done) => {
      window.localStorage.setItem(service.localStorageKey, 'fail');
      const fetchItemsPromise = service.fetch();

      fetchItemsPromise
        .catch(() => {
          done();
        });
    });

    it('should return items from localStorage', (done) => {
      window.localStorage.setItem(service.localStorageKey, '["foo", "bar"]');
      const fetchItemsPromise = service.fetch();

      fetchItemsPromise
        .then((items) => {
          expect(items).toEqual(['foo', 'bar']);
          done();
        });
    });
  });

  describe('setRecentSearches', () => {
    it('should save things in localStorage', () => {
      const items = ['foo', 'bar'];
      service.save(items);
      const newLocalStorageValue =
        window.localStorage.getItem(service.localStorageKey);
      expect(JSON.parse(newLocalStorageValue)).toEqual(items);
    });
  });
});