Fixed most tests using react-router-dom hooks

This commit is contained in:
Alejandro Celaya 2022-02-07 22:17:57 +01:00
parent 97024d828e
commit c4e928ff09
22 changed files with 177 additions and 175 deletions

View file

@ -17,6 +17,8 @@
"ignorePatterns": ["src/service*.ts"],
"rules": {
"complexity": "off",
"@typescript-eslint/no-unnecessary-type-assertion": "off"
"@typescript-eslint/no-unnecessary-type-assertion": "off",
"@typescript-eslint/no-unsafe-return": "off",
"@typescript-eslint/no-unsafe-call": "off"
}
}

View file

@ -1,9 +1,9 @@
import { FC, useEffect } from 'react';
import { pipe } from 'ramda';
import { useParams } from 'react-router-dom';
import { CreateVisit } from '../../visits/types';
import { MercureInfo } from '../reducers/mercureInfo';
import { bindToMercureTopic } from './index';
import { useParams } from 'react-router-dom';
export interface MercureBoundProps {
createNewVisits: (createdVisits: CreateVisit[]) => void;

View file

@ -1,7 +1,7 @@
import { pipe } from 'ramda';
import { FC, useEffect, useMemo, useState } from 'react';
import { Card } from 'reactstrap';
import { useParams } from 'react-router-dom';
import { useLocation, useParams } from 'react-router-dom';
import { OrderingDropdown } from '../utils/OrderingDropdown';
import { determineOrderDir, OrderDir } from '../utils/helpers/ordering';
import { getServerId, SelectedServer } from '../servers/data';
@ -31,6 +31,7 @@ const ShortUrlsList = (ShortUrlsTable: FC<ShortUrlsTableProps>, ShortUrlsFilteri
}: ShortUrlsListProps) => {
const serverId = getServerId(selectedServer);
const { page } = useParams();
const location = useLocation();
const [{ tags, search, startDate, endDate, orderBy }, toFirstPage ] = useShortUrlsQuery();
const [ actualOrderBy, setActualOrderBy ] = useState(
// This separated state handling is needed to be able to fall back to settings value, but only once when loaded

View file

@ -1,7 +1,7 @@
import { useState, useRef, EffectCallback, DependencyList, useEffect } from 'react';
import { useSwipeable as useReactSwipeable } from 'react-swipeable';
import { parseQuery, stringifyQuery } from './query';
import { useNavigate } from 'react-router-dom';
import { parseQuery, stringifyQuery } from './query';
const DEFAULT_DELAY = 2000;

View file

@ -1,12 +1,15 @@
import { shallow, ShallowWrapper } from 'enzyme';
import { Route } from 'react-router-dom';
import { Route, useLocation } from 'react-router-dom';
import { Mock } from 'ts-mockery';
import { match } from 'react-router';
import { History, Location } from 'history';
import { Settings } from '../../src/settings/reducers/settings';
import appFactory from '../../src/app/App';
import { AppUpdateBanner } from '../../src/common/AppUpdateBanner';
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useLocation: jest.fn().mockReturnValue({}),
}));
describe('<App />', () => {
let wrapper: ShallowWrapper;
const MainHeader = () => null;
@ -21,7 +24,7 @@ describe('<App />', () => {
() => null,
ShlinkVersions,
);
const createWrapper = (pathname = '') => {
const createWrapper = () => {
wrapper = shallow(
<App
fetchServers={() => {}}
@ -29,16 +32,14 @@ describe('<App />', () => {
settings={Mock.all<Settings>()}
appUpdated={false}
resetAppUpdate={() => {}}
match={Mock.all<match>()}
history={Mock.all<History>()}
location={Mock.of<Location>({ pathname })}
/>,
);
return wrapper;
};
afterEach(() => wrapper.unmount());
afterEach(jest.clearAllMocks);
afterEach(() => wrapper?.unmount());
it('renders children components', () => {
const wrapper = createWrapper();
@ -52,12 +53,12 @@ describe('<App />', () => {
const wrapper = createWrapper();
const routes = wrapper.find(Route);
const expectedPaths = [
'/',
undefined,
'/settings',
'/manage-servers',
'/server/create',
'/server/:serverId/edit',
'/server/:serverId',
'/server/:serverId/*',
];
expect.assertions(expectedPaths.length + 1);
@ -72,7 +73,9 @@ describe('<App />', () => {
[ '/bar', 'shlink-wrapper' ],
[ '/', 'shlink-wrapper d-flex d-md-block align-items-center' ],
])('renders expected classes on shlink-wrapper based on current pathname', (pathname, expectedClasses) => {
const wrapper = createWrapper(pathname);
(useLocation as any).mockReturnValue({ pathname }); // eslint-disable-line @typescript-eslint/no-unsafe-call
const wrapper = createWrapper();
const shlinkWrapper = wrapper.find('.shlink-wrapper');
expect(shlinkWrapper.prop('className')).toEqual(expectedClasses);

View file

@ -3,6 +3,11 @@ import { Mock } from 'ts-mockery';
import asideMenuCreator from '../../src/common/AsideMenu';
import { ReachableServer } from '../../src/servers/data';
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useLocation: jest.fn().mockReturnValue({ pathname: '' }),
}));
describe('<AsideMenu />', () => {
let wrapped: ShallowWrapper;
const DeleteServerButton = () => null;

View file

@ -1,19 +1,18 @@
import { shallow, ShallowWrapper } from 'enzyme';
import { Mock } from 'ts-mockery';
import { RouteChildrenProps } from 'react-router-dom';
import Home, { HomeProps } from '../../src/common/Home';
import { ServerWithId } from '../../src/servers/data';
import { ShlinkLogo } from '../../src/common/img/ShlinkLogo';
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useNavigate: jest.fn().mockReturnValue(jest.fn()),
}));
describe('<Home />', () => {
let wrapped: ShallowWrapper;
const defaultProps = {
...Mock.all<RouteChildrenProps>(),
resetSelectedServer: jest.fn(),
servers: {},
};
const createComponent = (props: Partial<HomeProps> = {}) => {
const actualProps = { ...defaultProps, ...props };
const actualProps = { resetSelectedServer: jest.fn(), servers: {}, ...props };
wrapped = shallow(<Home {...actualProps} />);

View file

@ -1,24 +1,28 @@
import { shallow, ShallowWrapper } from 'enzyme';
import { Mock } from 'ts-mockery';
import { match } from 'react-router';
import { History, Location } from 'history';
import { useLocation } from 'react-router-dom';
import { Collapse, NavbarToggler, NavLink } from 'reactstrap';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import createMainHeader from '../../src/common/MainHeader';
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useLocation: jest.fn().mockReturnValue({}),
}));
describe('<MainHeader />', () => {
const ServersDropdown = () => null;
const MainHeader = createMainHeader(ServersDropdown);
let wrapper: ShallowWrapper;
const createWrapper = (pathname = '') => {
const location = Mock.of<Location>({ pathname });
(useLocation as any).mockReturnValue({ pathname });
wrapper = shallow(<MainHeader history={Mock.all<History>()} location={location} match={Mock.all<match>()} />);
wrapper = shallow(<MainHeader />);
return wrapper;
};
afterEach(jest.clearAllMocks);
afterEach(() => wrapper?.unmount());
it('renders ServersDropdown', () => {

View file

@ -1,34 +1,31 @@
import { shallow, ShallowWrapper } from 'enzyme';
import { History, Location } from 'history';
import { match } from 'react-router'; // eslint-disable-line @typescript-eslint/no-unused-vars
import { Route } from 'react-router-dom';
import { Route, useParams } from 'react-router-dom';
import { Mock } from 'ts-mockery';
import createMenuLayout from '../../src/common/MenuLayout';
import { NonReachableServer, NotFoundServer, ReachableServer, SelectedServer } from '../../src/servers/data';
import { NoMenuLayout } from '../../src/common/NoMenuLayout';
import { SemVer } from '../../src/utils/helpers/version';
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useParams: jest.fn().mockReturnValue({}),
useLocation: jest.fn().mockReturnValue({}),
}));
describe('<MenuLayout />', () => {
const ServerError = jest.fn();
const C = jest.fn();
const MenuLayout = createMenuLayout(C, C, C, C, C, C, C, C, ServerError, C, C, C);
let wrapper: ShallowWrapper;
const createWrapper = (selectedServer: SelectedServer) => {
wrapper = shallow(
<MenuLayout
selectServer={jest.fn()}
selectedServer={selectedServer}
history={Mock.all<History>()}
location={Mock.all<Location>()}
match={Mock.of<match<{ serverId: string }>>({
params: { serverId: 'abc123' },
})}
/>,
);
(useParams as any).mockReturnValue({ serverId: 'abc123' });
wrapper = shallow(<MenuLayout selectServer={jest.fn()} selectedServer={selectedServer} />);
return wrapper;
};
afterEach(jest.clearAllMocks);
afterEach(() => wrapper?.unmount());
it.each([
@ -49,17 +46,18 @@ describe('<MenuLayout />', () => {
});
it.each([
[ '2.5.0' as SemVer, 8 ],
[ '2.6.0' as SemVer, 9 ],
[ '2.7.0' as SemVer, 9 ],
[ '2.8.0' as SemVer, 10 ],
[ '2.10.0' as SemVer, 10 ],
[ '3.0.0' as SemVer, 11 ],
[ '2.5.0' as SemVer, 9 ],
[ '2.6.0' as SemVer, 10 ],
[ '2.7.0' as SemVer, 10 ],
[ '2.8.0' as SemVer, 11 ],
[ '2.10.0' as SemVer, 11 ],
[ '3.0.0' as SemVer, 12 ],
])('has expected amount of routes based on selected server\'s version', (version, expectedAmountOfRoutes) => {
const selectedServer = Mock.of<ReachableServer>({ version });
const wrapper = createWrapper(selectedServer).dive();
const routes = wrapper.find(Route);
expect(routes).toHaveLength(expectedAmountOfRoutes);
expect(routes.findWhere((element) => element.prop('index'))).toHaveLength(1);
});
});

View file

@ -1,15 +1,18 @@
import { shallow, ShallowWrapper } from 'enzyme';
import { Mock } from 'ts-mockery';
import { RouteComponentProps } from 'react-router';
import createScrollToTop from '../../src/common/ScrollToTop';
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useLocation: jest.fn().mockReturnValue({}),
}));
describe('<ScrollToTop />', () => {
let wrapper: ShallowWrapper;
beforeEach(() => {
const ScrollToTop = createScrollToTop();
wrapper = shallow(<ScrollToTop {...Mock.all<RouteComponentProps>()}>Foobar</ScrollToTop>);
wrapper = shallow(<ScrollToTop>Foobar</ScrollToTop>);
});
afterEach(() => wrapper.unmount());

View file

@ -1,27 +1,29 @@
import { shallow, ShallowWrapper } from 'enzyme';
import { Mock } from 'ts-mockery';
import { History } from 'history';
import { useNavigate } from 'react-router-dom';
import createServerConstruct from '../../src/servers/CreateServer';
import { ServerForm } from '../../src/servers/helpers/ServerForm';
import { ServerWithId } from '../../src/servers/data';
import { DuplicatedServersModal } from '../../src/servers/helpers/DuplicatedServersModal';
jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom'), useNavigate: jest.fn() }));
describe('<CreateServer />', () => {
let wrapper: ShallowWrapper;
const ImportServersBtn = () => null;
const createServerMock = jest.fn();
const push = jest.fn();
const goBack = jest.fn();
const historyMock = Mock.of<History>({ push, goBack });
const navigate = jest.fn();
const servers = { foo: Mock.all<ServerWithId>() };
const createWrapper = (serversImported = false, importFailed = false) => {
(useNavigate as any).mockReturnValue(navigate);
const useStateFlagTimeout = jest.fn()
.mockReturnValueOnce([ serversImported, () => '' ])
.mockReturnValueOnce([ importFailed, () => '' ])
.mockReturnValue([]);
const CreateServer = createServerConstruct(ImportServersBtn, useStateFlagTimeout);
wrapper = shallow(<CreateServer createServer={createServerMock} history={historyMock} servers={servers} />);
wrapper = shallow(<CreateServer createServer={createServerMock} servers={servers} />);
return wrapper;
};
@ -68,7 +70,7 @@ describe('<CreateServer />', () => {
wrapper.find(DuplicatedServersModal).simulate('save');
expect(createServerMock).toHaveBeenCalledTimes(1);
expect(push).toHaveBeenCalledTimes(1);
expect(navigate).toHaveBeenCalledTimes(1);
});
it('goes back on modal discard', () => {
@ -76,6 +78,6 @@ describe('<CreateServer />', () => {
wrapper.find(DuplicatedServersModal).simulate('discard');
expect(goBack).toHaveBeenCalledTimes(1);
expect(navigate).toHaveBeenCalledWith(-1);
});
});

View file

@ -1,25 +1,28 @@
import { shallow, ShallowWrapper } from 'enzyme';
import { Modal, ModalBody, ModalFooter, ModalHeader } from 'reactstrap';
import { History } from 'history';
import { Mock } from 'ts-mockery';
import { useNavigate } from 'react-router-dom';
import DeleteServerModal from '../../src/servers/DeleteServerModal';
import { ServerWithId } from '../../src/servers/data';
jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom'), useNavigate: jest.fn() }));
describe('<DeleteServerModal />', () => {
let wrapper: ShallowWrapper;
const deleteServerMock = jest.fn();
const push = jest.fn();
const navigate = jest.fn();
const toggleMock = jest.fn();
const serverName = 'the_server_name';
beforeEach(() => {
(useNavigate as any).mockReturnValue(navigate);
wrapper = shallow(
<DeleteServerModal
server={Mock.of<ServerWithId>({ name: serverName })}
toggle={toggleMock}
isOpen={true}
deleteServer={deleteServerMock}
history={Mock.of<History>({ push })}
/>,
);
});
@ -48,7 +51,7 @@ describe('<DeleteServerModal />', () => {
expect(toggleMock).toHaveBeenCalledTimes(1);
expect(deleteServerMock).not.toHaveBeenCalled();
expect(push).not.toHaveBeenCalled();
expect(navigate).not.toHaveBeenCalled();
});
it('deletes server when clicking accept button', () => {
@ -58,6 +61,6 @@ describe('<DeleteServerModal />', () => {
expect(toggleMock).toHaveBeenCalledTimes(1);
expect(deleteServerMock).toHaveBeenCalledTimes(1);
expect(push).toHaveBeenCalledTimes(1);
expect(navigate).toHaveBeenCalledTimes(1);
});
});

View file

@ -1,43 +1,34 @@
import { mount, ReactWrapper } from 'enzyme';
import { Mock } from 'ts-mockery';
import { History, Location } from 'history';
import { match } from 'react-router'; // eslint-disable-line @typescript-eslint/no-unused-vars
import { useNavigate } from 'react-router-dom';
import { EditServer as editServerConstruct } from '../../src/servers/EditServer';
import { ServerForm } from '../../src/servers/helpers/ServerForm';
import { ReachableServer } from '../../src/servers/data';
jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom'), useNavigate: jest.fn() }));
describe('<EditServer />', () => {
let wrapper: ReactWrapper;
const ServerError = jest.fn();
const editServerMock = jest.fn();
const goBack = jest.fn();
const historyMock = Mock.of<History>({ goBack });
const match = Mock.of<match<{ serverId: string }>>({
params: { serverId: 'abc123' },
});
const navigate = jest.fn();
const selectedServer = Mock.of<ReachableServer>({
id: 'abc123',
name: 'name',
url: 'url',
apiKey: 'apiKey',
});
const EditServer = editServerConstruct(ServerError);
beforeEach(() => {
const EditServer = editServerConstruct(ServerError);
(useNavigate as any).mockReturnValue(navigate);
wrapper = mount(
<EditServer
editServer={editServerMock}
history={historyMock}
match={match}
location={Mock.all<Location>()}
selectedServer={selectedServer}
selectServer={jest.fn()}
/>,
<EditServer editServer={editServerMock} selectedServer={selectedServer} selectServer={jest.fn()} />,
);
});
afterEach(jest.resetAllMocks);
afterEach(jest.clearAllMocks);
afterEach(() => wrapper?.unmount());
it('renders components', () => {
@ -50,6 +41,6 @@ describe('<EditServer />', () => {
form.simulate('submit', {});
expect(editServerMock).toHaveBeenCalledTimes(1);
expect(goBack).toHaveBeenCalledTimes(1);
expect(navigate).toHaveBeenCalledWith(-1);
});
});

View file

@ -1,7 +1,6 @@
import { shallow, ShallowWrapper } from 'enzyme';
import { Mock } from 'ts-mockery';
import { History, Location } from 'history';
import { match } from 'react-router'; // eslint-disable-line @typescript-eslint/no-unused-vars
import { useLocation, useParams } from 'react-router-dom';
import { EditShortUrl as createEditShortUrl } from '../../src/short-urls/EditShortUrl';
import { Settings } from '../../src/settings/reducers/settings';
import { ShortUrlDetail } from '../../src/short-urls/reducers/shortUrlDetail';
@ -9,29 +8,32 @@ import { ShortUrlEdition } from '../../src/short-urls/reducers/shortUrlEdition';
import { ShlinkApiError } from '../../src/api/ShlinkApiError';
import { ShortUrl } from '../../src/short-urls/data';
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useNavigate: jest.fn().mockReturnValue(jest.fn()),
useParams: jest.fn().mockReturnValue({}),
useLocation: jest.fn().mockReturnValue({}),
}));
describe('<EditShortUrl />', () => {
let wrapper: ShallowWrapper;
const ShortUrlForm = () => null;
const goBack = jest.fn();
const getShortUrlDetail = jest.fn();
const editShortUrl = jest.fn(async () => Promise.resolve());
const shortUrlCreation = { validateUrls: true };
const EditShortUrl = createEditShortUrl(ShortUrlForm);
const createWrapper = (detail: Partial<ShortUrlDetail> = {}, edition: Partial<ShortUrlEdition> = {}) => {
const EditSHortUrl = createEditShortUrl(ShortUrlForm);
(useParams as any).mockReturnValue({ shortCode: 'the_base_url' });
(useLocation as any).mockReturnValue({ search: '' });
wrapper = shallow(
<EditSHortUrl
<EditShortUrl
settings={Mock.of<Settings>({ shortUrlCreation })}
selectedServer={null}
shortUrlDetail={Mock.of<ShortUrlDetail>(detail)}
shortUrlEdition={Mock.of<ShortUrlEdition>(edition)}
getShortUrlDetail={getShortUrlDetail}
editShortUrl={editShortUrl}
history={Mock.of<History>({ goBack })}
location={Mock.all<Location>()}
match={Mock.of<match<{ shortCode: string }>>({
params: { shortCode: 'the_base_url' },
})}
/>,
);

View file

@ -1,29 +1,30 @@
import { shallow, ShallowWrapper } from 'enzyme';
import { Mock } from 'ts-mockery';
import { History, Location } from 'history';
import { match } from 'react-router';
import { formatISO } from 'date-fns';
import filteringBarCreator, { ShortUrlsFilteringProps } from '../../src/short-urls/ShortUrlsFilteringBar';
import { useLocation, useNavigate } from 'react-router-dom';
import filteringBarCreator from '../../src/short-urls/ShortUrlsFilteringBar';
import SearchField from '../../src/utils/SearchField';
import Tag from '../../src/tags/helpers/Tag';
import { DateRangeSelector } from '../../src/utils/dates/DateRangeSelector';
import ColorGenerator from '../../src/utils/services/ColorGenerator';
import { ShortUrlListRouteParams } from '../../src/short-urls/helpers/hooks';
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useNavigate: jest.fn(),
useParams: jest.fn().mockReturnValue({ serverId: '1' }),
useLocation: jest.fn().mockReturnValue({}),
}));
describe('<ShortUrlsFilteringBar />', () => {
let wrapper: ShallowWrapper;
const ShortUrlsFilteringBar = filteringBarCreator(Mock.all<ColorGenerator>());
const push = jest.fn();
const navigate = jest.fn();
const now = new Date();
const createWrapper = (props: Partial<ShortUrlsFilteringProps> = {}) => {
wrapper = shallow(
<ShortUrlsFilteringBar
history={Mock.of<History>({ push })}
location={Mock.of<Location>({ search: '' })}
match={Mock.of<match<ShortUrlListRouteParams>>({ params: { serverId: '1' } })}
{...props}
/>,
);
const createWrapper = (search = '') => {
(useLocation as any).mockReturnValue({ search });
(useNavigate as any).mockReturnValue(navigate);
wrapper = shallow(<ShortUrlsFilteringBar />);
return wrapper;
};
@ -44,7 +45,7 @@ describe('<ShortUrlsFilteringBar />', () => {
[ '', 0 ],
[ 'foo=bar', 0 ],
])('renders the proper amount of tags', (search, expectedTagComps) => {
const wrapper = createWrapper({ location: Mock.of<Location>({ search }) });
const wrapper = createWrapper(search);
expect(wrapper.find(Tag)).toHaveLength(expectedTagComps);
});
@ -53,18 +54,18 @@ describe('<ShortUrlsFilteringBar />', () => {
const wrapper = createWrapper();
const searchField = wrapper.find(SearchField);
expect(push).not.toHaveBeenCalled();
expect(navigate).not.toHaveBeenCalled();
searchField.simulate('change', 'search-term');
expect(push).toHaveBeenCalledWith('/server/1/list-short-urls/1?search=search-term');
expect(navigate).toHaveBeenCalledWith('/server/1/list-short-urls/1?search=search-term');
});
it('redirects to first page when a tag is removed', () => {
const wrapper = createWrapper({ location: Mock.of<Location>({ search: 'tags=foo,bar' }) });
const wrapper = createWrapper('tags=foo,bar');
const tag = wrapper.find(Tag).first();
expect(push).not.toHaveBeenCalled();
expect(navigate).not.toHaveBeenCalled();
tag.simulate('close');
expect(push).toHaveBeenCalledWith('/server/1/list-short-urls/1?tags=bar');
expect(navigate).toHaveBeenCalledWith('/server/1/list-short-urls/1?tags=bar');
});
it.each([
@ -78,8 +79,8 @@ describe('<ShortUrlsFilteringBar />', () => {
const wrapper = createWrapper();
const dateRange = wrapper.find(DateRangeSelector);
expect(push).not.toHaveBeenCalled();
expect(navigate).not.toHaveBeenCalled();
dateRange.simulate('datesChange', dates);
expect(push).toHaveBeenCalledWith(`/server/1/list-short-urls/1?${expectedQuery}`);
expect(navigate).toHaveBeenCalledWith(`/server/1/list-short-urls/1?${expectedQuery}`);
});
});

View file

@ -1,8 +1,7 @@
import { shallow, ShallowWrapper } from 'enzyme';
import { ReactElement } from 'react';
import { Mock } from 'ts-mockery';
import { History, Location } from 'history';
import { match } from 'react-router';
import { useNavigate } from 'react-router-dom';
import shortUrlsListCreator from '../../src/short-urls/ShortUrlsList';
import { ShortUrlsOrderableFields, ShortUrl, ShortUrlsOrder } from '../../src/short-urls/data';
import { MercureBoundProps } from '../../src/mercure/helpers/boundToMercureHub';
@ -10,15 +9,21 @@ import { ShortUrlsList as ShortUrlsListModel } from '../../src/short-urls/reduce
import { OrderingDropdown } from '../../src/utils/OrderingDropdown';
import Paginator from '../../src/short-urls/Paginator';
import { ReachableServer } from '../../src/servers/data';
import { ShortUrlListRouteParams } from '../../src/short-urls/helpers/hooks';
import { Settings } from '../../src/settings/reducers/settings';
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useNavigate: jest.fn().mockReturnValue(jest.fn()),
useParams: jest.fn().mockReturnValue({}),
useLocation: jest.fn().mockReturnValue({ search: '?tags=test%20tag&search=example.com' }),
}));
describe('<ShortUrlsList />', () => {
let wrapper: ShallowWrapper;
const ShortUrlsTable = () => null;
const ShortUrlsFilteringBar = () => null;
const listShortUrlsMock = jest.fn();
const push = jest.fn();
const navigate = jest.fn();
const shortUrlsList = Mock.of<ShortUrlsListModel>({
shortUrls: {
data: [
@ -36,20 +41,19 @@ describe('<ShortUrlsList />', () => {
<ShortUrlsList
{...Mock.of<MercureBoundProps>({ mercureInfo: { loading: true } })}
listShortUrls={listShortUrlsMock}
match={Mock.of<match<ShortUrlListRouteParams>>({ params: {} })}
location={Mock.of<Location>({ search: '?tags=test%20tag&search=example.com' })}
shortUrlsList={shortUrlsList}
history={Mock.of<History>({ push })}
selectedServer={Mock.of<ReachableServer>({ id: '1' })}
settings={Mock.of<Settings>({ shortUrlsList: { defaultOrdering } })}
/>,
).dive(); // Dive is needed as this component is wrapped in a HOC
beforeEach(() => {
(useNavigate as any).mockReturnValue(navigate);
wrapper = createWrapper();
});
afterEach(jest.resetAllMocks);
afterEach(jest.clearAllMocks);
afterEach(() => wrapper?.unmount());
it('wraps expected components', () => {
@ -68,10 +72,10 @@ describe('<ShortUrlsList />', () => {
wrapper.find(ShortUrlsTable).simulate('tagClick', 'bar');
wrapper.find(ShortUrlsTable).simulate('tagClick', 'baz');
expect(push).toHaveBeenCalledTimes(3);
expect(push).toHaveBeenNthCalledWith(1, expect.stringContaining(`tags=${encodeURIComponent('test tag,foo')}`));
expect(push).toHaveBeenNthCalledWith(2, expect.stringContaining(`tags=${encodeURIComponent('test tag,bar')}`));
expect(push).toHaveBeenNthCalledWith(3, expect.stringContaining(`tags=${encodeURIComponent('test tag,baz')}`));
expect(navigate).toHaveBeenCalledTimes(3);
expect(navigate).toHaveBeenNthCalledWith(1, expect.stringContaining(`tags=${encodeURIComponent('test tag,foo')}`));
expect(navigate).toHaveBeenNthCalledWith(2, expect.stringContaining(`tags=${encodeURIComponent('test tag,bar')}`));
expect(navigate).toHaveBeenNthCalledWith(3, expect.stringContaining(`tags=${encodeURIComponent('test tag,baz')}`));
});
it('invokes order icon rendering', () => {

View file

@ -1,13 +1,14 @@
import { Mock } from 'ts-mockery';
import { shallow, ShallowWrapper } from 'enzyme';
import { match } from 'react-router';
import { Location, History } from 'history';
import { useLocation } from 'react-router-dom';
import { TagsTable as createTagsTable } from '../../src/tags/TagsTable';
import { SelectedServer } from '../../src/servers/data';
import { rangeOf } from '../../src/utils/utils';
import SimplePaginator from '../../src/common/SimplePaginator';
import { NormalizedTag } from '../../src/tags/data';
jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom'), useLocation: jest.fn() }));
describe('<TagsTable />', () => {
const TagsTableRow = () => null;
const orderByColumn = jest.fn();
@ -15,14 +16,13 @@ describe('<TagsTable />', () => {
const tags = (amount: number) => rangeOf(amount, (i) => `tag_${i}`);
let wrapper: ShallowWrapper;
const createWrapper = (sortedTags: string[] = [], search = '') => {
(useLocation as any).mockReturnValue({ search });
wrapper = shallow(
<TagsTable
sortedTags={sortedTags.map((tag) => Mock.of<NormalizedTag>({ tag }))}
selectedServer={Mock.all<SelectedServer>()}
currentOrder={{}}
history={Mock.all<History>()}
location={Mock.of<Location>({ search })}
match={Mock.all<match>()}
orderByColumn={() => orderByColumn}
/>,
);
@ -30,11 +30,6 @@ describe('<TagsTable />', () => {
return wrapper;
};
beforeEach(() => {
(global as any).location = { search: '', pathname: '' };
(global as any).history = { pushState: jest.fn() };
});
afterEach(jest.clearAllMocks);
afterEach(() => wrapper?.unmount());

View file

@ -1,7 +1,5 @@
import { shallow } from 'enzyme';
import { Mock } from 'ts-mockery';
import { History, Location } from 'history';
import { match } from 'react-router';
import { NonOrphanVisits as createNonOrphanVisits } from '../../src/visits/NonOrphanVisits';
import { MercureBoundProps } from '../../src/mercure/helpers/boundToMercureHub';
import { VisitsInfo } from '../../src/visits/types';
@ -11,9 +9,14 @@ import { Settings } from '../../src/settings/reducers/settings';
import { VisitsExporter } from '../../src/visits/services/VisitsExporter';
import { SelectedServer } from '../../src/servers/data';
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useNavigate: jest.fn().mockReturnValue(jest.fn()),
useParams: jest.fn().mockReturnValue({}),
}));
describe('<NonOrphanVisits />', () => {
it('wraps visits stats and header', () => {
const goBack = jest.fn();
const getNonOrphanVisits = jest.fn();
const cancelGetNonOrphanVisits = jest.fn();
const nonOrphanVisits = Mock.all<VisitsInfo>();
@ -25,9 +28,6 @@ describe('<NonOrphanVisits />', () => {
getNonOrphanVisits={getNonOrphanVisits}
nonOrphanVisits={nonOrphanVisits}
cancelGetNonOrphanVisits={cancelGetNonOrphanVisits}
history={Mock.of<History>({ goBack })}
location={Mock.all<Location>()}
match={Mock.of<match>({ url: 'the_base_url' })}
settings={Mock.all<Settings>()}
selectedServer={Mock.all<SelectedServer>()}
/>,
@ -39,9 +39,8 @@ describe('<NonOrphanVisits />', () => {
expect(header).toHaveLength(1);
expect(stats.prop('cancelGetVisits')).toEqual(cancelGetNonOrphanVisits);
expect(stats.prop('visitsInfo')).toEqual(nonOrphanVisits);
expect(stats.prop('baseUrl')).toEqual('the_base_url');
expect(stats.prop('isOrphanVisits')).not.toBeDefined();
expect(header.prop('nonOrphanVisits')).toEqual(nonOrphanVisits);
expect(header.prop('goBack')).toEqual(goBack);
expect(header.prop('goBack')).toEqual(expect.any(Function));
});
});

View file

@ -1,7 +1,5 @@
import { shallow } from 'enzyme';
import { Mock } from 'ts-mockery';
import { History, Location } from 'history';
import { match } from 'react-router';
import { OrphanVisits as createOrphanVisits } from '../../src/visits/OrphanVisits';
import { MercureBoundProps } from '../../src/mercure/helpers/boundToMercureHub';
import { VisitsInfo } from '../../src/visits/types';
@ -11,9 +9,14 @@ import { Settings } from '../../src/settings/reducers/settings';
import { VisitsExporter } from '../../src/visits/services/VisitsExporter';
import { SelectedServer } from '../../src/servers/data';
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useNavigate: jest.fn().mockReturnValue(jest.fn()),
useParams: jest.fn().mockReturnValue({}),
}));
describe('<OrphanVisits />', () => {
it('wraps visits stats and header', () => {
const goBack = jest.fn();
const getOrphanVisits = jest.fn();
const cancelGetOrphanVisits = jest.fn();
const orphanVisits = Mock.all<VisitsInfo>();
@ -25,9 +28,6 @@ describe('<OrphanVisits />', () => {
getOrphanVisits={getOrphanVisits}
orphanVisits={orphanVisits}
cancelGetOrphanVisits={cancelGetOrphanVisits}
history={Mock.of<History>({ goBack })}
location={Mock.all<Location>()}
match={Mock.of<match>({ url: 'the_base_url' })}
settings={Mock.all<Settings>()}
selectedServer={Mock.all<SelectedServer>()}
/>,
@ -39,9 +39,8 @@ describe('<OrphanVisits />', () => {
expect(header).toHaveLength(1);
expect(stats.prop('cancelGetVisits')).toEqual(cancelGetOrphanVisits);
expect(stats.prop('visitsInfo')).toEqual(orphanVisits);
expect(stats.prop('baseUrl')).toEqual('the_base_url');
expect(stats.prop('isOrphanVisits')).toEqual(true);
expect(header.prop('orphanVisits')).toEqual(orphanVisits);
expect(header.prop('goBack')).toEqual(goBack);
expect(header.prop('goBack')).toEqual(expect.any(Function));
});
});

View file

@ -1,8 +1,6 @@
import { shallow, ShallowWrapper } from 'enzyme';
import { identity } from 'ramda';
import { Mock } from 'ts-mockery';
import { History, Location } from 'history';
import { match } from 'react-router'; // eslint-disable-line @typescript-eslint/no-unused-vars
import createShortUrlVisits, { ShortUrlVisitsProps } from '../../src/visits/ShortUrlVisits';
import ShortUrlVisitsHeader from '../../src/visits/ShortUrlVisitsHeader';
import { ShortUrlVisits as ShortUrlVisitsState } from '../../src/visits/reducers/shortUrlVisits';
@ -11,16 +9,16 @@ import VisitsStats from '../../src/visits/VisitsStats';
import { MercureBoundProps } from '../../src/mercure/helpers/boundToMercureHub';
import { VisitsExporter } from '../../src/visits/services/VisitsExporter';
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useNavigate: jest.fn().mockReturnValue(jest.fn()),
useLocation: jest.fn().mockReturnValue({ search: '' }),
useParams: jest.fn().mockReturnValue({ shortCode: 'abc123' }),
}));
describe('<ShortUrlVisits />', () => {
let wrapper: ShallowWrapper;
const getShortUrlVisitsMock = jest.fn();
const match = Mock.of<match<{ shortCode: string }>>({
params: { shortCode: 'abc123' },
});
const location = Mock.of<Location>({ search: '' });
const history = Mock.of<History>({
goBack: jest.fn(),
});
const ShortUrlVisits = createShortUrlVisits(Mock.all<VisitsExporter>());
beforeEach(() => {
@ -30,9 +28,6 @@ describe('<ShortUrlVisits />', () => {
{...Mock.of<MercureBoundProps>({ mercureInfo: {} })}
getShortUrlDetail={identity}
getShortUrlVisits={getShortUrlVisitsMock}
match={match}
location={location}
history={history}
shortUrlVisits={Mock.of<ShortUrlVisitsState>({ loading: true, visits: [] })}
shortUrlDetail={Mock.all<ShortUrlDetail>()}
cancelGetShortUrlVisits={() => {}}
@ -40,8 +35,8 @@ describe('<ShortUrlVisits />', () => {
).dive(); // Dive is needed as this component is wrapped in a HOC
});
afterEach(jest.clearAllMocks);
afterEach(() => wrapper.unmount());
afterEach(jest.resetAllMocks);
it('renders visit stats and visits header', () => {
const visitStats = wrapper.find(VisitsStats);

View file

@ -1,7 +1,5 @@
import { shallow, ShallowWrapper } from 'enzyme';
import { Mock } from 'ts-mockery';
import { History } from 'history';
import { match } from 'react-router'; // eslint-disable-line @typescript-eslint/no-unused-vars
import createTagVisits, { TagVisitsProps } from '../../src/visits/TagVisits';
import TagVisitsHeader from '../../src/visits/TagVisitsHeader';
import ColorGenerator from '../../src/utils/services/ColorGenerator';
@ -10,15 +8,16 @@ import VisitsStats from '../../src/visits/VisitsStats';
import { MercureBoundProps } from '../../src/mercure/helpers/boundToMercureHub';
import { VisitsExporter } from '../../src/visits/services/VisitsExporter';
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useNavigate: jest.fn().mockReturnValue(jest.fn()),
useLocation: jest.fn().mockReturnValue({}),
useParams: jest.fn().mockReturnValue({ tag: 'foo' }),
}));
describe('<TagVisits />', () => {
let wrapper: ShallowWrapper;
const getTagVisitsMock = jest.fn();
const match = Mock.of<match<{ tag: string }>>({
params: { tag: 'foo' },
});
const history = Mock.of<History>({
goBack: jest.fn(),
});
beforeEach(() => {
const TagVisits = createTagVisits(Mock.all<ColorGenerator>(), Mock.all<VisitsExporter>());
@ -28,8 +27,6 @@ describe('<TagVisits />', () => {
{...Mock.all<TagVisitsProps>()}
{...Mock.of<MercureBoundProps>({ mercureInfo: {} })}
getTagVisits={getTagVisitsMock}
match={match}
history={history}
tagVisits={Mock.of<TagVisitsStats>({ loading: true, visits: [] })}
cancelGetTagVisits={() => {}}
/>,

View file

@ -12,7 +12,7 @@ import { SelectedServer } from '../../src/servers/data';
import { SortableBarChartCard } from '../../src/visits/charts/SortableBarChartCard';
import { DoughnutChartCard } from '../../src/visits/charts/DoughnutChartCard';
describe('<VisitStats />', () => {
describe('<VisitsStats />', () => {
const visits = [ Mock.all<Visit>(), Mock.all<Visit>(), Mock.all<Visit>() ];
let wrapper: ShallowWrapper;
@ -25,7 +25,6 @@ describe('<VisitStats />', () => {
getVisits={getVisitsMock}
visitsInfo={Mock.of<VisitsInfo>(visitsInfo)}
cancelGetVisits={() => {}}
baseUrl={''}
settings={Mock.all<Settings>()}
exportCsv={exportCsv}
selectedServer={Mock.all<SelectedServer>()}