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