summaryrefslogtreecommitdiff
path: root/spec/frontend/boards/project_select_deprecated_spec.js
blob: e4f8f96bd335a3868204bfb61f6b07178f8e69fe (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
import { mount } from '@vue/test-utils';
import axios from 'axios';
import AxiosMockAdapter from 'axios-mock-adapter';
import { GlDropdown, GlDropdownItem, GlSearchBoxByType, GlLoadingIcon } from '@gitlab/ui';
import httpStatus from '~/lib/utils/http_status';
import { featureAccessLevel } from '~/pages/projects/shared/permissions/constants';
import { ListType } from '~/boards/constants';
import eventHub from '~/boards/eventhub';
import { deprecatedCreateFlash as flash } from '~/flash';

import ProjectSelect from '~/boards/components/project_select_deprecated.vue';

import { listObj, mockRawGroupProjects } from './mock_data';

jest.mock('~/boards/eventhub');
jest.mock('~/flash');

const dummyGon = {
  api_version: 'v4',
  relative_url_root: '/gitlab',
};

const mockGroupId = 1;
const mockProjectsList1 = mockRawGroupProjects.slice(0, 1);
const mockProjectsList2 = mockRawGroupProjects.slice(1);
const mockDefaultFetchOptions = {
  with_issues_enabled: true,
  with_shared: false,
  include_subgroups: true,
  order_by: 'similarity',
};

const itemsPerPage = 20;

describe('ProjectSelect component', () => {
  let wrapper;
  let axiosMock;

  const findLabel = () => wrapper.find("[data-testid='header-label']");
  const findGlDropdown = () => wrapper.find(GlDropdown);
  const findGlDropdownLoadingIcon = () =>
    findGlDropdown().find('button:first-child').find(GlLoadingIcon);
  const findGlSearchBoxByType = () => wrapper.find(GlSearchBoxByType);
  const findGlDropdownItems = () => wrapper.findAll(GlDropdownItem);
  const findFirstGlDropdownItem = () => findGlDropdownItems().at(0);
  const findInMenuLoadingIcon = () => wrapper.find("[data-testid='dropdown-text-loading-icon']");
  const findEmptySearchMessage = () => wrapper.find("[data-testid='empty-result-message']");

  const mockGetRequest = (data = [], statusCode = httpStatus.OK) => {
    axiosMock
      .onGet(`/gitlab/api/v4/groups/${mockGroupId}/projects.json`)
      .replyOnce(statusCode, data);
  };

  const searchForProject = async (keyword, waitForAll = true) => {
    findGlSearchBoxByType().vm.$emit('input', keyword);

    if (waitForAll) {
      await axios.waitForAll();
    }
  };

  const createWrapper = async ({ list = listObj } = {}, waitForAll = true) => {
    wrapper = mount(ProjectSelect, {
      propsData: {
        list,
      },
      provide: {
        groupId: 1,
      },
    });

    if (waitForAll) {
      await axios.waitForAll();
    }
  };

  beforeEach(() => {
    axiosMock = new AxiosMockAdapter(axios);
    window.gon = dummyGon;
  });

  afterEach(() => {
    wrapper.destroy();
    wrapper = null;
    axiosMock.restore();
    jest.clearAllMocks();
  });

  it('displays a header title', async () => {
    createWrapper({});

    expect(findLabel().text()).toBe('Projects');
  });

  it('renders a default dropdown text', async () => {
    createWrapper({});

    expect(findGlDropdown().exists()).toBe(true);
    expect(findGlDropdown().text()).toContain('Select a project');
  });

  describe('when mounted', () => {
    it('displays a loading icon while projects are being fetched', async () => {
      mockGetRequest([]);

      createWrapper({}, false);

      expect(findGlDropdownLoadingIcon().exists()).toBe(true);

      await axios.waitForAll();

      expect(axiosMock.history.get[0].params).toMatchObject({ search: '' });
      expect(axiosMock.history.get[0].url).toBe(
        `/gitlab/api/v4/groups/${mockGroupId}/projects.json`,
      );

      expect(findGlDropdownLoadingIcon().exists()).toBe(false);
    });
  });

  describe('when dropdown menu is open', () => {
    describe('by default', () => {
      beforeEach(async () => {
        mockGetRequest(mockProjectsList1);

        await createWrapper();
      });

      it('shows GlSearchBoxByType with default attributes', () => {
        expect(findGlSearchBoxByType().exists()).toBe(true);
        expect(findGlSearchBoxByType().vm.$attrs).toMatchObject({
          placeholder: 'Search projects',
          debounce: '250',
        });
      });

      it("displays the fetched project's name", () => {
        expect(findFirstGlDropdownItem().exists()).toBe(true);
        expect(findFirstGlDropdownItem().text()).toContain(mockProjectsList1[0].name);
      });

      it("doesn't render loading icon in the menu", () => {
        expect(findInMenuLoadingIcon().isVisible()).toBe(false);
      });

      it('renders empty search result message', async () => {
        await createWrapper();

        expect(findEmptySearchMessage().exists()).toBe(true);
      });
    });

    describe('when a project is selected', () => {
      beforeEach(async () => {
        mockGetRequest(mockProjectsList1);

        await createWrapper();

        await findFirstGlDropdownItem().find('button').trigger('click');
      });

      it('emits setSelectedProject with correct project metadata', () => {
        expect(eventHub.$emit).toHaveBeenCalledWith('setSelectedProject', {
          id: mockProjectsList1[0].id,
          path: mockProjectsList1[0].path_with_namespace,
          name: mockProjectsList1[0].name,
          namespacedName: mockProjectsList1[0].name_with_namespace,
        });
      });

      it('renders the name of the selected project', () => {
        expect(findGlDropdown().find('.gl-new-dropdown-button-text').text()).toBe(
          mockProjectsList1[0].name,
        );
      });
    });

    describe('when user searches for a project', () => {
      beforeEach(async () => {
        mockGetRequest(mockProjectsList1);

        await createWrapper();
      });

      it('calls API with correct parameters with default fetch options', async () => {
        await searchForProject('foobar');

        const expectedApiParams = {
          search: 'foobar',
          per_page: itemsPerPage,
          ...mockDefaultFetchOptions,
        };

        expect(axiosMock.history.get[1].params).toMatchObject(expectedApiParams);
        expect(axiosMock.history.get[1].url).toBe(
          `/gitlab/api/v4/groups/${mockGroupId}/projects.json`,
        );
      });

      describe("when list type is defined and isn't backlog", () => {
        it('calls API with an additional fetch option (min_access_level)', async () => {
          axiosMock.reset();

          await createWrapper({ list: { ...listObj, type: ListType.label } });

          await searchForProject('foobar');

          const expectedApiParams = {
            search: 'foobar',
            per_page: itemsPerPage,
            ...mockDefaultFetchOptions,
            min_access_level: featureAccessLevel.EVERYONE,
          };

          expect(axiosMock.history.get[1].params).toMatchObject(expectedApiParams);
          expect(axiosMock.history.get[1].url).toBe(
            `/gitlab/api/v4/groups/${mockGroupId}/projects.json`,
          );
        });
      });

      it('displays and hides gl-loading-icon while and after fetching data', async () => {
        await searchForProject('some keyword', false);

        await wrapper.vm.$nextTick();

        expect(findInMenuLoadingIcon().isVisible()).toBe(true);

        await axios.waitForAll();

        expect(findInMenuLoadingIcon().isVisible()).toBe(false);
      });

      it('flashes an error message when fetching fails', async () => {
        mockGetRequest([], httpStatus.INTERNAL_SERVER_ERROR);

        await searchForProject('foobar');

        expect(flash).toHaveBeenCalledTimes(1);
        expect(flash).toHaveBeenCalledWith('Something went wrong while fetching projects');
      });

      describe('with non-empty search result', () => {
        beforeEach(async () => {
          mockGetRequest(mockProjectsList2);

          await searchForProject('foobar');
        });

        it('displays the retrieved list of projects', async () => {
          expect(findFirstGlDropdownItem().text()).toContain(mockProjectsList2[0].name);
        });

        it('does not render empty search result message', async () => {
          expect(findEmptySearchMessage().exists()).toBe(false);
        });
      });
    });
  });
});