Commit 3fc2bf93 authored by Jacques Erasmus's avatar Jacques Erasmus

Merge branch 'more-set-window-location' into 'master'

Migrate more specs to location helpers [RUN AS-IF-FOSS]

See merge request gitlab-org/gitlab!67065
parents 411012c4 7783ce29
<script> <script>
import { GlFilteredSearchToken } from '@gitlab/ui'; import { GlFilteredSearchToken } from '@gitlab/ui';
import { mapState } from 'vuex'; import { mapState } from 'vuex';
import { getParameterByName, setUrlParams, queryToObject } from '~/lib/utils/url_utility'; import {
getParameterByName,
setUrlParams,
queryToObject,
redirectTo,
} from '~/lib/utils/url_utility';
import { s__ } from '~/locale'; import { s__ } from '~/locale';
import { import {
SEARCH_TOKEN_TYPE, SEARCH_TOKEN_TYPE,
...@@ -122,14 +127,16 @@ export default { ...@@ -122,14 +127,16 @@ export default {
const sortParamValue = getParameterByName(SORT_QUERY_PARAM_NAME); const sortParamValue = getParameterByName(SORT_QUERY_PARAM_NAME);
const activeTabParamValue = getParameterByName(ACTIVE_TAB_QUERY_PARAM_NAME); const activeTabParamValue = getParameterByName(ACTIVE_TAB_QUERY_PARAM_NAME);
window.location.href = setUrlParams( redirectTo(
{ setUrlParams(
...params, {
...(sortParamValue && { [SORT_QUERY_PARAM_NAME]: sortParamValue }), ...params,
...(activeTabParamValue && { [ACTIVE_TAB_QUERY_PARAM_NAME]: activeTabParamValue }), ...(sortParamValue && { [SORT_QUERY_PARAM_NAME]: sortParamValue }),
}, ...(activeTabParamValue && { [ACTIVE_TAB_QUERY_PARAM_NAME]: activeTabParamValue }),
window.location.href, },
true, window.location.href,
true,
),
); );
}, },
}, },
......
...@@ -442,6 +442,18 @@ it('passes', () => { ...@@ -442,6 +442,18 @@ it('passes', () => {
}); });
``` ```
NOTE:
To modify only the hash, use either the `setWindowLocation` helper, or assign
directly to `window.location.hash`, e.g.:
```javascript
it('passes', () => {
window.location.hash = '#foo';
expect(window.location.href).toBe('http://test.host/#foo');
});
```
If your tests need to assert that certain `window.location` methods were If your tests need to assert that certain `window.location` methods were
called, use the `useMockLocationHelper` helper: called, use the `useMockLocationHelper` helper:
......
import * as actions from 'ee/audit_events/store/actions'; import * as actions from 'ee/audit_events/store/actions';
import * as types from 'ee/audit_events/store/mutation_types'; import * as types from 'ee/audit_events/store/mutation_types';
import createState from 'ee/audit_events/store/state'; import createState from 'ee/audit_events/store/state';
import setWindowLocation from 'helpers/set_window_location_helper';
import testAction from 'helpers/vuex_action_helper'; import testAction from 'helpers/vuex_action_helper';
import * as urlUtility from '~/lib/utils/url_utility'; import * as urlUtility from '~/lib/utils/url_utility';
...@@ -48,8 +49,7 @@ describe('Audit Event actions', () => { ...@@ -48,8 +49,7 @@ describe('Audit Event actions', () => {
let spy; let spy;
beforeEach(() => { beforeEach(() => {
delete window.location; setWindowLocation('https://test/');
window.location = new URL('https://test/');
spy = jest.spyOn(urlUtility, 'visitUrl').mockReturnValue({}); spy = jest.spyOn(urlUtility, 'visitUrl').mockReturnValue({});
}); });
...@@ -81,8 +81,7 @@ describe('Audit Event actions', () => { ...@@ -81,8 +81,7 @@ describe('Audit Event actions', () => {
describe('initializeAuditEvents', () => { describe('initializeAuditEvents', () => {
describe('with an empty search query', () => { describe('with an empty search query', () => {
beforeEach(() => { beforeEach(() => {
delete window.location; setWindowLocation('?');
window.location = { search: '' };
}); });
it(`commits "${types.INITIALIZE_AUDIT_EVENTS}" with empty dates`, () => { it(`commits "${types.INITIALIZE_AUDIT_EVENTS}" with empty dates`, () => {
...@@ -100,11 +99,9 @@ describe('Audit Event actions', () => { ...@@ -100,11 +99,9 @@ describe('Audit Event actions', () => {
describe('with a full search query', () => { describe('with a full search query', () => {
beforeEach(() => { beforeEach(() => {
delete window.location; setWindowLocation(
window.location = { '?sort=created_desc&entity_type=User&entity_id=44&created_after=2020-06-05&created_before=2020-06-25',
search: );
'sort=created_desc&entity_type=User&entity_id=44&created_after=2020-06-05&created_before=2020-06-25',
};
}); });
it(`commits "${types.INITIALIZE_AUDIT_EVENTS}" with the query data`, () => { it(`commits "${types.INITIALIZE_AUDIT_EVENTS}" with the query data`, () => {
......
...@@ -4,6 +4,7 @@ import { ...@@ -4,6 +4,7 @@ import {
formatEpicListsPageInfo, formatEpicListsPageInfo,
transformBoardConfig, transformBoardConfig,
} from 'ee/boards/boards_util'; } from 'ee/boards/boards_util';
import setWindowLocation from 'helpers/set_window_location_helper';
import { mockLabel } from './mock_data'; import { mockLabel } from './mock_data';
const listId = 'gid://gitlab/Boards::EpicList/3'; const listId = 'gid://gitlab/Boards::EpicList/3';
...@@ -105,10 +106,6 @@ describe('formatEpicListsPageInfo', () => { ...@@ -105,10 +106,6 @@ describe('formatEpicListsPageInfo', () => {
}); });
describe('transformBoardConfig', () => { describe('transformBoardConfig', () => {
beforeEach(() => {
delete window.location;
});
const boardConfig = { const boardConfig = {
milestoneTitle: 'milestone', milestoneTitle: 'milestone',
assigneeUsername: 'username', assigneeUsername: 'username',
...@@ -120,18 +117,17 @@ describe('transformBoardConfig', () => { ...@@ -120,18 +117,17 @@ describe('transformBoardConfig', () => {
}; };
it('formats url parameters from boardConfig object', () => { it('formats url parameters from boardConfig object', () => {
window.location = { search: '' };
const result = transformBoardConfig(boardConfig); const result = transformBoardConfig(boardConfig);
expect(result).toContain( expect(result).toBe(
'milestone_title=milestone&weight=0&assignee_username=username&label_name[]=Deliverable&label_name[]=On%20hold', 'milestone_title=milestone&weight=0&assignee_username=username&label_name[]=Deliverable&label_name[]=On%20hold',
); );
}); });
it('formats url parameters from boardConfig object preventing duplicates with passed filter query', () => { it('formats url parameters from boardConfig object preventing duplicates with passed filter query', () => {
window.location = { search: '?label_name[]=Deliverable&label_name[]=On%20hold' }; setWindowLocation('?label_name[]=Deliverable&label_name[]=On%20hold');
const result = transformBoardConfig(boardConfig); const result = transformBoardConfig(boardConfig);
expect(result).toContain('milestone_title=milestone&weight=0&assignee_username=username'); expect(result).toBe('milestone_title=milestone&weight=0&assignee_username=username');
}); });
}); });
...@@ -44,7 +44,6 @@ const defaultProps = { ...@@ -44,7 +44,6 @@ const defaultProps = {
describe('BoardForm', () => { describe('BoardForm', () => {
let wrapper; let wrapper;
let mutate; let mutate;
let location;
const findModal = () => wrapper.findComponent(GlModal); const findModal = () => wrapper.findComponent(GlModal);
const findModalActionPrimary = () => findModal().props('actionPrimary'); const findModalActionPrimary = () => findModal().props('actionPrimary');
...@@ -81,16 +80,10 @@ describe('BoardForm', () => { ...@@ -81,16 +80,10 @@ describe('BoardForm', () => {
}); });
}; };
beforeAll(() => {
location = window.location;
delete window.location;
});
afterEach(() => { afterEach(() => {
wrapper.destroy(); wrapper.destroy();
wrapper = null; wrapper = null;
mutate = null; mutate = null;
window.location = location;
}); });
describe('when creating a new epic board', () => { describe('when creating a new epic board', () => {
...@@ -192,7 +185,6 @@ describe('BoardForm', () => { ...@@ -192,7 +185,6 @@ describe('BoardForm', () => {
}, },
}, },
}); });
window.location = new URL('https://test/boards/1');
createComponent({ canAdminBoard: true, currentPage: formType.edit }); createComponent({ canAdminBoard: true, currentPage: formType.edit });
findInput().trigger('keyup.enter', { metaKey: true }); findInput().trigger('keyup.enter', { metaKey: true });
......
...@@ -199,7 +199,7 @@ describe('Project Licenses', () => { ...@@ -199,7 +199,7 @@ describe('Project Licenses', () => {
`( `(
'when window.location contains the hash "$givenLocationHash"', 'when window.location contains the hash "$givenLocationHash"',
({ givenLocationHash, expectedActiveTab }) => { ({ givenLocationHash, expectedActiveTab }) => {
const originalLocation = window.location; const originalLocation = window.location.href;
beforeEach(() => { beforeEach(() => {
setWindowLocation(`http://foo.com/index${givenLocationHash}`); setWindowLocation(`http://foo.com/index${givenLocationHash}`);
...@@ -224,7 +224,7 @@ describe('Project Licenses', () => { ...@@ -224,7 +224,7 @@ describe('Project Licenses', () => {
}); });
afterEach(() => { afterEach(() => {
window.location = originalLocation; setWindowLocation(originalLocation);
}); });
it(`sets the active tab to be "${expectedActiveTab}"`, () => { it(`sets the active tab to be "${expectedActiveTab}"`, () => {
......
import { getByTestId, fireEvent } from '@testing-library/dom'; import { getByTestId, fireEvent } from '@testing-library/dom';
import { createWrapper } from '@vue/test-utils'; import { createWrapper } from '@vue/test-utils';
import setWindowLocation from 'helpers/set_window_location_helper';
import { initRecoveryCodes, initClose2faSuccessMessage } from '~/authentication/two_factor_auth'; import { initRecoveryCodes, initClose2faSuccessMessage } from '~/authentication/two_factor_auth';
import RecoveryCodes from '~/authentication/two_factor_auth/components/recovery_codes.vue'; import RecoveryCodes from '~/authentication/two_factor_auth/components/recovery_codes.vue';
import * as urlUtils from '~/lib/utils/url_utility'; import * as urlUtils from '~/lib/utils/url_utility';
...@@ -53,8 +54,7 @@ describe('initClose2faSuccessMessage', () => { ...@@ -53,8 +54,7 @@ describe('initClose2faSuccessMessage', () => {
describe('when alert is closed', () => { describe('when alert is closed', () => {
beforeEach(() => { beforeEach(() => {
delete window.location; setWindowLocation(
window.location = new URL(
'https://localhost/-/profile/account?two_factor_auth_enabled_successfully=true', 'https://localhost/-/profile/account?two_factor_auth_enabled_successfully=true',
); );
......
import setWindowLocation from 'helpers/set_window_location_helper';
import WebAuthnError from '~/authentication/webauthn/error'; import WebAuthnError from '~/authentication/webauthn/error';
describe('WebAuthnError', () => { describe('WebAuthnError', () => {
...@@ -17,19 +18,8 @@ describe('WebAuthnError', () => { ...@@ -17,19 +18,8 @@ describe('WebAuthnError', () => {
}); });
describe('SecurityError', () => { describe('SecurityError', () => {
const { location } = window;
beforeEach(() => {
delete window.location;
window.location = {};
});
afterEach(() => {
window.location = location;
});
it('returns a descriptive error if https is disabled', () => { it('returns a descriptive error if https is disabled', () => {
window.location.protocol = 'http:'; setWindowLocation('http://localhost');
const expectedMessage = const expectedMessage =
'WebAuthn only works with HTTPS-enabled websites. Contact your administrator for more details.'; 'WebAuthn only works with HTTPS-enabled websites. Contact your administrator for more details.';
...@@ -39,7 +29,7 @@ describe('WebAuthnError', () => { ...@@ -39,7 +29,7 @@ describe('WebAuthnError', () => {
}); });
it('returns a generic error if https is enabled', () => { it('returns a generic error if https is enabled', () => {
window.location.protocol = 'https:'; setWindowLocation('https://localhost');
const expectedMessage = 'There was a problem communicating with your device.'; const expectedMessage = 'There was a problem communicating with your device.';
expect( expect(
......
import $ from 'jquery'; import $ from 'jquery';
import setWindowLocation from 'helpers/set_window_location_helper';
import waitForPromises from 'helpers/wait_for_promises'; import waitForPromises from 'helpers/wait_for_promises';
import WebAuthnRegister from '~/authentication/webauthn/register'; import WebAuthnRegister from '~/authentication/webauthn/register';
import MockWebAuthnDevice from './mock_webauthn_device'; import MockWebAuthnDevice from './mock_webauthn_device';
...@@ -50,17 +51,14 @@ describe('WebAuthnRegister', () => { ...@@ -50,17 +51,14 @@ describe('WebAuthnRegister', () => {
}); });
describe('when unsupported', () => { describe('when unsupported', () => {
const { location, PublicKeyCredential } = window; const { PublicKeyCredential } = window;
beforeEach(() => { beforeEach(() => {
delete window.location;
delete window.credentials; delete window.credentials;
window.location = {};
window.PublicKeyCredential = undefined; window.PublicKeyCredential = undefined;
}); });
afterEach(() => { afterEach(() => {
window.location = location;
window.PublicKeyCredential = PublicKeyCredential; window.PublicKeyCredential = PublicKeyCredential;
}); });
...@@ -69,7 +67,7 @@ describe('WebAuthnRegister', () => { ...@@ -69,7 +67,7 @@ describe('WebAuthnRegister', () => {
${false} | ${'WebAuthn only works with HTTPS-enabled websites'} ${false} | ${'WebAuthn only works with HTTPS-enabled websites'}
${true} | ${'Please use a supported browser, e.g. Chrome (67+) or Firefox'} ${true} | ${'Please use a supported browser, e.g. Chrome (67+) or Firefox'}
`('when https is $httpsEnabled', ({ httpsEnabled, expectedText }) => { `('when https is $httpsEnabled', ({ httpsEnabled, expectedText }) => {
window.location.protocol = httpsEnabled ? 'https:' : 'http:'; setWindowLocation(`${httpsEnabled ? 'https:' : 'http:'}//localhost`);
component.start(); component.start();
expect(findMessage().text()).toContain(expectedText); expect(findMessage().text()).toContain(expectedText);
......
import { GlLabel, GlLoadingIcon, GlTooltip } from '@gitlab/ui'; import { GlLabel, GlLoadingIcon, GlTooltip } from '@gitlab/ui';
import { range } from 'lodash'; import { range } from 'lodash';
import Vuex from 'vuex'; import Vuex from 'vuex';
import setWindowLocation from 'helpers/set_window_location_helper';
import { mountExtended } from 'helpers/vue_test_utils_helper'; import { mountExtended } from 'helpers/vue_test_utils_helper';
import BoardBlockedIcon from '~/boards/components/board_blocked_icon.vue'; import BoardBlockedIcon from '~/boards/components/board_blocked_icon.vue';
import BoardCardInner from '~/boards/components/board_card_inner.vue'; import BoardCardInner from '~/boards/components/board_card_inner.vue';
...@@ -363,8 +364,6 @@ describe('Board card component', () => { ...@@ -363,8 +364,6 @@ describe('Board card component', () => {
describe('filterByLabel method', () => { describe('filterByLabel method', () => {
beforeEach(() => { beforeEach(() => {
delete window.location;
wrapper.setProps({ wrapper.setProps({
updateFilters: true, updateFilters: true,
}); });
...@@ -373,7 +372,7 @@ describe('Board card component', () => { ...@@ -373,7 +372,7 @@ describe('Board card component', () => {
describe('when selected label is not in the filter', () => { describe('when selected label is not in the filter', () => {
beforeEach(() => { beforeEach(() => {
jest.spyOn(wrapper.vm, 'performSearch').mockImplementation(() => {}); jest.spyOn(wrapper.vm, 'performSearch').mockImplementation(() => {});
window.location = { search: '' }; setWindowLocation('?');
wrapper.vm.filterByLabel(label1); wrapper.vm.filterByLabel(label1);
}); });
...@@ -394,7 +393,7 @@ describe('Board card component', () => { ...@@ -394,7 +393,7 @@ describe('Board card component', () => {
describe('when selected label is already in the filter', () => { describe('when selected label is already in the filter', () => {
beforeEach(() => { beforeEach(() => {
jest.spyOn(wrapper.vm, 'performSearch').mockImplementation(() => {}); jest.spyOn(wrapper.vm, 'performSearch').mockImplementation(() => {});
window.location = { search: '?label_name[]=testing%20123' }; setWindowLocation('?label_name[]=testing%20123');
wrapper.vm.filterByLabel(label1); wrapper.vm.filterByLabel(label1);
}); });
......
import { GlModal } from '@gitlab/ui'; import { GlModal } from '@gitlab/ui';
import { shallowMount } from '@vue/test-utils'; import { shallowMount } from '@vue/test-utils';
import setWindowLocation from 'helpers/set_window_location_helper';
import { TEST_HOST } from 'helpers/test_constants'; import { TEST_HOST } from 'helpers/test_constants';
import waitForPromises from 'helpers/wait_for_promises'; import waitForPromises from 'helpers/wait_for_promises';
...@@ -75,10 +76,6 @@ describe('BoardForm', () => { ...@@ -75,10 +76,6 @@ describe('BoardForm', () => {
}); });
}; };
beforeEach(() => {
delete window.location;
});
afterEach(() => { afterEach(() => {
wrapper.destroy(); wrapper.destroy();
wrapper = null; wrapper = null;
...@@ -244,7 +241,7 @@ describe('BoardForm', () => { ...@@ -244,7 +241,7 @@ describe('BoardForm', () => {
updateBoard: { board: { id: 'gid://gitlab/Board/321', webPath: 'test-path' } }, updateBoard: { board: { id: 'gid://gitlab/Board/321', webPath: 'test-path' } },
}, },
}); });
window.location = new URL('https://test/boards/1'); setWindowLocation('https://test/boards/1');
createComponent({ canAdminBoard: true, currentPage: formType.edit }); createComponent({ canAdminBoard: true, currentPage: formType.edit });
findInput().trigger('keyup.enter', { metaKey: true }); findInput().trigger('keyup.enter', { metaKey: true });
...@@ -270,7 +267,7 @@ describe('BoardForm', () => { ...@@ -270,7 +267,7 @@ describe('BoardForm', () => {
updateBoard: { board: { id: 'gid://gitlab/Board/321', webPath: 'test-path' } }, updateBoard: { board: { id: 'gid://gitlab/Board/321', webPath: 'test-path' } },
}, },
}); });
window.location = new URL('https://test/boards/1?group_by=epic'); setWindowLocation('https://test/boards/1?group_by=epic');
createComponent({ canAdminBoard: true, currentPage: formType.edit }); createComponent({ canAdminBoard: true, currentPage: formType.edit });
findInput().trigger('keyup.enter', { metaKey: true }); findInput().trigger('keyup.enter', { metaKey: true });
......
import MockAdapter from 'axios-mock-adapter'; import MockAdapter from 'axios-mock-adapter';
import { loadHTMLFixture } from 'helpers/fixtures'; import { loadHTMLFixture } from 'helpers/fixtures';
import { useMockLocationHelper } from 'helpers/mock_window_location_helper';
import { setTestTimeout } from 'helpers/timeout'; import { setTestTimeout } from 'helpers/timeout';
import Clusters from '~/clusters/clusters_bundle'; import Clusters from '~/clusters/clusters_bundle';
import axios from '~/lib/utils/axios_utils'; import axios from '~/lib/utils/axios_utils';
...@@ -8,6 +9,8 @@ import initProjectSelectDropdown from '~/project_select'; ...@@ -8,6 +9,8 @@ import initProjectSelectDropdown from '~/project_select';
jest.mock('~/lib/utils/poll'); jest.mock('~/lib/utils/poll');
jest.mock('~/project_select'); jest.mock('~/project_select');
useMockLocationHelper();
describe('Clusters', () => { describe('Clusters', () => {
setTestTimeout(1000); setTestTimeout(1000);
...@@ -55,20 +58,6 @@ describe('Clusters', () => { ...@@ -55,20 +58,6 @@ describe('Clusters', () => {
}); });
describe('updateContainer', () => { describe('updateContainer', () => {
const { location } = window;
beforeEach(() => {
delete window.location;
window.location = {
reload: jest.fn(),
hash: location.hash,
};
});
afterEach(() => {
window.location = location;
});
describe('when creating cluster', () => { describe('when creating cluster', () => {
it('should show the creating container', () => { it('should show the creating container', () => {
cluster.updateContainer(null, 'creating'); cluster.updateContainer(null, 'creating');
......
...@@ -4,6 +4,7 @@ import MockAdapter from 'axios-mock-adapter'; ...@@ -4,6 +4,7 @@ import MockAdapter from 'axios-mock-adapter';
import Mousetrap from 'mousetrap'; import Mousetrap from 'mousetrap';
import Vue, { nextTick } from 'vue'; import Vue, { nextTick } from 'vue';
import Vuex from 'vuex'; import Vuex from 'vuex';
import setWindowLocation from 'helpers/set_window_location_helper';
import { TEST_HOST } from 'spec/test_constants'; import { TEST_HOST } from 'spec/test_constants';
import App from '~/diffs/components/app.vue'; import App from '~/diffs/components/app.vue';
import CommitWidget from '~/diffs/components/commit_widget.vue'; import CommitWidget from '~/diffs/components/commit_widget.vue';
...@@ -428,12 +429,10 @@ describe('diffs/components/app', () => { ...@@ -428,12 +429,10 @@ describe('diffs/components/app', () => {
jest.spyOn(wrapper.vm, 'refetchDiffData').mockImplementation(() => {}); jest.spyOn(wrapper.vm, 'refetchDiffData').mockImplementation(() => {});
jest.spyOn(wrapper.vm, 'adjustView').mockImplementation(() => {}); jest.spyOn(wrapper.vm, 'adjustView').mockImplementation(() => {});
}; };
let location; const location = window.location.href;
beforeAll(() => { beforeAll(() => {
location = window.location; setWindowLocation(COMMIT_URL);
delete window.location;
window.location = COMMIT_URL;
document.title = 'My Title'; document.title = 'My Title';
}); });
...@@ -442,7 +441,7 @@ describe('diffs/components/app', () => { ...@@ -442,7 +441,7 @@ describe('diffs/components/app', () => {
}); });
afterAll(() => { afterAll(() => {
window.location = location; setWindowLocation(location);
}); });
it('when the commit changes and the app is not loading it should update the history, refetch the diff data, and update the view', async () => { it('when the commit changes and the app is not loading it should update the history, refetch the diff data, and update the view', async () => {
......
...@@ -220,7 +220,7 @@ describe('CompareVersions', () => { ...@@ -220,7 +220,7 @@ describe('CompareVersions', () => {
describe('prev commit', () => { describe('prev commit', () => {
beforeAll(() => { beforeAll(() => {
setWindowLocation(`${TEST_HOST}?commit_id=${mrCommit.id}`); setWindowLocation(`?commit_id=${mrCommit.id}`);
}); });
beforeEach(() => { beforeEach(() => {
...@@ -255,7 +255,7 @@ describe('CompareVersions', () => { ...@@ -255,7 +255,7 @@ describe('CompareVersions', () => {
describe('next commit', () => { describe('next commit', () => {
beforeAll(() => { beforeAll(() => {
setWindowLocation(`${TEST_HOST}?commit_id=${mrCommit.id}`); setWindowLocation(`?commit_id=${mrCommit.id}`);
}); });
beforeEach(() => { beforeEach(() => {
......
import { Range } from 'monaco-editor'; import { Range } from 'monaco-editor';
import { useFakeRequestAnimationFrame } from 'helpers/fake_request_animation_frame'; import { useFakeRequestAnimationFrame } from 'helpers/fake_request_animation_frame';
import setWindowLocation from 'helpers/set_window_location_helper';
import { import {
ERROR_INSTANCE_REQUIRED_FOR_EXTENSION, ERROR_INSTANCE_REQUIRED_FOR_EXTENSION,
EDITOR_TYPE_CODE, EDITOR_TYPE_CODE,
...@@ -152,12 +153,7 @@ describe('The basis for an Source Editor extension', () => { ...@@ -152,12 +153,7 @@ describe('The basis for an Source Editor extension', () => {
useFakeRequestAnimationFrame(); useFakeRequestAnimationFrame();
beforeEach(() => { beforeEach(() => {
delete window.location; setWindowLocation('https://localhost');
window.location = new URL(`https://localhost`);
});
afterEach(() => {
window.location.hash = '';
}); });
it.each` it.each`
......
import { GlFilteredSearchToken } from '@gitlab/ui'; import { GlFilteredSearchToken } from '@gitlab/ui';
import { shallowMount, createLocalVue } from '@vue/test-utils'; import { shallowMount, createLocalVue } from '@vue/test-utils';
import Vuex from 'vuex'; import Vuex from 'vuex';
import setWindowLocation from 'helpers/set_window_location_helper';
import { redirectTo } from '~/lib/utils/url_utility';
import MembersFilteredSearchBar from '~/members/components/filter_sort/members_filtered_search_bar.vue'; import MembersFilteredSearchBar from '~/members/components/filter_sort/members_filtered_search_bar.vue';
import { MEMBER_TYPES } from '~/members/constants'; import { MEMBER_TYPES } from '~/members/constants';
import { OPERATOR_IS_ONLY } from '~/vue_shared/components/filtered_search_bar/constants'; import { OPERATOR_IS_ONLY } from '~/vue_shared/components/filtered_search_bar/constants';
import FilteredSearchBar from '~/vue_shared/components/filtered_search_bar/filtered_search_bar_root.vue'; import FilteredSearchBar from '~/vue_shared/components/filtered_search_bar/filtered_search_bar_root.vue';
jest.mock('~/lib/utils/url_utility', () => {
const urlUtility = jest.requireActual('~/lib/utils/url_utility');
return {
__esModule: true,
...urlUtility,
redirectTo: jest.fn(),
};
});
const localVue = createLocalVue(); const localVue = createLocalVue();
localVue.use(Vuex); localVue.use(Vuex);
...@@ -113,12 +125,11 @@ describe('MembersFilteredSearchBar', () => { ...@@ -113,12 +125,11 @@ describe('MembersFilteredSearchBar', () => {
describe('when filters are set via query params', () => { describe('when filters are set via query params', () => {
beforeEach(() => { beforeEach(() => {
delete window.location; setWindowLocation('https://localhost');
window.location = new URL('https://localhost');
}); });
it('parses and passes tokens to `FilteredSearchBar` component as `initialFilterValue` prop', () => { it('parses and passes tokens to `FilteredSearchBar` component as `initialFilterValue` prop', () => {
window.location.search = '?two_factor=enabled&token_not_available=foobar'; setWindowLocation('?two_factor=enabled&token_not_available=foobar');
createComponent(); createComponent();
...@@ -134,7 +145,7 @@ describe('MembersFilteredSearchBar', () => { ...@@ -134,7 +145,7 @@ describe('MembersFilteredSearchBar', () => {
}); });
it('parses and passes search param to `FilteredSearchBar` component as `initialFilterValue` prop', () => { it('parses and passes search param to `FilteredSearchBar` component as `initialFilterValue` prop', () => {
window.location.search = '?search=foobar'; setWindowLocation('?search=foobar');
createComponent(); createComponent();
...@@ -149,7 +160,7 @@ describe('MembersFilteredSearchBar', () => { ...@@ -149,7 +160,7 @@ describe('MembersFilteredSearchBar', () => {
}); });
it('parses and passes search param with multiple words to `FilteredSearchBar` component as `initialFilterValue` prop', () => { it('parses and passes search param with multiple words to `FilteredSearchBar` component as `initialFilterValue` prop', () => {
window.location.search = '?search=foo+bar+baz'; setWindowLocation('?search=foo+bar+baz');
createComponent(); createComponent();
...@@ -166,8 +177,7 @@ describe('MembersFilteredSearchBar', () => { ...@@ -166,8 +177,7 @@ describe('MembersFilteredSearchBar', () => {
describe('when filter bar is submitted', () => { describe('when filter bar is submitted', () => {
beforeEach(() => { beforeEach(() => {
delete window.location; setWindowLocation('https://localhost');
window.location = new URL('https://localhost');
}); });
it('adds correct filter query params', () => { it('adds correct filter query params', () => {
...@@ -177,7 +187,7 @@ describe('MembersFilteredSearchBar', () => { ...@@ -177,7 +187,7 @@ describe('MembersFilteredSearchBar', () => {
{ type: 'two_factor', value: { data: 'enabled', operator: '=' } }, { type: 'two_factor', value: { data: 'enabled', operator: '=' } },
]); ]);
expect(window.location.href).toBe('https://localhost/?two_factor=enabled'); expect(redirectTo).toHaveBeenCalledWith('https://localhost/?two_factor=enabled');
}); });
it('adds search query param', () => { it('adds search query param', () => {
...@@ -188,7 +198,9 @@ describe('MembersFilteredSearchBar', () => { ...@@ -188,7 +198,9 @@ describe('MembersFilteredSearchBar', () => {
{ type: 'filtered-search-term', value: { data: 'foobar' } }, { type: 'filtered-search-term', value: { data: 'foobar' } },
]); ]);
expect(window.location.href).toBe('https://localhost/?two_factor=enabled&search=foobar'); expect(redirectTo).toHaveBeenCalledWith(
'https://localhost/?two_factor=enabled&search=foobar',
);
}); });
it('adds search query param with multiple words', () => { it('adds search query param with multiple words', () => {
...@@ -199,11 +211,13 @@ describe('MembersFilteredSearchBar', () => { ...@@ -199,11 +211,13 @@ describe('MembersFilteredSearchBar', () => {
{ type: 'filtered-search-term', value: { data: 'foo bar baz' } }, { type: 'filtered-search-term', value: { data: 'foo bar baz' } },
]); ]);
expect(window.location.href).toBe('https://localhost/?two_factor=enabled&search=foo+bar+baz'); expect(redirectTo).toHaveBeenCalledWith(
'https://localhost/?two_factor=enabled&search=foo+bar+baz',
);
}); });
it('adds sort query param', () => { it('adds sort query param', () => {
window.location.search = '?sort=name_asc'; setWindowLocation('?sort=name_asc');
createComponent(); createComponent();
...@@ -212,13 +226,13 @@ describe('MembersFilteredSearchBar', () => { ...@@ -212,13 +226,13 @@ describe('MembersFilteredSearchBar', () => {
{ type: 'filtered-search-term', value: { data: 'foobar' } }, { type: 'filtered-search-term', value: { data: 'foobar' } },
]); ]);
expect(window.location.href).toBe( expect(redirectTo).toHaveBeenCalledWith(
'https://localhost/?two_factor=enabled&search=foobar&sort=name_asc', 'https://localhost/?two_factor=enabled&search=foobar&sort=name_asc',
); );
}); });
it('adds active tab query param', () => { it('adds active tab query param', () => {
window.location.search = '?tab=invited'; setWindowLocation('?tab=invited');
createComponent(); createComponent();
...@@ -226,7 +240,7 @@ describe('MembersFilteredSearchBar', () => { ...@@ -226,7 +240,7 @@ describe('MembersFilteredSearchBar', () => {
{ type: 'filtered-search-term', value: { data: 'foobar' } }, { type: 'filtered-search-term', value: { data: 'foobar' } },
]); ]);
expect(window.location.href).toBe('https://localhost/?search=foobar&tab=invited'); expect(redirectTo).toHaveBeenCalledWith('https://localhost/?search=foobar&tab=invited');
}); });
}); });
}); });
import { GlSorting, GlSortingItem } from '@gitlab/ui'; import { GlSorting, GlSortingItem } from '@gitlab/ui';
import { mount, createLocalVue } from '@vue/test-utils'; import { mount, createLocalVue } from '@vue/test-utils';
import Vuex from 'vuex'; import Vuex from 'vuex';
import setWindowLocation from 'helpers/set_window_location_helper';
import * as urlUtilities from '~/lib/utils/url_utility'; import * as urlUtilities from '~/lib/utils/url_utility';
import SortDropdown from '~/members/components/filter_sort/sort_dropdown.vue'; import SortDropdown from '~/members/components/filter_sort/sort_dropdown.vue';
import { MEMBER_TYPES } from '~/members/constants'; import { MEMBER_TYPES } from '~/members/constants';
...@@ -52,17 +53,16 @@ describe('SortDropdown', () => { ...@@ -52,17 +53,16 @@ describe('SortDropdown', () => {
.findAll(GlSortingItem) .findAll(GlSortingItem)
.wrappers.find((dropdownItemWrapper) => dropdownItemWrapper.text() === text); .wrappers.find((dropdownItemWrapper) => dropdownItemWrapper.text() === text);
describe('dropdown options', () => { beforeEach(() => {
beforeEach(() => { setWindowLocation(URL_HOST);
delete window.location; });
window.location = new URL(URL_HOST);
});
describe('dropdown options', () => {
it('adds dropdown items for all the sortable fields', () => { it('adds dropdown items for all the sortable fields', () => {
const URL_FILTER_PARAMS = '?two_factor=enabled&search=foobar'; const URL_FILTER_PARAMS = '?two_factor=enabled&search=foobar';
const EXPECTED_BASE_URL = `${URL_HOST}${URL_FILTER_PARAMS}&sort=`; const EXPECTED_BASE_URL = `${URL_HOST}${URL_FILTER_PARAMS}&sort=`;
window.location.search = URL_FILTER_PARAMS; setWindowLocation(URL_FILTER_PARAMS);
const expectedDropdownItems = [ const expectedDropdownItems = [
{ {
...@@ -94,7 +94,7 @@ describe('SortDropdown', () => { ...@@ -94,7 +94,7 @@ describe('SortDropdown', () => {
}); });
it('checks selected sort option', () => { it('checks selected sort option', () => {
window.location.search = '?sort=access_level_asc'; setWindowLocation('?sort=access_level_asc');
createComponent(); createComponent();
...@@ -103,11 +103,6 @@ describe('SortDropdown', () => { ...@@ -103,11 +103,6 @@ describe('SortDropdown', () => {
}); });
describe('dropdown toggle', () => { describe('dropdown toggle', () => {
beforeEach(() => {
delete window.location;
window.location = new URL(URL_HOST);
});
it('defaults to sorting by "Account" in ascending order', () => { it('defaults to sorting by "Account" in ascending order', () => {
createComponent(); createComponent();
...@@ -116,7 +111,7 @@ describe('SortDropdown', () => { ...@@ -116,7 +111,7 @@ describe('SortDropdown', () => {
}); });
it('sets text as selected sort option', () => { it('sets text as selected sort option', () => {
window.location.search = '?sort=access_level_asc'; setWindowLocation('?sort=access_level_asc');
createComponent(); createComponent();
...@@ -126,15 +121,12 @@ describe('SortDropdown', () => { ...@@ -126,15 +121,12 @@ describe('SortDropdown', () => {
describe('sort direction toggle', () => { describe('sort direction toggle', () => {
beforeEach(() => { beforeEach(() => {
delete window.location; jest.spyOn(urlUtilities, 'visitUrl').mockImplementation();
window.location = new URL(URL_HOST);
jest.spyOn(urlUtilities, 'visitUrl');
}); });
describe('when current sort direction is ascending', () => { describe('when current sort direction is ascending', () => {
beforeEach(() => { beforeEach(() => {
window.location.search = '?sort=access_level_asc'; setWindowLocation('?sort=access_level_asc');
createComponent(); createComponent();
}); });
...@@ -152,7 +144,7 @@ describe('SortDropdown', () => { ...@@ -152,7 +144,7 @@ describe('SortDropdown', () => {
describe('when current sort direction is descending', () => { describe('when current sort direction is descending', () => {
beforeEach(() => { beforeEach(() => {
window.location.search = '?sort=access_level_desc'; setWindowLocation('?sort=access_level_desc');
createComponent(); createComponent();
}); });
......
import { GlTabs } from '@gitlab/ui'; import { GlTabs } from '@gitlab/ui';
import Vue, { nextTick } from 'vue'; import Vue, { nextTick } from 'vue';
import Vuex from 'vuex'; import Vuex from 'vuex';
import setWindowLocation from 'helpers/set_window_location_helper';
import { mountExtended } from 'helpers/vue_test_utils_helper'; import { mountExtended } from 'helpers/vue_test_utils_helper';
import MembersApp from '~/members/components/app.vue'; import MembersApp from '~/members/components/app.vue';
import MembersTabs from '~/members/components/members_tabs.vue'; import MembersTabs from '~/members/components/members_tabs.vue';
...@@ -90,8 +91,7 @@ describe('MembersTabs', () => { ...@@ -90,8 +91,7 @@ describe('MembersTabs', () => {
const findActiveTab = () => wrapper.findByRole('tab', { selected: true }); const findActiveTab = () => wrapper.findByRole('tab', { selected: true });
beforeEach(() => { beforeEach(() => {
delete window.location; setWindowLocation('https://localhost');
window.location = new URL('https://localhost');
}); });
afterEach(() => { afterEach(() => {
...@@ -151,7 +151,7 @@ describe('MembersTabs', () => { ...@@ -151,7 +151,7 @@ describe('MembersTabs', () => {
describe('when url param matches `filteredSearchBar.searchParam`', () => { describe('when url param matches `filteredSearchBar.searchParam`', () => {
beforeEach(() => { beforeEach(() => {
window.location.search = '?search_groups=foo+bar'; setWindowLocation('?search_groups=foo+bar');
}); });
it('shows tab that corresponds to search param', async () => { it('shows tab that corresponds to search param', async () => {
......
...@@ -6,6 +6,7 @@ import { ...@@ -6,6 +6,7 @@ import {
} from '@testing-library/dom'; } from '@testing-library/dom';
import { mount, createLocalVue, createWrapper } from '@vue/test-utils'; import { mount, createLocalVue, createWrapper } from '@vue/test-utils';
import Vuex from 'vuex'; import Vuex from 'vuex';
import setWindowLocation from 'helpers/set_window_location_helper';
import { extendedWrapper } from 'helpers/vue_test_utils_helper'; import { extendedWrapper } from 'helpers/vue_test_utils_helper';
import CreatedAt from '~/members/components/table/created_at.vue'; import CreatedAt from '~/members/components/table/created_at.vue';
import ExpirationDatepicker from '~/members/components/table/expiration_datepicker.vue'; import ExpirationDatepicker from '~/members/components/table/expiration_datepicker.vue';
...@@ -243,12 +244,8 @@ describe('MembersTable', () => { ...@@ -243,12 +244,8 @@ describe('MembersTable', () => {
}); });
describe('when required pagination data is provided', () => { describe('when required pagination data is provided', () => {
beforeEach(() => {
delete window.location;
});
it('renders `gl-pagination` component with correct props', () => { it('renders `gl-pagination` component with correct props', () => {
window.location = new URL(url); setWindowLocation(url);
createComponent(); createComponent();
...@@ -268,7 +265,7 @@ describe('MembersTable', () => { ...@@ -268,7 +265,7 @@ describe('MembersTable', () => {
}); });
it('uses `pagination.paramName` to generate the pagination links', () => { it('uses `pagination.paramName` to generate the pagination links', () => {
window.location = new URL(url); setWindowLocation(url);
createComponent({ createComponent({
pagination: { pagination: {
...@@ -283,7 +280,7 @@ describe('MembersTable', () => { ...@@ -283,7 +280,7 @@ describe('MembersTable', () => {
}); });
it('removes any url params defined as `null` in the `params` attribute', () => { it('removes any url params defined as `null` in the `params` attribute', () => {
window.location = new URL(`${url}&search_groups=foo`); setWindowLocation(`${url}&search_groups=foo`);
createComponent({ createComponent({
pagination: { pagination: {
......
import setWindowLocation from 'helpers/set_window_location_helper';
import { DEFAULT_SORT, MEMBER_TYPES } from '~/members/constants'; import { DEFAULT_SORT, MEMBER_TYPES } from '~/members/constants';
import { import {
generateBadges, generateBadges,
...@@ -150,21 +151,18 @@ describe('Members Utils', () => { ...@@ -150,21 +151,18 @@ describe('Members Utils', () => {
describe('parseSortParam', () => { describe('parseSortParam', () => {
beforeEach(() => { beforeEach(() => {
delete window.location; setWindowLocation(URL_HOST);
window.location = new URL(URL_HOST);
}); });
describe('when `sort` param is not present', () => { describe('when `sort` param is not present', () => {
it('returns default sort options', () => { it('returns default sort options', () => {
window.location.search = '';
expect(parseSortParam(['account'])).toEqual(DEFAULT_SORT); expect(parseSortParam(['account'])).toEqual(DEFAULT_SORT);
}); });
}); });
describe('when field passed in `sortableFields` argument does not have `sort` key defined', () => { describe('when field passed in `sortableFields` argument does not have `sort` key defined', () => {
it('returns default sort options', () => { it('returns default sort options', () => {
window.location.search = '?sort=source_asc'; setWindowLocation('?sort=source_asc');
expect(parseSortParam(['source'])).toEqual(DEFAULT_SORT); expect(parseSortParam(['source'])).toEqual(DEFAULT_SORT);
}); });
...@@ -182,7 +180,7 @@ describe('Members Utils', () => { ...@@ -182,7 +180,7 @@ describe('Members Utils', () => {
${'oldest_sign_in'} | ${{ sortByKey: 'lastSignIn', sortDesc: true }} ${'oldest_sign_in'} | ${{ sortByKey: 'lastSignIn', sortDesc: true }}
`('when `sort` query string param is `$sortParam`', ({ sortParam, expected }) => { `('when `sort` query string param is `$sortParam`', ({ sortParam, expected }) => {
it(`returns ${JSON.stringify(expected)}`, async () => { it(`returns ${JSON.stringify(expected)}`, async () => {
window.location.search = `?sort=${sortParam}`; setWindowLocation(`?sort=${sortParam}`);
expect(parseSortParam(['account', 'granted', 'expires', 'maxRole', 'lastSignIn'])).toEqual( expect(parseSortParam(['account', 'granted', 'expires', 'maxRole', 'lastSignIn'])).toEqual(
expected, expected,
...@@ -193,8 +191,7 @@ describe('Members Utils', () => { ...@@ -193,8 +191,7 @@ describe('Members Utils', () => {
describe('buildSortHref', () => { describe('buildSortHref', () => {
beforeEach(() => { beforeEach(() => {
delete window.location; setWindowLocation(URL_HOST);
window.location = new URL(URL_HOST);
}); });
describe('when field passed in `sortBy` argument does not have `sort` key defined', () => { describe('when field passed in `sortBy` argument does not have `sort` key defined', () => {
...@@ -225,7 +222,7 @@ describe('Members Utils', () => { ...@@ -225,7 +222,7 @@ describe('Members Utils', () => {
describe('when filter params are set', () => { describe('when filter params are set', () => {
it('merges the `sort` param with the filter params', () => { it('merges the `sort` param with the filter params', () => {
window.location.search = '?two_factor=enabled&with_inherited_permissions=exclude'; setWindowLocation('?two_factor=enabled&with_inherited_permissions=exclude');
expect( expect(
buildSortHref({ buildSortHref({
...@@ -240,7 +237,7 @@ describe('Members Utils', () => { ...@@ -240,7 +237,7 @@ describe('Members Utils', () => {
describe('when search param is set', () => { describe('when search param is set', () => {
it('merges the `sort` param with the search param', () => { it('merges the `sort` param with the search param', () => {
window.location.search = '?search=foobar'; setWindowLocation('?search=foobar');
expect( expect(
buildSortHref({ buildSortHref({
......
...@@ -301,9 +301,6 @@ describe('Actions menu', () => { ...@@ -301,9 +301,6 @@ describe('Actions menu', () => {
}); });
it('redirects to the newly created dashboard', () => { it('redirects to the newly created dashboard', () => {
delete window.location;
window.location = new URL('https://localhost');
const newDashboard = dashboardGitResponse[1]; const newDashboard = dashboardGitResponse[1];
const newDashboardUrl = 'root/sandbox/-/metrics/dashboard.yml'; const newDashboardUrl = 'root/sandbox/-/metrics/dashboard.yml';
......
import MockAdapter from 'axios-mock-adapter'; import MockAdapter from 'axios-mock-adapter';
import VueDraggable from 'vuedraggable'; import VueDraggable from 'vuedraggable';
import setWindowLocation from 'helpers/set_window_location_helper';
import { TEST_HOST } from 'helpers/test_constants'; import { TEST_HOST } from 'helpers/test_constants';
import { mountExtended, shallowMountExtended } from 'helpers/vue_test_utils_helper'; import { mountExtended, shallowMountExtended } from 'helpers/vue_test_utils_helper';
import createFlash from '~/flash'; import createFlash from '~/flash';
...@@ -226,32 +227,25 @@ describe('Dashboard', () => { ...@@ -226,32 +227,25 @@ describe('Dashboard', () => {
}); });
describe('when the URL contains a reference to a panel', () => { describe('when the URL contains a reference to a panel', () => {
let location; const location = window.location.href;
const setSearch = (search) => { const setSearch = (searchParams) => {
window.location = { ...location, search }; setWindowLocation(`?${objectToQuery(searchParams)}`);
}; };
beforeEach(() => {
location = window.location;
delete window.location;
});
afterEach(() => { afterEach(() => {
window.location = location; setWindowLocation(location);
}); });
it('when the URL points to a panel it expands', () => { it('when the URL points to a panel it expands', () => {
const panelGroup = metricsDashboardViewModel.panelGroups[0]; const panelGroup = metricsDashboardViewModel.panelGroups[0];
const panel = panelGroup.panels[0]; const panel = panelGroup.panels[0];
setSearch( setSearch({
objectToQuery({ group: panelGroup.group,
group: panelGroup.group, title: panel.title,
title: panel.title, y_label: panel.y_label,
y_label: panel.y_label, });
}),
);
createMountedWrapper({ hasMetrics: true }); createMountedWrapper({ hasMetrics: true });
setupStoreWithData(store); setupStoreWithData(store);
...@@ -268,7 +262,7 @@ describe('Dashboard', () => { ...@@ -268,7 +262,7 @@ describe('Dashboard', () => {
}); });
it('when the URL does not link to any panel, no panel is expanded', () => { it('when the URL does not link to any panel, no panel is expanded', () => {
setSearch(''); setSearch();
createMountedWrapper({ hasMetrics: true }); createMountedWrapper({ hasMetrics: true });
setupStoreWithData(store); setupStoreWithData(store);
...@@ -285,13 +279,11 @@ describe('Dashboard', () => { ...@@ -285,13 +279,11 @@ describe('Dashboard', () => {
const panelGroup = metricsDashboardViewModel.panelGroups[0]; const panelGroup = metricsDashboardViewModel.panelGroups[0];
const panel = panelGroup.panels[0]; const panel = panelGroup.panels[0];
setSearch( setSearch({
objectToQuery({ group: panelGroup.group,
group: panelGroup.group, title: 'incorrect',
title: 'incorrect', y_label: panel.y_label,
y_label: panel.y_label, });
}),
);
createMountedWrapper({ hasMetrics: true }); createMountedWrapper({ hasMetrics: true });
setupStoreWithData(store); setupStoreWithData(store);
......
...@@ -2,6 +2,7 @@ import { GlEmptyState } from '@gitlab/ui'; ...@@ -2,6 +2,7 @@ import { GlEmptyState } from '@gitlab/ui';
import { mount, createLocalVue } from '@vue/test-utils'; import { mount, createLocalVue } from '@vue/test-utils';
import { nextTick } from 'vue'; import { nextTick } from 'vue';
import Vuex from 'vuex'; import Vuex from 'vuex';
import { useMockLocationHelper } from 'helpers/mock_window_location_helper';
import stubChildren from 'helpers/stub_children'; import stubChildren from 'helpers/stub_children';
import AdditionalMetadata from '~/packages/details/components/additional_metadata.vue'; import AdditionalMetadata from '~/packages/details/components/additional_metadata.vue';
...@@ -30,6 +31,8 @@ import { ...@@ -30,6 +31,8 @@ import {
const localVue = createLocalVue(); const localVue = createLocalVue();
localVue.use(Vuex); localVue.use(Vuex);
useMockLocationHelper();
describe('PackagesApp', () => { describe('PackagesApp', () => {
let wrapper; let wrapper;
let store; let store;
...@@ -37,7 +40,6 @@ describe('PackagesApp', () => { ...@@ -37,7 +40,6 @@ describe('PackagesApp', () => {
const deletePackage = jest.fn(); const deletePackage = jest.fn();
const deletePackageFile = jest.fn(); const deletePackageFile = jest.fn();
const defaultProjectName = 'bar'; const defaultProjectName = 'bar';
const { location } = window;
function createComponent({ function createComponent({
packageEntity = mavenPackage, packageEntity = mavenPackage,
...@@ -100,14 +102,8 @@ describe('PackagesApp', () => { ...@@ -100,14 +102,8 @@ describe('PackagesApp', () => {
const findInstallationCommands = () => wrapper.find(InstallationCommands); const findInstallationCommands = () => wrapper.find(InstallationCommands);
const findPackageFiles = () => wrapper.find(PackageFiles); const findPackageFiles = () => wrapper.find(PackageFiles);
beforeEach(() => {
delete window.location;
window.location = { replace: jest.fn() };
});
afterEach(() => { afterEach(() => {
wrapper.destroy(); wrapper.destroy();
window.location = location;
}); });
it('renders the app and displays the package title', async () => { it('renders the app and displays the package title', async () => {
......
import { GlEmptyState, GlSprintf, GlLink } from '@gitlab/ui'; import { GlEmptyState, GlSprintf, GlLink } from '@gitlab/ui';
import { shallowMount, createLocalVue } from '@vue/test-utils'; import { shallowMount, createLocalVue } from '@vue/test-utils';
import Vuex from 'vuex'; import Vuex from 'vuex';
import setWindowLocation from 'helpers/set_window_location_helper';
import createFlash from '~/flash'; import createFlash from '~/flash';
import * as commonUtils from '~/lib/utils/common_utils'; import * as commonUtils from '~/lib/utils/common_utils';
import PackageListApp from '~/packages/list/components/packages_list_app.vue'; import PackageListApp from '~/packages/list/components/packages_list_app.vue';
...@@ -233,21 +234,17 @@ describe('packages_list_app', () => { ...@@ -233,21 +234,17 @@ describe('packages_list_app', () => {
}); });
describe('delete alert handling', () => { describe('delete alert handling', () => {
const { location } = window.location; const originalLocation = window.location.href;
const search = `?${SHOW_DELETE_SUCCESS_ALERT}=true`; const search = `?${SHOW_DELETE_SUCCESS_ALERT}=true`;
beforeEach(() => { beforeEach(() => {
createStore(); createStore();
jest.spyOn(commonUtils, 'historyReplaceState').mockImplementation(() => {}); jest.spyOn(commonUtils, 'historyReplaceState').mockImplementation(() => {});
delete window.location; setWindowLocation(search);
window.location = {
href: `foo_bar_baz${search}`,
search,
};
}); });
afterEach(() => { afterEach(() => {
window.location = location; setWindowLocation(originalLocation);
}); });
it(`creates a flash if the query string contains ${SHOW_DELETE_SUCCESS_ALERT}`, () => { it(`creates a flash if the query string contains ${SHOW_DELETE_SUCCESS_ALERT}`, () => {
...@@ -262,11 +259,11 @@ describe('packages_list_app', () => { ...@@ -262,11 +259,11 @@ describe('packages_list_app', () => {
it('calls historyReplaceState with a clean url', () => { it('calls historyReplaceState with a clean url', () => {
mountComponent(); mountComponent();
expect(commonUtils.historyReplaceState).toHaveBeenCalledWith('foo_bar_baz'); expect(commonUtils.historyReplaceState).toHaveBeenCalledWith(originalLocation);
}); });
it(`does nothing if the query string does not contain ${SHOW_DELETE_SUCCESS_ALERT}`, () => { it(`does nothing if the query string does not contain ${SHOW_DELETE_SUCCESS_ALERT}`, () => {
window.location.search = ''; setWindowLocation('?');
mountComponent(); mountComponent();
expect(createFlash).not.toHaveBeenCalled(); expect(createFlash).not.toHaveBeenCalled();
......
import MockAdapter from 'axios-mock-adapter'; import MockAdapter from 'axios-mock-adapter';
import { useMockLocationHelper } from 'helpers/mock_window_location_helper';
import waitForPromises from 'helpers/wait_for_promises'; import waitForPromises from 'helpers/wait_for_promises';
import createFlash from '~/flash'; import createFlash from '~/flash';
import axios from '~/lib/utils/axios_utils'; import axios from '~/lib/utils/axios_utils';
...@@ -166,6 +167,8 @@ describe('PersistentUserCallout', () => { ...@@ -166,6 +167,8 @@ describe('PersistentUserCallout', () => {
let mockAxios; let mockAxios;
let persistentUserCallout; let persistentUserCallout;
useMockLocationHelper();
beforeEach(() => { beforeEach(() => {
const fixture = createFollowLinkFixture(); const fixture = createFollowLinkFixture();
const container = fixture.querySelector('.container'); const container = fixture.querySelector('.container');
...@@ -174,9 +177,6 @@ describe('PersistentUserCallout', () => { ...@@ -174,9 +177,6 @@ describe('PersistentUserCallout', () => {
persistentUserCallout = new PersistentUserCallout(container); persistentUserCallout = new PersistentUserCallout(container);
jest.spyOn(persistentUserCallout.container, 'remove').mockImplementation(() => {}); jest.spyOn(persistentUserCallout.container, 'remove').mockImplementation(() => {});
delete window.location;
window.location = { assign: jest.fn() };
}); });
afterEach(() => { afterEach(() => {
......
...@@ -2,6 +2,7 @@ import { GlAlert, GlButton, GlLoadingIcon, GlTabs } from '@gitlab/ui'; ...@@ -2,6 +2,7 @@ import { GlAlert, GlButton, GlLoadingIcon, GlTabs } from '@gitlab/ui';
import { shallowMount, createLocalVue } from '@vue/test-utils'; import { shallowMount, createLocalVue } from '@vue/test-utils';
import VueApollo from 'vue-apollo'; import VueApollo from 'vue-apollo';
import createMockApollo from 'helpers/mock_apollo_helper'; import createMockApollo from 'helpers/mock_apollo_helper';
import setWindowLocation from 'helpers/set_window_location_helper';
import waitForPromises from 'helpers/wait_for_promises'; import waitForPromises from 'helpers/wait_for_promises';
import CommitForm from '~/pipeline_editor/components/commit/commit_form.vue'; import CommitForm from '~/pipeline_editor/components/commit/commit_form.vue';
import TextEditor from '~/pipeline_editor/components/editor/text_editor.vue'; import TextEditor from '~/pipeline_editor/components/editor/text_editor.vue';
...@@ -348,15 +349,14 @@ describe('Pipeline editor app component', () => { ...@@ -348,15 +349,14 @@ describe('Pipeline editor app component', () => {
}); });
describe('when a template parameter is present in the URL', () => { describe('when a template parameter is present in the URL', () => {
const { location } = window; const originalLocation = window.location.href;
beforeEach(() => { beforeEach(() => {
delete window.location; setWindowLocation('?template=Android');
window.location = new URL('https://localhost?template=Android');
}); });
afterEach(() => { afterEach(() => {
window.location = location; setWindowLocation(originalLocation);
}); });
it('renders the given template', async () => { it('renders the given template', async () => {
......
import { GlButton } from '@gitlab/ui'; import { GlButton } from '@gitlab/ui';
import { shallowMount } from '@vue/test-utils'; import { shallowMount } from '@vue/test-utils';
import { nextTick } from 'vue'; import { nextTick } from 'vue';
import { useMockLocationHelper } from 'helpers/mock_window_location_helper';
import { extendedWrapper } from 'helpers/vue_test_utils_helper'; import { extendedWrapper } from 'helpers/vue_test_utils_helper';
import createFlash from '~/flash'; import createFlash from '~/flash';
import IntegrationView from '~/profile/preferences/components/integration_view.vue'; import IntegrationView from '~/profile/preferences/components/integration_view.vue';
...@@ -19,6 +20,8 @@ import { ...@@ -19,6 +20,8 @@ import {
jest.mock('~/flash'); jest.mock('~/flash');
const expectedUrl = '/foo'; const expectedUrl = '/foo';
useMockLocationHelper();
describe('ProfilePreferences component', () => { describe('ProfilePreferences component', () => {
let wrapper; let wrapper;
const defaultProvide = { const defaultProvide = {
...@@ -174,8 +177,6 @@ describe('ProfilePreferences component', () => { ...@@ -174,8 +177,6 @@ describe('ProfilePreferences component', () => {
}); });
describe('theme changes', () => { describe('theme changes', () => {
const { location } = window;
let themeInput; let themeInput;
let form; let form;
...@@ -197,18 +198,6 @@ describe('ProfilePreferences component', () => { ...@@ -197,18 +198,6 @@ describe('ProfilePreferences component', () => {
form.dispatchEvent(successEvent); form.dispatchEvent(successEvent);
} }
beforeAll(() => {
delete window.location;
window.location = {
...location,
reload: jest.fn(),
};
});
afterAll(() => {
window.location = location;
});
beforeEach(() => { beforeEach(() => {
setupBody(); setupBody();
themeInput = createThemeInput(); themeInput = createThemeInput();
......
import { GlButton, GlModal } from '@gitlab/ui'; import { GlButton, GlModal } from '@gitlab/ui';
import { mount } from '@vue/test-utils'; import { mount } from '@vue/test-utils';
import { ApolloMutation } from 'vue-apollo'; import { ApolloMutation } from 'vue-apollo';
import { useMockLocationHelper } from 'helpers/mock_window_location_helper';
import waitForPromises from 'helpers/wait_for_promises'; import waitForPromises from 'helpers/wait_for_promises';
import { Blob, BinaryBlob } from 'jest/blob/components/mock_data'; import { Blob, BinaryBlob } from 'jest/blob/components/mock_data';
import { differenceInMilliseconds } from '~/lib/utils/datetime_utility'; import { differenceInMilliseconds } from '~/lib/utils/datetime_utility';
import SnippetHeader from '~/snippets/components/snippet_header.vue'; import SnippetHeader from '~/snippets/components/snippet_header.vue';
import DeleteSnippetMutation from '~/snippets/mutations/deleteSnippet.mutation.graphql'; import DeleteSnippetMutation from '~/snippets/mutations/deleteSnippet.mutation.graphql';
useMockLocationHelper();
describe('Snippet header component', () => { describe('Snippet header component', () => {
let wrapper; let wrapper;
let snippet; let snippet;
...@@ -200,19 +203,6 @@ describe('Snippet header component', () => { ...@@ -200,19 +203,6 @@ describe('Snippet header component', () => {
}); });
describe('Delete mutation', () => { describe('Delete mutation', () => {
const { location } = window;
beforeEach(() => {
delete window.location;
window.location = {
pathname: '',
};
});
afterEach(() => {
window.location = location;
});
it('dispatches a mutation to delete the snippet with correct variables', () => { it('dispatches a mutation to delete the snippet with correct variables', () => {
createComponent(); createComponent();
wrapper.vm.deleteSnippet(); wrapper.vm.deleteSnippet();
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment