summaryrefslogtreecommitdiff
path: root/spec/javascripts/lib/utils/accessor_spec.js
blob: b768d6f2a68b4edb89a76dfbbac5e1e487bd1058 (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
import AccessorUtilities from '~/lib/utils/accessor';

describe('AccessorUtilities', () => {
  const testError = new Error('test error');

  describe('isPropertyAccessSafe', () => {
    let base;

    it('should return `true` if access is safe', () => {
      base = { testProp: 'testProp' };

      expect(AccessorUtilities.isPropertyAccessSafe(base, 'testProp')).toBe(true);
    });

    it('should return `false` if access throws an error', () => {
      base = { get testProp() { throw testError; } };

      expect(AccessorUtilities.isPropertyAccessSafe(base, 'testProp')).toBe(false);
    });

    it('should return `false` if property is undefined', () => {
      base = {};

      expect(AccessorUtilities.isPropertyAccessSafe(base, 'testProp')).toBe(false);
    });
  });

  describe('isFunctionCallSafe', () => {
    const base = {};

    it('should return `true` if calling is safe', () => {
      base.func = () => {};

      expect(AccessorUtilities.isFunctionCallSafe(base, 'func')).toBe(true);
    });

    it('should return `false` if calling throws an error', () => {
      base.func = () => { throw new Error('test error'); };

      expect(AccessorUtilities.isFunctionCallSafe(base, 'func')).toBe(false);
    });

    it('should return `false` if function is undefined', () => {
      base.func = undefined;

      expect(AccessorUtilities.isFunctionCallSafe(base, 'func')).toBe(false);
    });
  });

  describe('isLocalStorageAccessSafe', () => {
    beforeEach(() => {
      spyOn(window.localStorage, 'setItem');
      spyOn(window.localStorage, 'removeItem');
    });

    it('should return `true` if access is safe', () => {
      expect(AccessorUtilities.isLocalStorageAccessSafe()).toBe(true);
    });

    it('should return `false` if access to .setItem isnt safe', () => {
      window.localStorage.setItem.and.callFake(() => { throw testError; });

      expect(AccessorUtilities.isLocalStorageAccessSafe()).toBe(false);
    });

    it('should set a test item if access is safe', () => {
      AccessorUtilities.isLocalStorageAccessSafe();

      expect(window.localStorage.setItem).toHaveBeenCalledWith('isLocalStorageAccessSafe', 'true');
    });

    it('should remove the test item if access is safe', () => {
      AccessorUtilities.isLocalStorageAccessSafe();

      expect(window.localStorage.removeItem).toHaveBeenCalledWith('isLocalStorageAccessSafe');
    });
  });
});