summaryrefslogtreecommitdiff
path: root/spec/frontend/filtered_search/droplab/plugins/ajax_filter_spec.js
blob: 88b3fc236e428535a165dbb5af1549520b107f81 (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
import AjaxFilter from '~/filtered_search/droplab/plugins/ajax_filter';
import AjaxCache from '~/lib/utils/ajax_cache';

describe('AjaxFilter', () => {
  let dummyConfig;
  const dummyData = 'dummy data';
  let dummyList;

  beforeEach(() => {
    dummyConfig = {
      endpoint: 'dummy endpoint',
      searchKey: 'dummy search key',
    };
    dummyList = {
      data: [],
      list: document.createElement('div'),
    };

    AjaxFilter.hook = {
      config: {
        AjaxFilter: dummyConfig,
      },
      list: dummyList,
    };
  });

  describe('trigger', () => {
    let ajaxSpy;

    beforeEach(() => {
      jest.spyOn(AjaxCache, 'retrieve').mockImplementation((url) => ajaxSpy(url));
      jest.spyOn(AjaxFilter, '_loadData').mockImplementation(() => {});

      dummyConfig.onLoadingFinished = jest.fn();

      const dynamicList = document.createElement('div');
      dynamicList.dataset.dynamic = true;
      dummyList.list.appendChild(dynamicList);
    });

    it('calls onLoadingFinished after loading data', (done) => {
      ajaxSpy = (url) => {
        expect(url).toBe('dummy endpoint?dummy search key=');
        return Promise.resolve(dummyData);
      };

      AjaxFilter.trigger()
        .then(() => {
          expect(dummyConfig.onLoadingFinished.mock.calls.length).toBe(1);
        })
        .then(done)
        .catch(done.fail);
    });

    it('does not call onLoadingFinished if Ajax call fails', (done) => {
      const dummyError = new Error('My dummy is sick! :-(');
      ajaxSpy = (url) => {
        expect(url).toBe('dummy endpoint?dummy search key=');
        return Promise.reject(dummyError);
      };

      AjaxFilter.trigger()
        .then(done.fail)
        .catch((error) => {
          expect(error).toBe(dummyError);
          expect(dummyConfig.onLoadingFinished.mock.calls.length).toBe(0);
        })
        .then(done)
        .catch(done.fail);
    });
  });
});