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"], "ignorePatterns": ["src/service*.ts"],
"rules": { "rules": {
"complexity": "off", "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 { FC, useEffect } from 'react';
import { pipe } from 'ramda'; import { pipe } from 'ramda';
import { useParams } from 'react-router-dom';
import { CreateVisit } from '../../visits/types'; import { CreateVisit } from '../../visits/types';
import { MercureInfo } from '../reducers/mercureInfo'; import { MercureInfo } from '../reducers/mercureInfo';
import { bindToMercureTopic } from './index'; import { bindToMercureTopic } from './index';
import { useParams } from 'react-router-dom';
export interface MercureBoundProps { export interface MercureBoundProps {
createNewVisits: (createdVisits: CreateVisit[]) => void; createNewVisits: (createdVisits: CreateVisit[]) => void;

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,27 +1,29 @@
import { shallow, ShallowWrapper } from 'enzyme'; import { shallow, ShallowWrapper } from 'enzyme';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { History } from 'history'; import { useNavigate } from 'react-router-dom';
import createServerConstruct from '../../src/servers/CreateServer'; import createServerConstruct from '../../src/servers/CreateServer';
import { ServerForm } from '../../src/servers/helpers/ServerForm'; import { ServerForm } from '../../src/servers/helpers/ServerForm';
import { ServerWithId } from '../../src/servers/data'; import { ServerWithId } from '../../src/servers/data';
import { DuplicatedServersModal } from '../../src/servers/helpers/DuplicatedServersModal'; import { DuplicatedServersModal } from '../../src/servers/helpers/DuplicatedServersModal';
jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom'), useNavigate: jest.fn() }));
describe('<CreateServer />', () => { describe('<CreateServer />', () => {
let wrapper: ShallowWrapper; let wrapper: ShallowWrapper;
const ImportServersBtn = () => null; const ImportServersBtn = () => null;
const createServerMock = jest.fn(); const createServerMock = jest.fn();
const push = jest.fn(); const navigate = jest.fn();
const goBack = jest.fn();
const historyMock = Mock.of<History>({ push, goBack });
const servers = { foo: Mock.all<ServerWithId>() }; const servers = { foo: Mock.all<ServerWithId>() };
const createWrapper = (serversImported = false, importFailed = false) => { const createWrapper = (serversImported = false, importFailed = false) => {
(useNavigate as any).mockReturnValue(navigate);
const useStateFlagTimeout = jest.fn() const useStateFlagTimeout = jest.fn()
.mockReturnValueOnce([ serversImported, () => '' ]) .mockReturnValueOnce([ serversImported, () => '' ])
.mockReturnValueOnce([ importFailed, () => '' ]) .mockReturnValueOnce([ importFailed, () => '' ])
.mockReturnValue([]); .mockReturnValue([]);
const CreateServer = createServerConstruct(ImportServersBtn, useStateFlagTimeout); const CreateServer = createServerConstruct(ImportServersBtn, useStateFlagTimeout);
wrapper = shallow(<CreateServer createServer={createServerMock} history={historyMock} servers={servers} />); wrapper = shallow(<CreateServer createServer={createServerMock} servers={servers} />);
return wrapper; return wrapper;
}; };
@ -68,7 +70,7 @@ describe('<CreateServer />', () => {
wrapper.find(DuplicatedServersModal).simulate('save'); wrapper.find(DuplicatedServersModal).simulate('save');
expect(createServerMock).toHaveBeenCalledTimes(1); expect(createServerMock).toHaveBeenCalledTimes(1);
expect(push).toHaveBeenCalledTimes(1); expect(navigate).toHaveBeenCalledTimes(1);
}); });
it('goes back on modal discard', () => { it('goes back on modal discard', () => {
@ -76,6 +78,6 @@ describe('<CreateServer />', () => {
wrapper.find(DuplicatedServersModal).simulate('discard'); 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 { shallow, ShallowWrapper } from 'enzyme';
import { Modal, ModalBody, ModalFooter, ModalHeader } from 'reactstrap'; import { Modal, ModalBody, ModalFooter, ModalHeader } from 'reactstrap';
import { History } from 'history';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { useNavigate } from 'react-router-dom';
import DeleteServerModal from '../../src/servers/DeleteServerModal'; import DeleteServerModal from '../../src/servers/DeleteServerModal';
import { ServerWithId } from '../../src/servers/data'; import { ServerWithId } from '../../src/servers/data';
jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom'), useNavigate: jest.fn() }));
describe('<DeleteServerModal />', () => { describe('<DeleteServerModal />', () => {
let wrapper: ShallowWrapper; let wrapper: ShallowWrapper;
const deleteServerMock = jest.fn(); const deleteServerMock = jest.fn();
const push = jest.fn(); const navigate = jest.fn();
const toggleMock = jest.fn(); const toggleMock = jest.fn();
const serverName = 'the_server_name'; const serverName = 'the_server_name';
beforeEach(() => { beforeEach(() => {
(useNavigate as any).mockReturnValue(navigate);
wrapper = shallow( wrapper = shallow(
<DeleteServerModal <DeleteServerModal
server={Mock.of<ServerWithId>({ name: serverName })} server={Mock.of<ServerWithId>({ name: serverName })}
toggle={toggleMock} toggle={toggleMock}
isOpen={true} isOpen={true}
deleteServer={deleteServerMock} deleteServer={deleteServerMock}
history={Mock.of<History>({ push })}
/>, />,
); );
}); });
@ -48,7 +51,7 @@ describe('<DeleteServerModal />', () => {
expect(toggleMock).toHaveBeenCalledTimes(1); expect(toggleMock).toHaveBeenCalledTimes(1);
expect(deleteServerMock).not.toHaveBeenCalled(); expect(deleteServerMock).not.toHaveBeenCalled();
expect(push).not.toHaveBeenCalled(); expect(navigate).not.toHaveBeenCalled();
}); });
it('deletes server when clicking accept button', () => { it('deletes server when clicking accept button', () => {
@ -58,6 +61,6 @@ describe('<DeleteServerModal />', () => {
expect(toggleMock).toHaveBeenCalledTimes(1); expect(toggleMock).toHaveBeenCalledTimes(1);
expect(deleteServerMock).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 { mount, ReactWrapper } from 'enzyme';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { History, Location } from 'history'; import { useNavigate } from 'react-router-dom';
import { match } from 'react-router'; // eslint-disable-line @typescript-eslint/no-unused-vars
import { EditServer as editServerConstruct } from '../../src/servers/EditServer'; import { EditServer as editServerConstruct } from '../../src/servers/EditServer';
import { ServerForm } from '../../src/servers/helpers/ServerForm'; import { ServerForm } from '../../src/servers/helpers/ServerForm';
import { ReachableServer } from '../../src/servers/data'; import { ReachableServer } from '../../src/servers/data';
jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom'), useNavigate: jest.fn() }));
describe('<EditServer />', () => { describe('<EditServer />', () => {
let wrapper: ReactWrapper; let wrapper: ReactWrapper;
const ServerError = jest.fn(); const ServerError = jest.fn();
const editServerMock = jest.fn(); const editServerMock = jest.fn();
const goBack = jest.fn(); const navigate = jest.fn();
const historyMock = Mock.of<History>({ goBack });
const match = Mock.of<match<{ serverId: string }>>({
params: { serverId: 'abc123' },
});
const selectedServer = Mock.of<ReachableServer>({ const selectedServer = Mock.of<ReachableServer>({
id: 'abc123', id: 'abc123',
name: 'name', name: 'name',
url: 'url', url: 'url',
apiKey: 'apiKey', apiKey: 'apiKey',
}); });
beforeEach(() => {
const EditServer = editServerConstruct(ServerError); const EditServer = editServerConstruct(ServerError);
beforeEach(() => {
(useNavigate as any).mockReturnValue(navigate);
wrapper = mount( wrapper = mount(
<EditServer <EditServer editServer={editServerMock} selectedServer={selectedServer} selectServer={jest.fn()} />,
editServer={editServerMock}
history={historyMock}
match={match}
location={Mock.all<Location>()}
selectedServer={selectedServer}
selectServer={jest.fn()}
/>,
); );
}); });
afterEach(jest.resetAllMocks); afterEach(jest.clearAllMocks);
afterEach(() => wrapper?.unmount()); afterEach(() => wrapper?.unmount());
it('renders components', () => { it('renders components', () => {
@ -50,6 +41,6 @@ describe('<EditServer />', () => {
form.simulate('submit', {}); form.simulate('submit', {});
expect(editServerMock).toHaveBeenCalledTimes(1); expect(editServerMock).toHaveBeenCalledTimes(1);
expect(goBack).toHaveBeenCalledTimes(1); expect(navigate).toHaveBeenCalledWith(-1);
}); });
}); });

View file

@ -1,7 +1,6 @@
import { shallow, ShallowWrapper } from 'enzyme'; import { shallow, ShallowWrapper } from 'enzyme';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { History, Location } from 'history'; import { useLocation, useParams } from 'react-router-dom';
import { match } from 'react-router'; // eslint-disable-line @typescript-eslint/no-unused-vars
import { EditShortUrl as createEditShortUrl } from '../../src/short-urls/EditShortUrl'; import { EditShortUrl as createEditShortUrl } from '../../src/short-urls/EditShortUrl';
import { Settings } from '../../src/settings/reducers/settings'; import { Settings } from '../../src/settings/reducers/settings';
import { ShortUrlDetail } from '../../src/short-urls/reducers/shortUrlDetail'; 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 { ShlinkApiError } from '../../src/api/ShlinkApiError';
import { ShortUrl } from '../../src/short-urls/data'; 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 />', () => { describe('<EditShortUrl />', () => {
let wrapper: ShallowWrapper; let wrapper: ShallowWrapper;
const ShortUrlForm = () => null; const ShortUrlForm = () => null;
const goBack = jest.fn();
const getShortUrlDetail = jest.fn(); const getShortUrlDetail = jest.fn();
const editShortUrl = jest.fn(async () => Promise.resolve()); const editShortUrl = jest.fn(async () => Promise.resolve());
const shortUrlCreation = { validateUrls: true }; const shortUrlCreation = { validateUrls: true };
const EditShortUrl = createEditShortUrl(ShortUrlForm);
const createWrapper = (detail: Partial<ShortUrlDetail> = {}, edition: Partial<ShortUrlEdition> = {}) => { 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( wrapper = shallow(
<EditSHortUrl <EditShortUrl
settings={Mock.of<Settings>({ shortUrlCreation })} settings={Mock.of<Settings>({ shortUrlCreation })}
selectedServer={null} selectedServer={null}
shortUrlDetail={Mock.of<ShortUrlDetail>(detail)} shortUrlDetail={Mock.of<ShortUrlDetail>(detail)}
shortUrlEdition={Mock.of<ShortUrlEdition>(edition)} shortUrlEdition={Mock.of<ShortUrlEdition>(edition)}
getShortUrlDetail={getShortUrlDetail} getShortUrlDetail={getShortUrlDetail}
editShortUrl={editShortUrl} 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 { shallow, ShallowWrapper } from 'enzyme';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { History, Location } from 'history';
import { match } from 'react-router';
import { formatISO } from 'date-fns'; 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 SearchField from '../../src/utils/SearchField';
import Tag from '../../src/tags/helpers/Tag'; import Tag from '../../src/tags/helpers/Tag';
import { DateRangeSelector } from '../../src/utils/dates/DateRangeSelector'; import { DateRangeSelector } from '../../src/utils/dates/DateRangeSelector';
import ColorGenerator from '../../src/utils/services/ColorGenerator'; 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 />', () => { describe('<ShortUrlsFilteringBar />', () => {
let wrapper: ShallowWrapper; let wrapper: ShallowWrapper;
const ShortUrlsFilteringBar = filteringBarCreator(Mock.all<ColorGenerator>()); const ShortUrlsFilteringBar = filteringBarCreator(Mock.all<ColorGenerator>());
const push = jest.fn(); const navigate = jest.fn();
const now = new Date(); const now = new Date();
const createWrapper = (props: Partial<ShortUrlsFilteringProps> = {}) => { const createWrapper = (search = '') => {
wrapper = shallow( (useLocation as any).mockReturnValue({ search });
<ShortUrlsFilteringBar (useNavigate as any).mockReturnValue(navigate);
history={Mock.of<History>({ push })}
location={Mock.of<Location>({ search: '' })} wrapper = shallow(<ShortUrlsFilteringBar />);
match={Mock.of<match<ShortUrlListRouteParams>>({ params: { serverId: '1' } })}
{...props}
/>,
);
return wrapper; return wrapper;
}; };
@ -44,7 +45,7 @@ describe('<ShortUrlsFilteringBar />', () => {
[ '', 0 ], [ '', 0 ],
[ 'foo=bar', 0 ], [ 'foo=bar', 0 ],
])('renders the proper amount of tags', (search, expectedTagComps) => { ])('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); expect(wrapper.find(Tag)).toHaveLength(expectedTagComps);
}); });
@ -53,18 +54,18 @@ describe('<ShortUrlsFilteringBar />', () => {
const wrapper = createWrapper(); const wrapper = createWrapper();
const searchField = wrapper.find(SearchField); const searchField = wrapper.find(SearchField);
expect(push).not.toHaveBeenCalled(); expect(navigate).not.toHaveBeenCalled();
searchField.simulate('change', 'search-term'); 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', () => { 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(); const tag = wrapper.find(Tag).first();
expect(push).not.toHaveBeenCalled(); expect(navigate).not.toHaveBeenCalled();
tag.simulate('close'); 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([ it.each([
@ -78,8 +79,8 @@ describe('<ShortUrlsFilteringBar />', () => {
const wrapper = createWrapper(); const wrapper = createWrapper();
const dateRange = wrapper.find(DateRangeSelector); const dateRange = wrapper.find(DateRangeSelector);
expect(push).not.toHaveBeenCalled(); expect(navigate).not.toHaveBeenCalled();
dateRange.simulate('datesChange', dates); 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 { shallow, ShallowWrapper } from 'enzyme';
import { ReactElement } from 'react'; import { ReactElement } from 'react';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { History, Location } from 'history'; import { useNavigate } from 'react-router-dom';
import { match } from 'react-router';
import shortUrlsListCreator from '../../src/short-urls/ShortUrlsList'; import shortUrlsListCreator from '../../src/short-urls/ShortUrlsList';
import { ShortUrlsOrderableFields, ShortUrl, ShortUrlsOrder } from '../../src/short-urls/data'; import { ShortUrlsOrderableFields, ShortUrl, ShortUrlsOrder } from '../../src/short-urls/data';
import { MercureBoundProps } from '../../src/mercure/helpers/boundToMercureHub'; 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 { OrderingDropdown } from '../../src/utils/OrderingDropdown';
import Paginator from '../../src/short-urls/Paginator'; import Paginator from '../../src/short-urls/Paginator';
import { ReachableServer } from '../../src/servers/data'; import { ReachableServer } from '../../src/servers/data';
import { ShortUrlListRouteParams } from '../../src/short-urls/helpers/hooks';
import { Settings } from '../../src/settings/reducers/settings'; 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 />', () => { describe('<ShortUrlsList />', () => {
let wrapper: ShallowWrapper; let wrapper: ShallowWrapper;
const ShortUrlsTable = () => null; const ShortUrlsTable = () => null;
const ShortUrlsFilteringBar = () => null; const ShortUrlsFilteringBar = () => null;
const listShortUrlsMock = jest.fn(); const listShortUrlsMock = jest.fn();
const push = jest.fn(); const navigate = jest.fn();
const shortUrlsList = Mock.of<ShortUrlsListModel>({ const shortUrlsList = Mock.of<ShortUrlsListModel>({
shortUrls: { shortUrls: {
data: [ data: [
@ -36,20 +41,19 @@ describe('<ShortUrlsList />', () => {
<ShortUrlsList <ShortUrlsList
{...Mock.of<MercureBoundProps>({ mercureInfo: { loading: true } })} {...Mock.of<MercureBoundProps>({ mercureInfo: { loading: true } })}
listShortUrls={listShortUrlsMock} listShortUrls={listShortUrlsMock}
match={Mock.of<match<ShortUrlListRouteParams>>({ params: {} })}
location={Mock.of<Location>({ search: '?tags=test%20tag&search=example.com' })}
shortUrlsList={shortUrlsList} shortUrlsList={shortUrlsList}
history={Mock.of<History>({ push })}
selectedServer={Mock.of<ReachableServer>({ id: '1' })} selectedServer={Mock.of<ReachableServer>({ id: '1' })}
settings={Mock.of<Settings>({ shortUrlsList: { defaultOrdering } })} settings={Mock.of<Settings>({ shortUrlsList: { defaultOrdering } })}
/>, />,
).dive(); // Dive is needed as this component is wrapped in a HOC ).dive(); // Dive is needed as this component is wrapped in a HOC
beforeEach(() => { beforeEach(() => {
(useNavigate as any).mockReturnValue(navigate);
wrapper = createWrapper(); wrapper = createWrapper();
}); });
afterEach(jest.resetAllMocks); afterEach(jest.clearAllMocks);
afterEach(() => wrapper?.unmount()); afterEach(() => wrapper?.unmount());
it('wraps expected components', () => { it('wraps expected components', () => {
@ -68,10 +72,10 @@ describe('<ShortUrlsList />', () => {
wrapper.find(ShortUrlsTable).simulate('tagClick', 'bar'); wrapper.find(ShortUrlsTable).simulate('tagClick', 'bar');
wrapper.find(ShortUrlsTable).simulate('tagClick', 'baz'); wrapper.find(ShortUrlsTable).simulate('tagClick', 'baz');
expect(push).toHaveBeenCalledTimes(3); expect(navigate).toHaveBeenCalledTimes(3);
expect(push).toHaveBeenNthCalledWith(1, expect.stringContaining(`tags=${encodeURIComponent('test tag,foo')}`)); expect(navigate).toHaveBeenNthCalledWith(1, expect.stringContaining(`tags=${encodeURIComponent('test tag,foo')}`));
expect(push).toHaveBeenNthCalledWith(2, expect.stringContaining(`tags=${encodeURIComponent('test tag,bar')}`)); expect(navigate).toHaveBeenNthCalledWith(2, expect.stringContaining(`tags=${encodeURIComponent('test tag,bar')}`));
expect(push).toHaveBeenNthCalledWith(3, expect.stringContaining(`tags=${encodeURIComponent('test tag,baz')}`)); expect(navigate).toHaveBeenNthCalledWith(3, expect.stringContaining(`tags=${encodeURIComponent('test tag,baz')}`));
}); });
it('invokes order icon rendering', () => { it('invokes order icon rendering', () => {

View file

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

View file

@ -1,7 +1,5 @@
import { shallow } from 'enzyme'; import { shallow } from 'enzyme';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { History, Location } from 'history';
import { match } from 'react-router';
import { NonOrphanVisits as createNonOrphanVisits } from '../../src/visits/NonOrphanVisits'; import { NonOrphanVisits as createNonOrphanVisits } from '../../src/visits/NonOrphanVisits';
import { MercureBoundProps } from '../../src/mercure/helpers/boundToMercureHub'; import { MercureBoundProps } from '../../src/mercure/helpers/boundToMercureHub';
import { VisitsInfo } from '../../src/visits/types'; 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 { VisitsExporter } from '../../src/visits/services/VisitsExporter';
import { SelectedServer } from '../../src/servers/data'; 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 />', () => { describe('<NonOrphanVisits />', () => {
it('wraps visits stats and header', () => { it('wraps visits stats and header', () => {
const goBack = jest.fn();
const getNonOrphanVisits = jest.fn(); const getNonOrphanVisits = jest.fn();
const cancelGetNonOrphanVisits = jest.fn(); const cancelGetNonOrphanVisits = jest.fn();
const nonOrphanVisits = Mock.all<VisitsInfo>(); const nonOrphanVisits = Mock.all<VisitsInfo>();
@ -25,9 +28,6 @@ describe('<NonOrphanVisits />', () => {
getNonOrphanVisits={getNonOrphanVisits} getNonOrphanVisits={getNonOrphanVisits}
nonOrphanVisits={nonOrphanVisits} nonOrphanVisits={nonOrphanVisits}
cancelGetNonOrphanVisits={cancelGetNonOrphanVisits} cancelGetNonOrphanVisits={cancelGetNonOrphanVisits}
history={Mock.of<History>({ goBack })}
location={Mock.all<Location>()}
match={Mock.of<match>({ url: 'the_base_url' })}
settings={Mock.all<Settings>()} settings={Mock.all<Settings>()}
selectedServer={Mock.all<SelectedServer>()} selectedServer={Mock.all<SelectedServer>()}
/>, />,
@ -39,9 +39,8 @@ describe('<NonOrphanVisits />', () => {
expect(header).toHaveLength(1); expect(header).toHaveLength(1);
expect(stats.prop('cancelGetVisits')).toEqual(cancelGetNonOrphanVisits); expect(stats.prop('cancelGetVisits')).toEqual(cancelGetNonOrphanVisits);
expect(stats.prop('visitsInfo')).toEqual(nonOrphanVisits); expect(stats.prop('visitsInfo')).toEqual(nonOrphanVisits);
expect(stats.prop('baseUrl')).toEqual('the_base_url');
expect(stats.prop('isOrphanVisits')).not.toBeDefined(); expect(stats.prop('isOrphanVisits')).not.toBeDefined();
expect(header.prop('nonOrphanVisits')).toEqual(nonOrphanVisits); 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 { shallow } from 'enzyme';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { History, Location } from 'history';
import { match } from 'react-router';
import { OrphanVisits as createOrphanVisits } from '../../src/visits/OrphanVisits'; import { OrphanVisits as createOrphanVisits } from '../../src/visits/OrphanVisits';
import { MercureBoundProps } from '../../src/mercure/helpers/boundToMercureHub'; import { MercureBoundProps } from '../../src/mercure/helpers/boundToMercureHub';
import { VisitsInfo } from '../../src/visits/types'; 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 { VisitsExporter } from '../../src/visits/services/VisitsExporter';
import { SelectedServer } from '../../src/servers/data'; 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 />', () => { describe('<OrphanVisits />', () => {
it('wraps visits stats and header', () => { it('wraps visits stats and header', () => {
const goBack = jest.fn();
const getOrphanVisits = jest.fn(); const getOrphanVisits = jest.fn();
const cancelGetOrphanVisits = jest.fn(); const cancelGetOrphanVisits = jest.fn();
const orphanVisits = Mock.all<VisitsInfo>(); const orphanVisits = Mock.all<VisitsInfo>();
@ -25,9 +28,6 @@ describe('<OrphanVisits />', () => {
getOrphanVisits={getOrphanVisits} getOrphanVisits={getOrphanVisits}
orphanVisits={orphanVisits} orphanVisits={orphanVisits}
cancelGetOrphanVisits={cancelGetOrphanVisits} cancelGetOrphanVisits={cancelGetOrphanVisits}
history={Mock.of<History>({ goBack })}
location={Mock.all<Location>()}
match={Mock.of<match>({ url: 'the_base_url' })}
settings={Mock.all<Settings>()} settings={Mock.all<Settings>()}
selectedServer={Mock.all<SelectedServer>()} selectedServer={Mock.all<SelectedServer>()}
/>, />,
@ -39,9 +39,8 @@ describe('<OrphanVisits />', () => {
expect(header).toHaveLength(1); expect(header).toHaveLength(1);
expect(stats.prop('cancelGetVisits')).toEqual(cancelGetOrphanVisits); expect(stats.prop('cancelGetVisits')).toEqual(cancelGetOrphanVisits);
expect(stats.prop('visitsInfo')).toEqual(orphanVisits); expect(stats.prop('visitsInfo')).toEqual(orphanVisits);
expect(stats.prop('baseUrl')).toEqual('the_base_url');
expect(stats.prop('isOrphanVisits')).toEqual(true); expect(stats.prop('isOrphanVisits')).toEqual(true);
expect(header.prop('orphanVisits')).toEqual(orphanVisits); 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 { shallow, ShallowWrapper } from 'enzyme';
import { identity } from 'ramda'; import { identity } from 'ramda';
import { Mock } from 'ts-mockery'; 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 createShortUrlVisits, { ShortUrlVisitsProps } from '../../src/visits/ShortUrlVisits';
import ShortUrlVisitsHeader from '../../src/visits/ShortUrlVisitsHeader'; import ShortUrlVisitsHeader from '../../src/visits/ShortUrlVisitsHeader';
import { ShortUrlVisits as ShortUrlVisitsState } from '../../src/visits/reducers/shortUrlVisits'; 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 { MercureBoundProps } from '../../src/mercure/helpers/boundToMercureHub';
import { VisitsExporter } from '../../src/visits/services/VisitsExporter'; 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 />', () => { describe('<ShortUrlVisits />', () => {
let wrapper: ShallowWrapper; let wrapper: ShallowWrapper;
const getShortUrlVisitsMock = jest.fn(); 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>()); const ShortUrlVisits = createShortUrlVisits(Mock.all<VisitsExporter>());
beforeEach(() => { beforeEach(() => {
@ -30,9 +28,6 @@ describe('<ShortUrlVisits />', () => {
{...Mock.of<MercureBoundProps>({ mercureInfo: {} })} {...Mock.of<MercureBoundProps>({ mercureInfo: {} })}
getShortUrlDetail={identity} getShortUrlDetail={identity}
getShortUrlVisits={getShortUrlVisitsMock} getShortUrlVisits={getShortUrlVisitsMock}
match={match}
location={location}
history={history}
shortUrlVisits={Mock.of<ShortUrlVisitsState>({ loading: true, visits: [] })} shortUrlVisits={Mock.of<ShortUrlVisitsState>({ loading: true, visits: [] })}
shortUrlDetail={Mock.all<ShortUrlDetail>()} shortUrlDetail={Mock.all<ShortUrlDetail>()}
cancelGetShortUrlVisits={() => {}} cancelGetShortUrlVisits={() => {}}
@ -40,8 +35,8 @@ describe('<ShortUrlVisits />', () => {
).dive(); // Dive is needed as this component is wrapped in a HOC ).dive(); // Dive is needed as this component is wrapped in a HOC
}); });
afterEach(jest.clearAllMocks);
afterEach(() => wrapper.unmount()); afterEach(() => wrapper.unmount());
afterEach(jest.resetAllMocks);
it('renders visit stats and visits header', () => { it('renders visit stats and visits header', () => {
const visitStats = wrapper.find(VisitsStats); const visitStats = wrapper.find(VisitsStats);

View file

@ -1,7 +1,5 @@
import { shallow, ShallowWrapper } from 'enzyme'; import { shallow, ShallowWrapper } from 'enzyme';
import { Mock } from 'ts-mockery'; 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 createTagVisits, { TagVisitsProps } from '../../src/visits/TagVisits';
import TagVisitsHeader from '../../src/visits/TagVisitsHeader'; import TagVisitsHeader from '../../src/visits/TagVisitsHeader';
import ColorGenerator from '../../src/utils/services/ColorGenerator'; 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 { MercureBoundProps } from '../../src/mercure/helpers/boundToMercureHub';
import { VisitsExporter } from '../../src/visits/services/VisitsExporter'; 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 />', () => { describe('<TagVisits />', () => {
let wrapper: ShallowWrapper; let wrapper: ShallowWrapper;
const getTagVisitsMock = jest.fn(); const getTagVisitsMock = jest.fn();
const match = Mock.of<match<{ tag: string }>>({
params: { tag: 'foo' },
});
const history = Mock.of<History>({
goBack: jest.fn(),
});
beforeEach(() => { beforeEach(() => {
const TagVisits = createTagVisits(Mock.all<ColorGenerator>(), Mock.all<VisitsExporter>()); const TagVisits = createTagVisits(Mock.all<ColorGenerator>(), Mock.all<VisitsExporter>());
@ -28,8 +27,6 @@ describe('<TagVisits />', () => {
{...Mock.all<TagVisitsProps>()} {...Mock.all<TagVisitsProps>()}
{...Mock.of<MercureBoundProps>({ mercureInfo: {} })} {...Mock.of<MercureBoundProps>({ mercureInfo: {} })}
getTagVisits={getTagVisitsMock} getTagVisits={getTagVisitsMock}
match={match}
history={history}
tagVisits={Mock.of<TagVisitsStats>({ loading: true, visits: [] })} tagVisits={Mock.of<TagVisitsStats>({ loading: true, visits: [] })}
cancelGetTagVisits={() => {}} cancelGetTagVisits={() => {}}
/>, />,

View file

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