summaryrefslogtreecommitdiff
path: root/spec/javascripts/lib/utils/sticky_spec.js
blob: b87c836654d0705a17d667b80112de8db504c6e8 (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
import { isSticky } from '~/lib/utils/sticky';

describe('sticky', () => {
  let el;

  beforeEach(() => {
    document.body.innerHTML += `
      <div class="parent">
        <div id="js-sticky"></div>
      </div>
    `;

    el = document.getElementById('js-sticky');
  });

  afterEach(() => {
    el.parentNode.remove();
  });

  describe('when stuck', () => {
    it('does not remove is-stuck class', () => {
      isSticky(el, 0, el.offsetTop);
      isSticky(el, 0, el.offsetTop);

      expect(
        el.classList.contains('is-stuck'),
      ).toBeTruthy();
    });

    it('adds is-stuck class', () => {
      isSticky(el, 0, el.offsetTop);

      expect(
        el.classList.contains('is-stuck'),
      ).toBeTruthy();
    });

    it('inserts placeholder element', () => {
      isSticky(el, 0, el.offsetTop, true);

      expect(
        document.querySelector('.sticky-placeholder'),
      ).not.toBeNull();
    });
  });

  describe('when not stuck', () => {
    it('removes is-stuck class', () => {
      spyOn(el.classList, 'remove').and.callThrough();

      isSticky(el, 0, el.offsetTop);
      isSticky(el, 0, 0);

      expect(
        el.classList.remove,
      ).toHaveBeenCalledWith('is-stuck');
      expect(
        el.classList.contains('is-stuck'),
      ).toBeFalsy();
    });

    it('does not add is-stuck class', () => {
      isSticky(el, 0, 0);

      expect(
        el.classList.contains('is-stuck'),
      ).toBeFalsy();
    });

    it('removes placeholder', () => {
      isSticky(el, 0, el.offsetTop, true);
      isSticky(el, 0, 0, true);

      expect(
        document.querySelector('.sticky-placeholder'),
      ).toBeNull();
    });
  });
});