Moved common test set-up code to helper function

This commit is contained in:
Alejandro Celaya 2022-07-09 23:03:21 +02:00
parent cb13e82b9c
commit d07f7e757e
57 changed files with 376 additions and 476 deletions

View file

@ -1,5 +1,6 @@
import { ReactElement } from 'react'; import { ReactElement } from 'react';
import { render } from '@testing-library/react'; import { render } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
export const setUpCanvas = (element: ReactElement) => { export const setUpCanvas = (element: ReactElement) => {
const result = render(element); const result = render(element);
@ -8,3 +9,8 @@ export const setUpCanvas = (element: ReactElement) => {
return { ...result, events: getEvents(), getEvents }; return { ...result, events: getEvents(), getEvents };
}; };
export const renderWithEvents = (element: ReactElement) => ({
user: userEvent.setup(),
...render(element),
});

View file

@ -1,14 +1,11 @@
import { render, screen } from '@testing-library/react'; import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { AppUpdateBanner } from '../../src/common/AppUpdateBanner'; import { AppUpdateBanner } from '../../src/common/AppUpdateBanner';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<AppUpdateBanner />', () => { describe('<AppUpdateBanner />', () => {
const toggle = jest.fn(); const toggle = jest.fn();
const forceUpdate = jest.fn(); const forceUpdate = jest.fn();
const setUp = () => ({ const setUp = () => renderWithEvents(<AppUpdateBanner isOpen toggle={toggle} forceUpdate={forceUpdate} />);
user: userEvent.setup(),
...render(<AppUpdateBanner isOpen toggle={toggle} forceUpdate={forceUpdate} />),
});
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);

View file

@ -1,7 +1,7 @@
import { render, screen } from '@testing-library/react'; import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { ErrorHandler as createErrorHandler } from '../../src/common/ErrorHandler'; import { ErrorHandler as createErrorHandler } from '../../src/common/ErrorHandler';
import { renderWithEvents } from '../__mocks__/setUpTest';
const ComponentWithError = () => { const ComponentWithError = () => {
throw new Error('Error!!'); throw new Error('Error!!');
@ -36,8 +36,7 @@ describe('<ErrorHandler />', () => {
}); });
it('reloads page on button click', async () => { it('reloads page on button click', async () => {
const user = userEvent.setup(); const { user } = renderWithEvents(<ErrorHandler children={<ComponentWithError />} />);
render(<ErrorHandler children={<ComponentWithError />} />);
expect(reload).not.toHaveBeenCalled(); expect(reload).not.toHaveBeenCalled();
await user.click(screen.getByRole('button')); await user.click(screen.getByRole('button'));

View file

@ -1,8 +1,8 @@
import { render, screen, waitFor } from '@testing-library/react'; import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Router } from 'react-router-dom'; import { Router } from 'react-router-dom';
import { createMemoryHistory } from 'history'; import { createMemoryHistory } from 'history';
import { MainHeader as createMainHeader } from '../../src/common/MainHeader'; import { MainHeader as createMainHeader } from '../../src/common/MainHeader';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<MainHeader />', () => { describe('<MainHeader />', () => {
const MainHeader = createMainHeader(() => <>ServersDropdown</>); const MainHeader = createMainHeader(() => <>ServersDropdown</>);
@ -10,14 +10,11 @@ describe('<MainHeader />', () => {
const history = createMemoryHistory(); const history = createMemoryHistory();
history.push(pathname); history.push(pathname);
const user = userEvent.setup(); return renderWithEvents(
const renderResult = render(
<Router location={history.location} navigator={history}> <Router location={history.location} navigator={history}>
<MainHeader /> <MainHeader />
</Router>, </Router>,
); );
return { user, ...renderResult };
}; };
it('renders ServersDropdown', () => { it('renders ServersDropdown', () => {

View file

@ -1,9 +1,9 @@
import { render, screen, waitFor } from '@testing-library/react'; import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { DomainSelector } from '../../src/domains/DomainSelector'; import { DomainSelector } from '../../src/domains/DomainSelector';
import { DomainsList } from '../../src/domains/reducers/domainsList'; import { DomainsList } from '../../src/domains/reducers/domainsList';
import { ShlinkDomain } from '../../src/api/types'; import { ShlinkDomain } from '../../src/api/types';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<DomainSelector />', () => { describe('<DomainSelector />', () => {
const domainsList = Mock.of<DomainsList>({ const domainsList = Mock.of<DomainsList>({
@ -13,10 +13,9 @@ describe('<DomainSelector />', () => {
Mock.of<ShlinkDomain>({ domain: 'bar.com' }), Mock.of<ShlinkDomain>({ domain: 'bar.com' }),
], ],
}); });
const setUp = (value = '') => ({ const setUp = (value = '') => renderWithEvents(
user: userEvent.setup(), <DomainSelector value={value} domainsList={domainsList} listDomains={jest.fn()} onChange={jest.fn()} />,
...render(<DomainSelector value={value} domainsList={domainsList} listDomains={jest.fn()} onChange={jest.fn()} />), );
});
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);

View file

@ -1,17 +1,15 @@
import { render, screen, waitFor } from '@testing-library/react'; import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { DomainsList } from '../../src/domains/reducers/domainsList'; import { DomainsList } from '../../src/domains/reducers/domainsList';
import { ManageDomains } from '../../src/domains/ManageDomains'; import { ManageDomains } from '../../src/domains/ManageDomains';
import { ProblemDetailsError, ShlinkDomain } from '../../src/api/types'; import { ProblemDetailsError, ShlinkDomain } from '../../src/api/types';
import { SelectedServer } from '../../src/servers/data'; import { SelectedServer } from '../../src/servers/data';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<ManageDomains />', () => { describe('<ManageDomains />', () => {
const listDomains = jest.fn(); const listDomains = jest.fn();
const filterDomains = jest.fn(); const filterDomains = jest.fn();
const setUp = (domainsList: DomainsList) => ({ const setUp = (domainsList: DomainsList) => renderWithEvents(
user: userEvent.setup(),
...render(
<ManageDomains <ManageDomains
listDomains={listDomains} listDomains={listDomains}
filterDomains={filterDomains} filterDomains={filterDomains}
@ -20,8 +18,7 @@ describe('<ManageDomains />', () => {
domainsList={domainsList} domainsList={domainsList}
selectedServer={Mock.all<SelectedServer>()} selectedServer={Mock.all<SelectedServer>()}
/>, />,
), );
});
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);

View file

@ -1,17 +1,15 @@
import { render, screen, waitForElementToBeRemoved } from '@testing-library/react'; import { screen, waitForElementToBeRemoved } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { MemoryRouter } from 'react-router-dom'; import { MemoryRouter } from 'react-router-dom';
import { DomainDropdown } from '../../../src/domains/helpers/DomainDropdown'; import { DomainDropdown } from '../../../src/domains/helpers/DomainDropdown';
import { Domain } from '../../../src/domains/data'; import { Domain } from '../../../src/domains/data';
import { ReachableServer, SelectedServer } from '../../../src/servers/data'; import { ReachableServer, SelectedServer } from '../../../src/servers/data';
import { SemVer } from '../../../src/utils/helpers/version'; import { SemVer } from '../../../src/utils/helpers/version';
import { renderWithEvents } from '../../__mocks__/setUpTest';
describe('<DomainDropdown />', () => { describe('<DomainDropdown />', () => {
const editDomainRedirects = jest.fn().mockResolvedValue(undefined); const editDomainRedirects = jest.fn().mockResolvedValue(undefined);
const setUp = (domain?: Domain, selectedServer?: SelectedServer) => ({ const setUp = (domain?: Domain, selectedServer?: SelectedServer) => renderWithEvents(
user: userEvent.setup(),
...render(
<MemoryRouter> <MemoryRouter>
<DomainDropdown <DomainDropdown
domain={domain ?? Mock.all<Domain>()} domain={domain ?? Mock.all<Domain>()}
@ -19,8 +17,7 @@ describe('<DomainDropdown />', () => {
editDomainRedirects={editDomainRedirects} editDomainRedirects={editDomainRedirects}
/> />
</MemoryRouter>, </MemoryRouter>,
), );
});
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);

View file

@ -1,15 +1,14 @@
import { render, screen } from '@testing-library/react'; import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { DomainStatus } from '../../../src/domains/data'; import { DomainStatus } from '../../../src/domains/data';
import { DomainStatusIcon } from '../../../src/domains/helpers/DomainStatusIcon'; import { DomainStatusIcon } from '../../../src/domains/helpers/DomainStatusIcon';
import { renderWithEvents } from '../../__mocks__/setUpTest';
describe('<DomainStatusIcon />', () => { describe('<DomainStatusIcon />', () => {
const matchMedia = jest.fn().mockReturnValue(Mock.of<MediaQueryList>({ matches: false })); const matchMedia = jest.fn().mockReturnValue(Mock.of<MediaQueryList>({ matches: false }));
const setUp = (status: DomainStatus) => ({ const setUp = (status: DomainStatus) => renderWithEvents(
user: userEvent.setup(), <DomainStatusIcon status={status} matchMedia={matchMedia} />,
...render(<DomainStatusIcon status={status} matchMedia={matchMedia} />), );
});
beforeEach(jest.clearAllMocks); beforeEach(jest.clearAllMocks);

View file

@ -1,8 +1,8 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import { fireEvent, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { ShlinkDomain } from '../../../src/api/types'; import { ShlinkDomain } from '../../../src/api/types';
import { EditDomainRedirectsModal } from '../../../src/domains/helpers/EditDomainRedirectsModal'; import { EditDomainRedirectsModal } from '../../../src/domains/helpers/EditDomainRedirectsModal';
import { renderWithEvents } from '../../__mocks__/setUpTest';
describe('<EditDomainRedirectsModal />', () => { describe('<EditDomainRedirectsModal />', () => {
const editDomainRedirects = jest.fn().mockResolvedValue(undefined); const editDomainRedirects = jest.fn().mockResolvedValue(undefined);
@ -13,12 +13,9 @@ describe('<EditDomainRedirectsModal />', () => {
baseUrlRedirect: 'baz', baseUrlRedirect: 'baz',
}, },
}); });
const setUp = () => ({ const setUp = () => renderWithEvents(
user: userEvent.setup(),
...render(
<EditDomainRedirectsModal domain={domain} isOpen toggle={toggle} editDomainRedirects={editDomainRedirects} />, <EditDomainRedirectsModal domain={domain} isOpen toggle={toggle} editDomainRedirects={editDomainRedirects} />,
), );
});
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);

View file

@ -1,9 +1,9 @@
import userEvent from '@testing-library/user-event'; import { fireEvent, screen, waitFor } from '@testing-library/react';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { CreateServer as createCreateServer } from '../../src/servers/CreateServer'; import { CreateServer as createCreateServer } from '../../src/servers/CreateServer';
import { ServerWithId } from '../../src/servers/data'; import { ServerWithId } from '../../src/servers/data';
import { renderWithEvents } from '../__mocks__/setUpTest';
jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom'), useNavigate: jest.fn() })); jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom'), useNavigate: jest.fn() }));
@ -22,10 +22,7 @@ describe('<CreateServer />', () => {
}); });
const CreateServer = createCreateServer(() => <>ImportServersBtn</>, useTimeoutToggle); const CreateServer = createCreateServer(() => <>ImportServersBtn</>, useTimeoutToggle);
return { return renderWithEvents(<CreateServer createServer={createServerMock} servers={servers} />);
user: userEvent.setup(),
...render(<CreateServer createServer={createServerMock} servers={servers} />),
};
}; };
beforeEach(jest.clearAllMocks); beforeEach(jest.clearAllMocks);

View file

@ -1,20 +1,17 @@
import { ReactNode } from 'react'; import { ReactNode } from 'react';
import userEvent from '@testing-library/user-event'; import { screen, waitFor } from '@testing-library/react';
import { render, screen, waitFor } from '@testing-library/react';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { DeleteServerButton as createDeleteServerButton } from '../../src/servers/DeleteServerButton'; import { DeleteServerButton as createDeleteServerButton } from '../../src/servers/DeleteServerButton';
import { ServerWithId } from '../../src/servers/data'; import { ServerWithId } from '../../src/servers/data';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<DeleteServerButton />', () => { describe('<DeleteServerButton />', () => {
const DeleteServerButton = createDeleteServerButton( const DeleteServerButton = createDeleteServerButton(
({ isOpen }) => <>DeleteServerModal {isOpen ? '[Open]' : '[Closed]'}</>, ({ isOpen }) => <>DeleteServerModal {isOpen ? '[Open]' : '[Closed]'}</>,
); );
const setUp = (children?: ReactNode) => ({ const setUp = (children?: ReactNode) => renderWithEvents(
user: userEvent.setup(),
...render(
<DeleteServerButton server={Mock.all<ServerWithId>()} textClassName="button">{children}</DeleteServerButton>, <DeleteServerButton server={Mock.all<ServerWithId>()} textClassName="button">{children}</DeleteServerButton>,
), );
});
it.each([ it.each([
['Foo bar'], ['Foo bar'],

View file

@ -1,9 +1,9 @@
import { render, screen } from '@testing-library/react'; import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { useNavigate } from 'react-router-dom'; 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';
import { renderWithEvents } from '../__mocks__/setUpTest';
jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom'), useNavigate: jest.fn() })); jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom'), useNavigate: jest.fn() }));
@ -15,17 +15,14 @@ describe('<DeleteServerModal />', () => {
const setUp = () => { const setUp = () => {
(useNavigate as any).mockReturnValue(navigate); (useNavigate as any).mockReturnValue(navigate);
return { return renderWithEvents(
user: userEvent.setup(),
...render(
<DeleteServerModal <DeleteServerModal
server={Mock.of<ServerWithId>({ name: serverName })} server={Mock.of<ServerWithId>({ name: serverName })}
toggle={toggleMock} toggle={toggleMock}
isOpen isOpen
deleteServer={deleteServerMock} deleteServer={deleteServerMock}
/>, />,
), );
};
}; };
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);

View file

@ -1,9 +1,9 @@
import { fireEvent, render, screen } from '@testing-library/react'; import { fireEvent, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { EditServer as editServerConstruct } from '../../src/servers/EditServer'; import { EditServer as editServerConstruct } from '../../src/servers/EditServer';
import { ReachableServer, SelectedServer } from '../../src/servers/data'; import { ReachableServer, SelectedServer } from '../../src/servers/data';
import { renderWithEvents } from '../__mocks__/setUpTest';
jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom'), useNavigate: jest.fn() })); jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom'), useNavigate: jest.fn() }));
@ -18,10 +18,9 @@ describe('<EditServer />', () => {
apiKey: 'the_api_key', apiKey: 'the_api_key',
}); });
const EditServer = editServerConstruct(ServerError); const EditServer = editServerConstruct(ServerError);
const setUp = (selectedServer: SelectedServer = defaultSelectedServer) => ({ const setUp = (selectedServer: SelectedServer = defaultSelectedServer) => renderWithEvents(
user: userEvent.setup(), <EditServer editServer={editServerMock} selectedServer={selectedServer} selectServer={jest.fn()} />,
...render(<EditServer editServer={editServerMock} selectedServer={selectedServer} selectServer={jest.fn()} />), );
});
beforeEach(() => { beforeEach(() => {
(useNavigate as any).mockReturnValue(navigate); (useNavigate as any).mockReturnValue(navigate);

View file

@ -1,10 +1,10 @@
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import userEvent from '@testing-library/user-event'; import { screen, waitFor } from '@testing-library/react';
import { render, screen, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom'; import { MemoryRouter } from 'react-router-dom';
import ServersExporter from '../../src/servers/services/ServersExporter'; import ServersExporter from '../../src/servers/services/ServersExporter';
import { ManageServers as createManageServers } from '../../src/servers/ManageServers'; import { ManageServers as createManageServers } from '../../src/servers/ManageServers';
import { ServersMap, ServerWithId } from '../../src/servers/data'; import { ServersMap, ServerWithId } from '../../src/servers/data';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<ManageServers />', () => { describe('<ManageServers />', () => {
const exportServers = jest.fn(); const exportServers = jest.fn();
@ -19,10 +19,9 @@ describe('<ManageServers />', () => {
const createServerMock = (value: string, autoConnect = false) => Mock.of<ServerWithId>( const createServerMock = (value: string, autoConnect = false) => Mock.of<ServerWithId>(
{ id: value, name: value, url: value, autoConnect }, { id: value, name: value, url: value, autoConnect },
); );
const setUp = (servers: ServersMap = {}) => ({ const setUp = (servers: ServersMap = {}) => renderWithEvents(
user: userEvent.setup(), <MemoryRouter><ManageServers servers={servers} /></MemoryRouter>,
...render(<MemoryRouter><ManageServers servers={servers} /></MemoryRouter>), );
});
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);

View file

@ -1,9 +1,9 @@
import userEvent from '@testing-library/user-event'; import { screen } from '@testing-library/react';
import { render, screen } from '@testing-library/react';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { MemoryRouter } from 'react-router-dom'; import { MemoryRouter } from 'react-router-dom';
import { ServerWithId } from '../../src/servers/data'; import { ServerWithId } from '../../src/servers/data';
import { ManageServersRowDropdown as createManageServersRowDropdown } from '../../src/servers/ManageServersRowDropdown'; import { ManageServersRowDropdown as createManageServersRowDropdown } from '../../src/servers/ManageServersRowDropdown';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<ManageServersRowDropdown />', () => { describe('<ManageServersRowDropdown />', () => {
const ManageServersRowDropdown = createManageServersRowDropdown( const ManageServersRowDropdown = createManageServersRowDropdown(
@ -12,14 +12,11 @@ describe('<ManageServersRowDropdown />', () => {
const setAutoConnect = jest.fn(); const setAutoConnect = jest.fn();
const setUp = (autoConnect = false) => { const setUp = (autoConnect = false) => {
const server = Mock.of<ServerWithId>({ id: 'abc123', autoConnect }); const server = Mock.of<ServerWithId>({ id: 'abc123', autoConnect });
return { return renderWithEvents(
user: userEvent.setup(),
...render(
<MemoryRouter> <MemoryRouter>
<ManageServersRowDropdown setAutoConnect={setAutoConnect} server={server} /> <ManageServersRowDropdown setAutoConnect={setAutoConnect} server={server} />
</MemoryRouter>, </MemoryRouter>,
), );
};
}; };
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);

View file

@ -1,10 +1,10 @@
import { render, screen } from '@testing-library/react'; import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { values } from 'ramda'; import { values } from 'ramda';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { MemoryRouter } from 'react-router-dom'; import { MemoryRouter } from 'react-router-dom';
import { ServersDropdown } from '../../src/servers/ServersDropdown'; import { ServersDropdown } from '../../src/servers/ServersDropdown';
import { ServersMap, ServerWithId } from '../../src/servers/data'; import { ServersMap, ServerWithId } from '../../src/servers/data';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<ServersDropdown />', () => { describe('<ServersDropdown />', () => {
const fallbackServers: ServersMap = { const fallbackServers: ServersMap = {
@ -12,10 +12,9 @@ describe('<ServersDropdown />', () => {
'2b': Mock.of<ServerWithId>({ name: 'bar', id: '2b' }), '2b': Mock.of<ServerWithId>({ name: 'bar', id: '2b' }),
'3c': Mock.of<ServerWithId>({ name: 'baz', id: '3c' }), '3c': Mock.of<ServerWithId>({ name: 'baz', id: '3c' }),
}; };
const setUp = (servers: ServersMap = fallbackServers) => ({ const setUp = (servers: ServersMap = fallbackServers) => renderWithEvents(
user: userEvent.setup(), <MemoryRouter><ServersDropdown servers={servers} selectedServer={null} /></MemoryRouter>,
...render(<MemoryRouter><ServersDropdown servers={servers} selectedServer={null} /></MemoryRouter>), );
});
it('contains the list of servers and the "mange servers" button', async () => { it('contains the list of servers and the "mange servers" button', async () => {
const { user } = setUp(); const { user } = setUp();

View file

@ -1,18 +1,15 @@
import { render, screen } from '@testing-library/react'; import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { DuplicatedServersModal } from '../../../src/servers/helpers/DuplicatedServersModal'; import { DuplicatedServersModal } from '../../../src/servers/helpers/DuplicatedServersModal';
import { ServerData } from '../../../src/servers/data'; import { ServerData } from '../../../src/servers/data';
import { renderWithEvents } from '../../__mocks__/setUpTest';
describe('<DuplicatedServersModal />', () => { describe('<DuplicatedServersModal />', () => {
const onDiscard = jest.fn(); const onDiscard = jest.fn();
const onSave = jest.fn(); const onSave = jest.fn();
const setUp = (duplicatedServers: ServerData[] = []) => ({ const setUp = (duplicatedServers: ServerData[] = []) => renderWithEvents(
user: userEvent.setup(),
...render(
<DuplicatedServersModal isOpen duplicatedServers={duplicatedServers} onDiscard={onDiscard} onSave={onSave} />, <DuplicatedServersModal isOpen duplicatedServers={duplicatedServers} onDiscard={onDiscard} onSave={onSave} />,
), );
});
beforeEach(jest.clearAllMocks); beforeEach(jest.clearAllMocks);

View file

@ -1,5 +1,4 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import { fireEvent, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { import {
ImportServersBtn as createImportServersBtn, ImportServersBtn as createImportServersBtn,
@ -7,6 +6,7 @@ import {
} from '../../../src/servers/helpers/ImportServersBtn'; } from '../../../src/servers/helpers/ImportServersBtn';
import { ServersImporter } from '../../../src/servers/services/ServersImporter'; import { ServersImporter } from '../../../src/servers/services/ServersImporter';
import { ServersMap, ServerWithId } from '../../../src/servers/data'; import { ServersMap, ServerWithId } from '../../../src/servers/data';
import { renderWithEvents } from '../../__mocks__/setUpTest';
describe('<ImportServersBtn />', () => { describe('<ImportServersBtn />', () => {
const onImportMock = jest.fn(); const onImportMock = jest.fn();
@ -14,17 +14,14 @@ describe('<ImportServersBtn />', () => {
const importServersFromFile = jest.fn().mockResolvedValue([]); const importServersFromFile = jest.fn().mockResolvedValue([]);
const serversImporterMock = Mock.of<ServersImporter>({ importServersFromFile }); const serversImporterMock = Mock.of<ServersImporter>({ importServersFromFile });
const ImportServersBtn = createImportServersBtn(serversImporterMock); const ImportServersBtn = createImportServersBtn(serversImporterMock);
const setUp = (props: Partial<ImportServersBtnProps> = {}, servers: ServersMap = {}) => ({ const setUp = (props: Partial<ImportServersBtnProps> = {}, servers: ServersMap = {}) => renderWithEvents(
user: userEvent.setup(),
...render(
<ImportServersBtn <ImportServersBtn
servers={servers} servers={servers}
{...props} {...props}
createServers={createServersMock} createServers={createServersMock}
onImport={onImportMock} onImport={onImportMock}
/>, />,
), );
});
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);

View file

@ -1,25 +1,22 @@
import userEvent from '@testing-library/user-event'; import { screen } from '@testing-library/react';
import { render, screen } from '@testing-library/react';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { import {
RealTimeUpdatesSettings as RealTimeUpdatesSettingsOptions, RealTimeUpdatesSettings as RealTimeUpdatesSettingsOptions,
Settings, Settings,
} from '../../src/settings/reducers/settings'; } from '../../src/settings/reducers/settings';
import { RealTimeUpdatesSettings } from '../../src/settings/RealTimeUpdatesSettings'; import { RealTimeUpdatesSettings } from '../../src/settings/RealTimeUpdatesSettings';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<RealTimeUpdatesSettings />', () => { describe('<RealTimeUpdatesSettings />', () => {
const toggleRealTimeUpdates = jest.fn(); const toggleRealTimeUpdates = jest.fn();
const setRealTimeUpdatesInterval = jest.fn(); const setRealTimeUpdatesInterval = jest.fn();
const setUp = (realTimeUpdates: Partial<RealTimeUpdatesSettingsOptions> = {}) => ({ const setUp = (realTimeUpdates: Partial<RealTimeUpdatesSettingsOptions> = {}) => renderWithEvents(
user: userEvent.setup(),
...render(
<RealTimeUpdatesSettings <RealTimeUpdatesSettings
settings={Mock.of<Settings>({ realTimeUpdates })} settings={Mock.of<Settings>({ realTimeUpdates })}
toggleRealTimeUpdates={toggleRealTimeUpdates} toggleRealTimeUpdates={toggleRealTimeUpdates}
setRealTimeUpdatesInterval={setRealTimeUpdatesInterval} setRealTimeUpdatesInterval={setRealTimeUpdatesInterval}
/>, />,
), );
});
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);

View file

@ -1,20 +1,17 @@
import { render, screen } from '@testing-library/react'; import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { ShortUrlCreationSettings as ShortUrlsSettings, Settings } from '../../src/settings/reducers/settings'; import { ShortUrlCreationSettings as ShortUrlsSettings, Settings } from '../../src/settings/reducers/settings';
import { ShortUrlCreationSettings } from '../../src/settings/ShortUrlCreationSettings'; import { ShortUrlCreationSettings } from '../../src/settings/ShortUrlCreationSettings';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<ShortUrlCreationSettings />', () => { describe('<ShortUrlCreationSettings />', () => {
const setShortUrlCreationSettings = jest.fn(); const setShortUrlCreationSettings = jest.fn();
const setUp = (shortUrlCreation?: ShortUrlsSettings) => ({ const setUp = (shortUrlCreation?: ShortUrlsSettings) => renderWithEvents(
user: userEvent.setup(),
...render(
<ShortUrlCreationSettings <ShortUrlCreationSettings
settings={Mock.of<Settings>({ shortUrlCreation })} settings={Mock.of<Settings>({ shortUrlCreation })}
setShortUrlCreationSettings={setShortUrlCreationSettings} setShortUrlCreationSettings={setShortUrlCreationSettings}
/>, />,
), );
});
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);

View file

@ -1,18 +1,15 @@
import userEvent from '@testing-library/user-event'; import { screen } from '@testing-library/react';
import { render, screen } from '@testing-library/react';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { Settings, ShortUrlsListSettings as ShortUrlsSettings } from '../../src/settings/reducers/settings'; import { Settings, ShortUrlsListSettings as ShortUrlsSettings } from '../../src/settings/reducers/settings';
import { ShortUrlsListSettings } from '../../src/settings/ShortUrlsListSettings'; import { ShortUrlsListSettings } from '../../src/settings/ShortUrlsListSettings';
import { ShortUrlsOrder } from '../../src/short-urls/data'; import { ShortUrlsOrder } from '../../src/short-urls/data';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<ShortUrlsListSettings />', () => { describe('<ShortUrlsListSettings />', () => {
const setSettings = jest.fn(); const setSettings = jest.fn();
const setUp = (shortUrlsList?: ShortUrlsSettings) => ({ const setUp = (shortUrlsList?: ShortUrlsSettings) => renderWithEvents(
user: userEvent.setup(),
...render(
<ShortUrlsListSettings settings={Mock.of<Settings>({ shortUrlsList })} setShortUrlsListSettings={setSettings} />, <ShortUrlsListSettings settings={Mock.of<Settings>({ shortUrlsList })} setShortUrlsListSettings={setSettings} />,
), );
});
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);

View file

@ -1,17 +1,16 @@
import userEvent from '@testing-library/user-event'; import { screen } from '@testing-library/react';
import { render, screen } from '@testing-library/react';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { Settings, TagsMode, TagsSettings as TagsSettingsOptions } from '../../src/settings/reducers/settings'; import { Settings, TagsMode, TagsSettings as TagsSettingsOptions } from '../../src/settings/reducers/settings';
import { TagsSettings } from '../../src/settings/TagsSettings'; import { TagsSettings } from '../../src/settings/TagsSettings';
import { TagsOrder } from '../../src/tags/data/TagsListChildrenProps'; import { TagsOrder } from '../../src/tags/data/TagsListChildrenProps';
import { capitalize } from '../../src/utils/utils'; import { capitalize } from '../../src/utils/utils';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<TagsSettings />', () => { describe('<TagsSettings />', () => {
const setTagsSettings = jest.fn(); const setTagsSettings = jest.fn();
const setUp = (tags?: TagsSettingsOptions) => ({ const setUp = (tags?: TagsSettingsOptions) => renderWithEvents(
user: userEvent.setup(), <TagsSettings settings={Mock.of<Settings>({ tags })} setTagsSettings={setTagsSettings} />,
...render(<TagsSettings settings={Mock.of<Settings>({ tags })} setTagsSettings={setTagsSettings} />), );
});
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);

View file

@ -1,16 +1,15 @@
import { render, screen } from '@testing-library/react'; import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { Settings, UiSettings } from '../../src/settings/reducers/settings'; import { Settings, UiSettings } from '../../src/settings/reducers/settings';
import { UserInterfaceSettings } from '../../src/settings/UserInterfaceSettings'; import { UserInterfaceSettings } from '../../src/settings/UserInterfaceSettings';
import { Theme } from '../../src/utils/theme'; import { Theme } from '../../src/utils/theme';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<UserInterfaceSettings />', () => { describe('<UserInterfaceSettings />', () => {
const setUiSettings = jest.fn(); const setUiSettings = jest.fn();
const setUp = (ui?: UiSettings) => ({ const setUp = (ui?: UiSettings) => renderWithEvents(
user: userEvent.setup(), <UserInterfaceSettings settings={Mock.of<Settings>({ ui })} setUiSettings={setUiSettings} />,
...render(<UserInterfaceSettings settings={Mock.of<Settings>({ ui })} setUiSettings={setUiSettings} />), );
});
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);

View file

@ -1,15 +1,14 @@
import { render, screen } from '@testing-library/react'; import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { Settings } from '../../src/settings/reducers/settings'; import { Settings } from '../../src/settings/reducers/settings';
import { VisitsSettings } from '../../src/settings/VisitsSettings'; import { VisitsSettings } from '../../src/settings/VisitsSettings';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<VisitsSettings />', () => { describe('<VisitsSettings />', () => {
const setVisitsSettings = jest.fn(); const setVisitsSettings = jest.fn();
const setUp = (settings: Partial<Settings> = {}) => ({ const setUp = (settings: Partial<Settings> = {}) => renderWithEvents(
user: userEvent.setup(), <VisitsSettings settings={Mock.of<Settings>(settings)} setVisitsSettings={setVisitsSettings} />,
...render(<VisitsSettings settings={Mock.of<Settings>(settings)} setVisitsSettings={setVisitsSettings} />), );
});
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);

View file

@ -1,5 +1,4 @@
import { render, screen } from '@testing-library/react'; import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { UserEvent } from '@testing-library/user-event/dist/types/setup'; import { UserEvent } from '@testing-library/user-event/dist/types/setup';
import { formatISO } from 'date-fns'; import { formatISO } from 'date-fns';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
@ -7,13 +6,13 @@ import { ShortUrlForm as createShortUrlForm, Mode } from '../../src/short-urls/S
import { ReachableServer, SelectedServer } from '../../src/servers/data'; import { ReachableServer, SelectedServer } from '../../src/servers/data';
import { parseDate } from '../../src/utils/helpers/date'; import { parseDate } from '../../src/utils/helpers/date';
import { OptionalString } from '../../src/utils/utils'; import { OptionalString } from '../../src/utils/utils';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<ShortUrlForm />', () => { describe('<ShortUrlForm />', () => {
const createShortUrl = jest.fn(async () => Promise.resolve()); const createShortUrl = jest.fn(async () => Promise.resolve());
const ShortUrlForm = createShortUrlForm(() => <span>TagsSelector</span>, () => <span>DomainSelector</span>); const ShortUrlForm = createShortUrlForm(() => <span>TagsSelector</span>, () => <span>DomainSelector</span>);
const setUp = (selectedServer: SelectedServer = null, mode: Mode = 'create', title?: OptionalString) => ({ const setUp = (selectedServer: SelectedServer = null, mode: Mode = 'create', title?: OptionalString) =>
user: userEvent.setup(), renderWithEvents(
...render(
<ShortUrlForm <ShortUrlForm
selectedServer={selectedServer} selectedServer={selectedServer}
mode={mode} mode={mode}
@ -21,8 +20,7 @@ describe('<ShortUrlForm />', () => {
initialState={{ validateUrl: true, findIfExists: false, title, longUrl: '' }} initialState={{ validateUrl: true, findIfExists: false, title, longUrl: '' }}
onSave={createShortUrl} onSave={createShortUrl}
/>, />,
), );
});
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);

View file

@ -1,5 +1,4 @@
import { render, screen, waitFor } from '@testing-library/react'; import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { endOfDay, formatISO, startOfDay } from 'date-fns'; import { endOfDay, formatISO, startOfDay } from 'date-fns';
import { MemoryRouter, useLocation, useNavigate } from 'react-router-dom'; import { MemoryRouter, useLocation, useNavigate } from 'react-router-dom';
@ -7,6 +6,7 @@ import { ShortUrlsFilteringBar as filteringBarCreator } from '../../src/short-ur
import { ReachableServer, SelectedServer } from '../../src/servers/data'; import { ReachableServer, SelectedServer } from '../../src/servers/data';
import { DateRange } from '../../src/utils/dates/types'; import { DateRange } from '../../src/utils/dates/types';
import { formatDate } from '../../src/utils/helpers/date'; import { formatDate } from '../../src/utils/helpers/date';
import { renderWithEvents } from '../__mocks__/setUpTest';
jest.mock('react-router-dom', () => ({ jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'), ...jest.requireActual('react-router-dom'),
@ -24,9 +24,7 @@ describe('<ShortUrlsFilteringBar />', () => {
(useLocation as any).mockReturnValue({ search }); (useLocation as any).mockReturnValue({ search });
(useNavigate as any).mockReturnValue(navigate); (useNavigate as any).mockReturnValue(navigate);
return { return renderWithEvents(
user: userEvent.setup(),
...render(
<MemoryRouter> <MemoryRouter>
<ShortUrlsFilteringBar <ShortUrlsFilteringBar
selectedServer={selectedServer ?? Mock.all<SelectedServer>()} selectedServer={selectedServer ?? Mock.all<SelectedServer>()}
@ -34,8 +32,7 @@ describe('<ShortUrlsFilteringBar />', () => {
handleOrderBy={handleOrderBy} handleOrderBy={handleOrderBy}
/> />
</MemoryRouter>, </MemoryRouter>,
), );
};
}; };
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);

View file

@ -1,5 +1,4 @@
import { render, screen } from '@testing-library/react'; import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { FC } from 'react'; import { FC } from 'react';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { MemoryRouter, useNavigate } from 'react-router-dom'; import { MemoryRouter, useNavigate } from 'react-router-dom';
@ -10,6 +9,7 @@ import { ShortUrlsList as ShortUrlsListModel } from '../../src/short-urls/reduce
import { ReachableServer } from '../../src/servers/data'; import { ReachableServer } from '../../src/servers/data';
import { Settings } from '../../src/settings/reducers/settings'; import { Settings } from '../../src/settings/reducers/settings';
import { ShortUrlsTableProps } from '../../src/short-urls/ShortUrlsTable'; import { ShortUrlsTableProps } from '../../src/short-urls/ShortUrlsTable';
import { renderWithEvents } from '../__mocks__/setUpTest';
jest.mock('react-router-dom', () => ({ jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'), ...jest.requireActual('react-router-dom'),
@ -36,9 +36,7 @@ describe('<ShortUrlsList />', () => {
}, },
}); });
const ShortUrlsList = createShortUrlsList(ShortUrlsTable, ShortUrlsFilteringBar); const ShortUrlsList = createShortUrlsList(ShortUrlsTable, ShortUrlsFilteringBar);
const setUp = (defaultOrdering: ShortUrlsOrder = {}) => ({ const setUp = (defaultOrdering: ShortUrlsOrder = {}) => renderWithEvents(
user: userEvent.setup(),
...render(
<MemoryRouter> <MemoryRouter>
<ShortUrlsList <ShortUrlsList
{...Mock.of<MercureBoundProps>({ mercureInfo: { loading: true } })} {...Mock.of<MercureBoundProps>({ mercureInfo: { loading: true } })}
@ -48,8 +46,7 @@ describe('<ShortUrlsList />', () => {
settings={Mock.of<Settings>({ shortUrlsList: { defaultOrdering } })} settings={Mock.of<Settings>({ shortUrlsList: { defaultOrdering } })}
/> />
</MemoryRouter>, </MemoryRouter>,
), );
});
beforeEach(() => { beforeEach(() => {
(useNavigate as any).mockReturnValue(navigate); (useNavigate as any).mockReturnValue(navigate);

View file

@ -1,21 +1,18 @@
import { fireEvent, render, screen } from '@testing-library/react'; import { fireEvent, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { ShortUrlsTable as shortUrlsTableCreator } from '../../src/short-urls/ShortUrlsTable'; import { ShortUrlsTable as shortUrlsTableCreator } from '../../src/short-urls/ShortUrlsTable';
import { ShortUrlsList } from '../../src/short-urls/reducers/shortUrlsList'; import { ShortUrlsList } from '../../src/short-urls/reducers/shortUrlsList';
import { ReachableServer, SelectedServer } from '../../src/servers/data'; import { ReachableServer, SelectedServer } from '../../src/servers/data';
import { ShortUrlsOrderableFields, SHORT_URLS_ORDERABLE_FIELDS } from '../../src/short-urls/data'; import { ShortUrlsOrderableFields, SHORT_URLS_ORDERABLE_FIELDS } from '../../src/short-urls/data';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<ShortUrlsTable />', () => { describe('<ShortUrlsTable />', () => {
const shortUrlsList = Mock.all<ShortUrlsList>(); const shortUrlsList = Mock.all<ShortUrlsList>();
const orderByColumn = jest.fn(); const orderByColumn = jest.fn();
const ShortUrlsTable = shortUrlsTableCreator(() => <span>ShortUrlsRow</span>); const ShortUrlsTable = shortUrlsTableCreator(() => <span>ShortUrlsRow</span>);
const setUp = (server: SelectedServer = null) => ({ const setUp = (server: SelectedServer = null) => renderWithEvents(
user: userEvent.setup(),
...render(
<ShortUrlsTable shortUrlsList={shortUrlsList} selectedServer={server} orderByColumn={() => orderByColumn} />, <ShortUrlsTable shortUrlsList={shortUrlsList} selectedServer={server} orderByColumn={() => orderByColumn} />,
), );
});
afterEach(jest.resetAllMocks); afterEach(jest.resetAllMocks);

View file

@ -1,11 +1,10 @@
import { render, screen } from '@testing-library/react'; import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { UseExistingIfFoundInfoIcon } from '../../src/short-urls/UseExistingIfFoundInfoIcon'; import { UseExistingIfFoundInfoIcon } from '../../src/short-urls/UseExistingIfFoundInfoIcon';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<UseExistingIfFoundInfoIcon />', () => { describe('<UseExistingIfFoundInfoIcon />', () => {
it('shows modal when icon is clicked', async () => { it('shows modal when icon is clicked', async () => {
const user = userEvent.setup(); const { user } = renderWithEvents(<UseExistingIfFoundInfoIcon />);
render(<UseExistingIfFoundInfoIcon />);
expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
await user.click(screen.getByTitle('What does this mean?').firstElementChild as Element); await user.click(screen.getByTitle('What does this mean?').firstElementChild as Element);

View file

@ -1,18 +1,17 @@
import { render, screen } from '@testing-library/react'; import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { CreateShortUrlResult as createResult } from '../../../src/short-urls/helpers/CreateShortUrlResult'; import { CreateShortUrlResult as createResult } from '../../../src/short-urls/helpers/CreateShortUrlResult';
import { ShortUrl } from '../../../src/short-urls/data'; import { ShortUrl } from '../../../src/short-urls/data';
import { TimeoutToggle } from '../../../src/utils/helpers/hooks'; import { TimeoutToggle } from '../../../src/utils/helpers/hooks';
import { renderWithEvents } from '../../__mocks__/setUpTest';
describe('<CreateShortUrlResult />', () => { describe('<CreateShortUrlResult />', () => {
const copyToClipboard = jest.fn(); const copyToClipboard = jest.fn();
const useTimeoutToggle = jest.fn(() => [false, copyToClipboard]) as TimeoutToggle; const useTimeoutToggle = jest.fn(() => [false, copyToClipboard]) as TimeoutToggle;
const CreateShortUrlResult = createResult(useTimeoutToggle); const CreateShortUrlResult = createResult(useTimeoutToggle);
const setUp = (result: ShortUrl | null = null, error = false) => ({ const setUp = (result: ShortUrl | null = null, error = false) => renderWithEvents(
user: userEvent.setup(), <CreateShortUrlResult resetCreateShortUrl={() => {}} result={result} error={error} saving={false} />,
...render(<CreateShortUrlResult resetCreateShortUrl={() => {}} result={result} error={error} saving={false} />), );
});
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);

View file

@ -1,10 +1,10 @@
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { render, screen, waitForElementToBeRemoved } from '@testing-library/react'; import { screen, waitForElementToBeRemoved } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router-dom'; import { MemoryRouter } from 'react-router-dom';
import { ReportExporter } from '../../../src/common/services/ReportExporter'; import { ReportExporter } from '../../../src/common/services/ReportExporter';
import { ExportShortUrlsBtn as createExportShortUrlsBtn } from '../../../src/short-urls/helpers/ExportShortUrlsBtn'; import { ExportShortUrlsBtn as createExportShortUrlsBtn } from '../../../src/short-urls/helpers/ExportShortUrlsBtn';
import { NotFoundServer, ReachableServer, SelectedServer } from '../../../src/servers/data'; import { NotFoundServer, ReachableServer, SelectedServer } from '../../../src/servers/data';
import { renderWithEvents } from '../../__mocks__/setUpTest';
describe('<ExportShortUrlsBtn />', () => { describe('<ExportShortUrlsBtn />', () => {
const listShortUrls = jest.fn(); const listShortUrls = jest.fn();
@ -12,14 +12,11 @@ describe('<ExportShortUrlsBtn />', () => {
const exportShortUrls = jest.fn(); const exportShortUrls = jest.fn();
const reportExporter = Mock.of<ReportExporter>({ exportShortUrls }); const reportExporter = Mock.of<ReportExporter>({ exportShortUrls });
const ExportShortUrlsBtn = createExportShortUrlsBtn(buildShlinkApiClient, reportExporter); const ExportShortUrlsBtn = createExportShortUrlsBtn(buildShlinkApiClient, reportExporter);
const setUp = (amount?: number, selectedServer?: SelectedServer) => ({ const setUp = (amount?: number, selectedServer?: SelectedServer) => renderWithEvents(
user: userEvent.setup(),
...render(
<MemoryRouter> <MemoryRouter>
<ExportShortUrlsBtn selectedServer={selectedServer ?? Mock.all<SelectedServer>()} amount={amount} /> <ExportShortUrlsBtn selectedServer={selectedServer ?? Mock.all<SelectedServer>()} amount={amount} />
</MemoryRouter>, </MemoryRouter>,
), );
});
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);

View file

@ -1,17 +1,14 @@
import { render, screen } from '@testing-library/react'; import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { QrErrorCorrection } from '../../../../src/utils/helpers/qrCodes'; import { QrErrorCorrection } from '../../../../src/utils/helpers/qrCodes';
import { QrErrorCorrectionDropdown } from '../../../../src/short-urls/helpers/qr-codes/QrErrorCorrectionDropdown'; import { QrErrorCorrectionDropdown } from '../../../../src/short-urls/helpers/qr-codes/QrErrorCorrectionDropdown';
import { renderWithEvents } from '../../../__mocks__/setUpTest';
describe('<QrErrorCorrectionDropdown />', () => { describe('<QrErrorCorrectionDropdown />', () => {
const initialErrorCorrection: QrErrorCorrection = 'Q'; const initialErrorCorrection: QrErrorCorrection = 'Q';
const setErrorCorrection = jest.fn(); const setErrorCorrection = jest.fn();
const setUp = () => ({ const setUp = () => renderWithEvents(
user: userEvent.setup(),
...render(
<QrErrorCorrectionDropdown errorCorrection={initialErrorCorrection} setErrorCorrection={setErrorCorrection} />, <QrErrorCorrectionDropdown errorCorrection={initialErrorCorrection} setErrorCorrection={setErrorCorrection} />,
), );
});
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);

View file

@ -1,15 +1,12 @@
import { render, screen } from '@testing-library/react'; import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { QrCodeFormat } from '../../../../src/utils/helpers/qrCodes'; import { QrCodeFormat } from '../../../../src/utils/helpers/qrCodes';
import { QrFormatDropdown } from '../../../../src/short-urls/helpers/qr-codes/QrFormatDropdown'; import { QrFormatDropdown } from '../../../../src/short-urls/helpers/qr-codes/QrFormatDropdown';
import { renderWithEvents } from '../../../__mocks__/setUpTest';
describe('<QrFormatDropdown />', () => { describe('<QrFormatDropdown />', () => {
const initialFormat: QrCodeFormat = 'svg'; const initialFormat: QrCodeFormat = 'svg';
const setFormat = jest.fn(); const setFormat = jest.fn();
const setUp = () => ({ const setUp = () => renderWithEvents(<QrFormatDropdown format={initialFormat} setFormat={setFormat} />);
user: userEvent.setup(),
...render(<QrFormatDropdown format={initialFormat} setFormat={setFormat} />),
});
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);

View file

@ -1,10 +1,10 @@
import userEvent from '@testing-library/user-event'; import { screen } from '@testing-library/react';
import { render, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom'; import { MemoryRouter } from 'react-router-dom';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { TagCard as createTagCard } from '../../src/tags/TagCard'; import { TagCard as createTagCard } from '../../src/tags/TagCard';
import { ColorGenerator } from '../../src/utils/services/ColorGenerator'; import { ColorGenerator } from '../../src/utils/services/ColorGenerator';
import { ReachableServer } from '../../src/servers/data'; import { ReachableServer } from '../../src/servers/data';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<TagCard />', () => { describe('<TagCard />', () => {
const TagCard = createTagCard( const TagCard = createTagCard(
@ -12,9 +12,7 @@ describe('<TagCard />', () => {
({ isOpen }) => <span>EditTagModal {isOpen ? '[Open]' : '[Closed]'}</span>, ({ isOpen }) => <span>EditTagModal {isOpen ? '[Open]' : '[Closed]'}</span>,
Mock.of<ColorGenerator>({ getColorForKey: () => '' }), Mock.of<ColorGenerator>({ getColorForKey: () => '' }),
); );
const setUp = (tag = 'ssr') => ({ const setUp = (tag = 'ssr') => renderWithEvents(
user: userEvent.setup(),
...render(
<MemoryRouter> <MemoryRouter>
<TagCard <TagCard
tag={{ tag, visits: 23257, shortUrls: 48 }} tag={{ tag, visits: 23257, shortUrls: 48 }}
@ -23,8 +21,7 @@ describe('<TagCard />', () => {
toggle={() => {}} toggle={() => {}}
/> />
</MemoryRouter>, </MemoryRouter>,
), );
});
afterEach(jest.resetAllMocks); afterEach(jest.resetAllMocks);

View file

@ -1,19 +1,18 @@
import { render, screen } from '@testing-library/react'; import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { TagsCards as createTagsCards } from '../../src/tags/TagsCards'; import { TagsCards as createTagsCards } from '../../src/tags/TagsCards';
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 { NormalizedTag } from '../../src/tags/data'; import { NormalizedTag } from '../../src/tags/data';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<TagsCards />', () => { describe('<TagsCards />', () => {
const amountOfTags = 10; const amountOfTags = 10;
const sortedTags = rangeOf(amountOfTags, (i) => Mock.of<NormalizedTag>({ tag: `tag_${i}` })); const sortedTags = rangeOf(amountOfTags, (i) => Mock.of<NormalizedTag>({ tag: `tag_${i}` }));
const TagsCards = createTagsCards(() => <span>TagCard</span>); const TagsCards = createTagsCards(() => <span>TagCard</span>);
const setUp = () => ({ const setUp = () => renderWithEvents(
user: userEvent.setup(), <TagsCards sortedTags={sortedTags} selectedServer={Mock.all<SelectedServer>()} />,
...render(<TagsCards sortedTags={sortedTags} selectedServer={Mock.all<SelectedServer>()} />), );
});
it('renders the proper amount of groups and cards based on the amount of tags', () => { it('renders the proper amount of groups and cards based on the amount of tags', () => {
const { container } = setUp(); const { container } = setUp();

View file

@ -1,18 +1,16 @@
import { render, screen, waitFor } from '@testing-library/react'; import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { identity } from 'ramda'; import { identity } from 'ramda';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { TagsList as createTagsList, TagsListProps } from '../../src/tags/TagsList'; import { TagsList as createTagsList, TagsListProps } from '../../src/tags/TagsList';
import { TagsList } from '../../src/tags/reducers/tagsList'; import { TagsList } from '../../src/tags/reducers/tagsList';
import { MercureBoundProps } from '../../src/mercure/helpers/boundToMercureHub'; import { MercureBoundProps } from '../../src/mercure/helpers/boundToMercureHub';
import { Settings } from '../../src/settings/reducers/settings'; import { Settings } from '../../src/settings/reducers/settings';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<TagsList />', () => { describe('<TagsList />', () => {
const filterTags = jest.fn(); const filterTags = jest.fn();
const TagsListComp = createTagsList(() => <>TagsCards</>, () => <>TagsTable</>); const TagsListComp = createTagsList(() => <>TagsCards</>, () => <>TagsTable</>);
const setUp = (tagsList: Partial<TagsList>) => ({ const setUp = (tagsList: Partial<TagsList>) => renderWithEvents(
user: userEvent.setup(),
...render(
<TagsListComp <TagsListComp
{...Mock.all<TagsListProps>()} {...Mock.all<TagsListProps>()}
{...Mock.of<MercureBoundProps>({ mercureInfo: {} })} {...Mock.of<MercureBoundProps>({ mercureInfo: {} })}
@ -21,8 +19,7 @@ describe('<TagsList />', () => {
tagsList={Mock.of<TagsList>(tagsList)} tagsList={Mock.of<TagsList>(tagsList)}
settings={Mock.all<Settings>()} settings={Mock.all<Settings>()}
/>, />,
), );
});
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);

View file

@ -1,14 +1,11 @@
import { render, screen } from '@testing-library/react'; import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { TagsModeDropdown } from '../../src/tags/TagsModeDropdown'; import { TagsModeDropdown } from '../../src/tags/TagsModeDropdown';
import { TagsMode } from '../../src/settings/reducers/settings'; import { TagsMode } from '../../src/settings/reducers/settings';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<TagsModeDropdown />', () => { describe('<TagsModeDropdown />', () => {
const onChange = jest.fn(); const onChange = jest.fn();
const setUp = (mode: TagsMode) => ({ const setUp = (mode: TagsMode) => renderWithEvents(<TagsModeDropdown mode={mode} onChange={onChange} />);
user: userEvent.setup(),
...render(<TagsModeDropdown mode={mode} onChange={onChange} />),
});
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);

View file

@ -2,12 +2,24 @@ import { shallow, ShallowWrapper } from 'enzyme';
import { Button, Modal, ModalBody, ModalFooter } from 'reactstrap'; import { Button, Modal, ModalBody, ModalFooter } from 'reactstrap';
import { DeleteTagConfirmModal } from '../../../src/tags/helpers/DeleteTagConfirmModal'; import { DeleteTagConfirmModal } from '../../../src/tags/helpers/DeleteTagConfirmModal';
import { TagDeletion } from '../../../src/tags/reducers/tagDelete'; import { TagDeletion } from '../../../src/tags/reducers/tagDelete';
import { renderWithEvents } from '../../__mocks__/setUpTest';
describe('<DeleteTagConfirmModal />', () => { describe('<DeleteTagConfirmModal />', () => {
let wrapper: ShallowWrapper;
const tag = 'nodejs'; const tag = 'nodejs';
const deleteTag = jest.fn(); const deleteTag = jest.fn();
const tagDeleted = jest.fn(); const tagDeleted = jest.fn();
const setUp = (tagDelete: TagDeletion) => renderWithEvents(
<DeleteTagConfirmModal
tag={tag}
toggle={() => ''}
isOpen
deleteTag={deleteTag}
tagDeleted={tagDeleted}
tagDelete={tagDelete}
/>,
);
let wrapper: ShallowWrapper;
const createWrapper = (tagDelete: TagDeletion) => { const createWrapper = (tagDelete: TagDeletion) => {
wrapper = shallow( wrapper = shallow(
<DeleteTagConfirmModal <DeleteTagConfirmModal
@ -22,8 +34,8 @@ describe('<DeleteTagConfirmModal />', () => {
return wrapper; return wrapper;
}; };
afterEach(() => wrapper?.unmount()); afterEach(() => wrapper?.unmount());
afterEach(jest.resetAllMocks); afterEach(jest.resetAllMocks);
it('asks confirmation for provided tag to be deleted', () => { it('asks confirmation for provided tag to be deleted', () => {

View file

@ -1,10 +1,10 @@
import { render, screen } from '@testing-library/react'; import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { ReactNode } from 'react'; import { ReactNode } from 'react';
import { ColorGenerator } from '../../../src/utils/services/ColorGenerator'; import { ColorGenerator } from '../../../src/utils/services/ColorGenerator';
import { MAIN_COLOR } from '../../../src/utils/theme'; import { MAIN_COLOR } from '../../../src/utils/theme';
import { Tag } from '../../../src/tags/helpers/Tag'; import { Tag } from '../../../src/tags/helpers/Tag';
import { renderWithEvents } from '../../__mocks__/setUpTest';
const hexToRgb = (hex: string) => { const hexToRgb = (hex: string) => {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
@ -25,14 +25,11 @@ describe('<Tag />', () => {
const isColorLightForKey = jest.fn(() => false); const isColorLightForKey = jest.fn(() => false);
const getColorForKey = jest.fn(() => MAIN_COLOR); const getColorForKey = jest.fn(() => MAIN_COLOR);
const colorGenerator = Mock.of<ColorGenerator>({ getColorForKey, isColorLightForKey }); const colorGenerator = Mock.of<ColorGenerator>({ getColorForKey, isColorLightForKey });
const setUp = (text: string, clearable?: boolean, children?: ReactNode) => ({ const setUp = (text: string, clearable?: boolean, children?: ReactNode) => renderWithEvents(
user: userEvent.setup(),
...render(
<Tag text={text} clearable={clearable} colorGenerator={colorGenerator} onClick={onClick} onClose={onClose}> <Tag text={text} clearable={clearable} colorGenerator={colorGenerator} onClick={onClick} onClose={onClose}>
{children} {children}
</Tag>, </Tag>,
), );
});
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);

View file

@ -1,6 +1,6 @@
import { render, screen } from '@testing-library/react'; import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Checkbox } from '../../src/utils/Checkbox'; import { Checkbox } from '../../src/utils/Checkbox';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<Checkbox />', () => { describe('<Checkbox />', () => {
it.each([['foo'], ['bar'], ['baz']])('includes extra class names when provided', (className) => { it.each([['foo'], ['bar'], ['baz']])('includes extra class names when provided', (className) => {
@ -24,9 +24,8 @@ describe('<Checkbox />', () => {
}); });
it.each([[true], [false]])('changes checked status on input change', async (checked) => { it.each([[true], [false]])('changes checked status on input change', async (checked) => {
const user = userEvent.setup();
const onChange = jest.fn(); const onChange = jest.fn();
render(<Checkbox onChange={onChange} checked={checked}>Foo</Checkbox>); const { user } = renderWithEvents(<Checkbox onChange={onChange} checked={checked}>Foo</Checkbox>);
expect(onChange).not.toHaveBeenCalled(); expect(onChange).not.toHaveBeenCalled();
await user.click(screen.getByLabelText('Foo')); await user.click(screen.getByLabelText('Foo'));

View file

@ -1,13 +1,9 @@
import { render } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { CopyToClipboardIcon } from '../../src/utils/CopyToClipboardIcon'; import { CopyToClipboardIcon } from '../../src/utils/CopyToClipboardIcon';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<CopyToClipboardIcon />', () => { describe('<CopyToClipboardIcon />', () => {
const onCopy = jest.fn(); const onCopy = jest.fn();
const setUp = (text = 'foo') => ({ const setUp = (text = 'foo') => renderWithEvents(<CopyToClipboardIcon text={text} onCopy={onCopy} />);
user: userEvent.setup(),
...render(<CopyToClipboardIcon text={text} onCopy={onCopy} />),
});
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);

View file

@ -1,13 +1,12 @@
import { render, screen, waitFor } from '@testing-library/react'; import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { DateInput, DateInputProps } from '../../src/utils/DateInput'; import { DateInput, DateInputProps } from '../../src/utils/DateInput';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<DateInput />', () => { describe('<DateInput />', () => {
const setUp = (props: Partial<DateInputProps> = {}) => ({ const setUp = (props: Partial<DateInputProps> = {}) => renderWithEvents(
user: userEvent.setup(), <DateInput {...Mock.of<DateInputProps>(props)} />,
...render(<DateInput {...Mock.of<DateInputProps>(props)} />), );
});
it('shows calendar icon when input is not clearable', () => { it('shows calendar icon when input is not clearable', () => {
setUp({ isClearable: false }); setUp({ isClearable: false });

View file

@ -1,13 +1,12 @@
import { render, screen, waitFor } from '@testing-library/react'; import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Placement } from '@popperjs/core'; import { Placement } from '@popperjs/core';
import { InfoTooltip, InfoTooltipProps } from '../../src/utils/InfoTooltip'; import { InfoTooltip, InfoTooltipProps } from '../../src/utils/InfoTooltip';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<InfoTooltip />', () => { describe('<InfoTooltip />', () => {
const setUp = (props: Partial<InfoTooltipProps> = {}) => ({ const setUp = (props: Partial<InfoTooltipProps> = {}) => renderWithEvents(
user: userEvent.setup(), <InfoTooltip placement="right" {...props} />,
...render(<InfoTooltip placement="right" {...props} />), );
});
it.each([ it.each([
[undefined], [undefined],

View file

@ -1,8 +1,8 @@
import { render, screen } from '@testing-library/react'; import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { values } from 'ramda'; import { values } from 'ramda';
import { OrderingDropdown, OrderingDropdownProps } from '../../src/utils/OrderingDropdown'; import { OrderingDropdown, OrderingDropdownProps } from '../../src/utils/OrderingDropdown';
import { OrderDir } from '../../src/utils/helpers/ordering'; import { OrderDir } from '../../src/utils/helpers/ordering';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<OrderingDropdown />', () => { describe('<OrderingDropdown />', () => {
const items = { const items = {
@ -10,10 +10,9 @@ describe('<OrderingDropdown />', () => {
bar: 'Bar', bar: 'Bar',
baz: 'Hello World', baz: 'Hello World',
}; };
const setUp = (props: Partial<OrderingDropdownProps> = {}) => ({ const setUp = (props: Partial<OrderingDropdownProps> = {}) => renderWithEvents(
user: userEvent.setup(), <OrderingDropdown items={items} order={{}} onChange={jest.fn()} {...props} />,
...render(<OrderingDropdown items={items} order={{}} onChange={jest.fn()} {...props} />), );
});
const setUpWithDisplayedMenu = async (props: Partial<OrderingDropdownProps> = {}) => { const setUpWithDisplayedMenu = async (props: Partial<OrderingDropdownProps> = {}) => {
const result = setUp(props); const result = setUp(props);
const { user } = result; const { user } = result;

View file

@ -1,14 +1,13 @@
import { render, screen, waitFor } from '@testing-library/react'; import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { DateIntervalDropdownItems } from '../../../src/utils/dates/DateIntervalDropdownItems'; import { DateIntervalDropdownItems } from '../../../src/utils/dates/DateIntervalDropdownItems';
import { DATE_INTERVALS, DateInterval, rangeOrIntervalToString } from '../../../src/utils/dates/types'; import { DATE_INTERVALS, DateInterval, rangeOrIntervalToString } from '../../../src/utils/dates/types';
import { DropdownBtn } from '../../../src/utils/DropdownBtn'; import { DropdownBtn } from '../../../src/utils/DropdownBtn';
import { renderWithEvents } from '../../__mocks__/setUpTest';
describe('<DateIntervalDropdownItems />', () => { describe('<DateIntervalDropdownItems />', () => {
const onChange = jest.fn(); const onChange = jest.fn();
const setUp = async () => { const setUp = async () => {
const user = userEvent.setup(); const { user, ...renderResult } = renderWithEvents(
const renderResult = render(
<DropdownBtn text="text"> <DropdownBtn text="text">
<DateIntervalDropdownItems allText="All" active="last180Days" onChange={onChange} /> <DateIntervalDropdownItems allText="All" active="last180Days" onChange={onChange} />
</DropdownBtn>, </DropdownBtn>,

View file

@ -1,15 +1,14 @@
import { render, screen, waitFor } from '@testing-library/react'; import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { DateInterval, rangeOrIntervalToString } from '../../../src/utils/dates/types'; import { DateInterval, rangeOrIntervalToString } from '../../../src/utils/dates/types';
import { DateIntervalSelector } from '../../../src/utils/dates/DateIntervalSelector'; import { DateIntervalSelector } from '../../../src/utils/dates/DateIntervalSelector';
import { renderWithEvents } from '../../__mocks__/setUpTest';
describe('<DateIntervalSelector />', () => { describe('<DateIntervalSelector />', () => {
const activeInterval: DateInterval = 'last7Days'; const activeInterval: DateInterval = 'last7Days';
const onChange = jest.fn(); const onChange = jest.fn();
const setUp = () => ({ const setUp = () => renderWithEvents(
user: userEvent.setup(), <DateIntervalSelector allText="All text" active={activeInterval} onChange={onChange} />,
...render(<DateIntervalSelector allText="All text" active={activeInterval} onChange={onChange} />), );
});
it('passes props down to nested DateIntervalDropdownItems', async () => { it('passes props down to nested DateIntervalDropdownItems', async () => {
const { user } = setUp(); const { user } = setUp();

View file

@ -1,5 +1,4 @@
import { render, screen } from '@testing-library/react'; import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router-dom'; import { MemoryRouter } from 'react-router-dom';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { formatISO } from 'date-fns'; import { formatISO } from 'date-fns';
@ -10,6 +9,7 @@ import { DomainVisits } from '../../src/visits/reducers/domainVisits';
import { Settings } from '../../src/settings/reducers/settings'; import { Settings } from '../../src/settings/reducers/settings';
import { SelectedServer } from '../../src/servers/data'; import { SelectedServer } from '../../src/servers/data';
import { Visit } from '../../src/visits/types'; import { Visit } from '../../src/visits/types';
import { renderWithEvents } from '../__mocks__/setUpTest';
jest.mock('react-router-dom', () => ({ jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'), ...jest.requireActual('react-router-dom'),
@ -22,9 +22,7 @@ describe('<DomainVisits />', () => {
const cancelGetDomainVisits = jest.fn(); const cancelGetDomainVisits = jest.fn();
const domainVisits = Mock.of<DomainVisits>({ visits: [Mock.of<Visit>({ date: formatISO(new Date()) })] }); const domainVisits = Mock.of<DomainVisits>({ visits: [Mock.of<Visit>({ date: formatISO(new Date()) })] });
const DomainVisits = createDomainVisits(Mock.of<ReportExporter>({ exportVisits })); const DomainVisits = createDomainVisits(Mock.of<ReportExporter>({ exportVisits }));
const setUp = () => ({ const setUp = () => renderWithEvents(
user: userEvent.setup(),
...render(
<MemoryRouter> <MemoryRouter>
<DomainVisits <DomainVisits
{...Mock.of<MercureBoundProps>({ mercureInfo: {} })} {...Mock.of<MercureBoundProps>({ mercureInfo: {} })}
@ -35,8 +33,7 @@ describe('<DomainVisits />', () => {
selectedServer={Mock.all<SelectedServer>()} selectedServer={Mock.all<SelectedServer>()}
/> />
</MemoryRouter>, </MemoryRouter>,
), );
});
it('wraps visits stats and header', () => { it('wraps visits stats and header', () => {
setUp(); setUp();

View file

@ -1,5 +1,4 @@
import { render, screen } from '@testing-library/react'; import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router-dom'; import { MemoryRouter } from 'react-router-dom';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { formatISO } from 'date-fns'; import { formatISO } from 'date-fns';
@ -9,6 +8,7 @@ import { Visit, VisitsInfo } from '../../src/visits/types';
import { Settings } from '../../src/settings/reducers/settings'; import { Settings } from '../../src/settings/reducers/settings';
import { ReportExporter } from '../../src/common/services/ReportExporter'; import { ReportExporter } from '../../src/common/services/ReportExporter';
import { SelectedServer } from '../../src/servers/data'; import { SelectedServer } from '../../src/servers/data';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<NonOrphanVisits />', () => { describe('<NonOrphanVisits />', () => {
const exportVisits = jest.fn(); const exportVisits = jest.fn();
@ -16,9 +16,7 @@ describe('<NonOrphanVisits />', () => {
const cancelGetNonOrphanVisits = jest.fn(); const cancelGetNonOrphanVisits = jest.fn();
const nonOrphanVisits = Mock.of<VisitsInfo>({ visits: [Mock.of<Visit>({ date: formatISO(new Date()) })] }); const nonOrphanVisits = Mock.of<VisitsInfo>({ visits: [Mock.of<Visit>({ date: formatISO(new Date()) })] });
const NonOrphanVisits = createNonOrphanVisits(Mock.of<ReportExporter>({ exportVisits })); const NonOrphanVisits = createNonOrphanVisits(Mock.of<ReportExporter>({ exportVisits }));
const setUp = () => ({ const setUp = () => renderWithEvents(
user: userEvent.setup(),
...render(
<MemoryRouter> <MemoryRouter>
<NonOrphanVisits <NonOrphanVisits
{...Mock.of<MercureBoundProps>({ mercureInfo: {} })} {...Mock.of<MercureBoundProps>({ mercureInfo: {} })}
@ -29,8 +27,7 @@ describe('<NonOrphanVisits />', () => {
selectedServer={Mock.all<SelectedServer>()} selectedServer={Mock.all<SelectedServer>()}
/> />
</MemoryRouter>, </MemoryRouter>,
), );
});
it('wraps visits stats and header', () => { it('wraps visits stats and header', () => {
setUp(); setUp();

View file

@ -1,5 +1,4 @@
import { render, screen } from '@testing-library/react'; import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router-dom'; import { MemoryRouter } from 'react-router-dom';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { formatISO } from 'date-fns'; import { formatISO } from 'date-fns';
@ -9,15 +8,14 @@ import { Visit, VisitsInfo } from '../../src/visits/types';
import { Settings } from '../../src/settings/reducers/settings'; import { Settings } from '../../src/settings/reducers/settings';
import { ReportExporter } from '../../src/common/services/ReportExporter'; import { ReportExporter } from '../../src/common/services/ReportExporter';
import { SelectedServer } from '../../src/servers/data'; import { SelectedServer } from '../../src/servers/data';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<OrphanVisits />', () => { describe('<OrphanVisits />', () => {
const getOrphanVisits = jest.fn(); const getOrphanVisits = jest.fn();
const exportVisits = jest.fn(); const exportVisits = jest.fn();
const orphanVisits = Mock.of<VisitsInfo>({ visits: [Mock.of<Visit>({ date: formatISO(new Date()) })] }); const orphanVisits = Mock.of<VisitsInfo>({ visits: [Mock.of<Visit>({ date: formatISO(new Date()) })] });
const OrphanVisits = createOrphanVisits(Mock.of<ReportExporter>({ exportVisits })); const OrphanVisits = createOrphanVisits(Mock.of<ReportExporter>({ exportVisits }));
const setUp = () => ({ const setUp = () => renderWithEvents(
user: userEvent.setup(),
...render(
<MemoryRouter> <MemoryRouter>
<OrphanVisits <OrphanVisits
{...Mock.of<MercureBoundProps>({ mercureInfo: {} })} {...Mock.of<MercureBoundProps>({ mercureInfo: {} })}
@ -28,8 +26,7 @@ describe('<OrphanVisits />', () => {
selectedServer={Mock.all<SelectedServer>()} selectedServer={Mock.all<SelectedServer>()}
/> />
</MemoryRouter>, </MemoryRouter>,
), );
});
it('wraps visits stats and header', () => { it('wraps visits stats and header', () => {
setUp(); setUp();

View file

@ -1,5 +1,4 @@
import { render, screen } from '@testing-library/react'; import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router-dom'; import { MemoryRouter } from 'react-router-dom';
import { identity } from 'ramda'; import { identity } from 'ramda';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
@ -11,15 +10,14 @@ import { MercureBoundProps } from '../../src/mercure/helpers/boundToMercureHub';
import { ReportExporter } from '../../src/common/services/ReportExporter'; import { ReportExporter } from '../../src/common/services/ReportExporter';
import { Visit } from '../../src/visits/types'; import { Visit } from '../../src/visits/types';
import { Settings } from '../../src/settings/reducers/settings'; import { Settings } from '../../src/settings/reducers/settings';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<ShortUrlVisits />', () => { describe('<ShortUrlVisits />', () => {
const getShortUrlVisitsMock = jest.fn(); const getShortUrlVisitsMock = jest.fn();
const exportVisits = jest.fn(); const exportVisits = jest.fn();
const shortUrlVisits = Mock.of<ShortUrlVisitsState>({ visits: [Mock.of<Visit>({ date: formatISO(new Date()) })] }); const shortUrlVisits = Mock.of<ShortUrlVisitsState>({ visits: [Mock.of<Visit>({ date: formatISO(new Date()) })] });
const ShortUrlVisits = createShortUrlVisits(Mock.of<ReportExporter>({ exportVisits })); const ShortUrlVisits = createShortUrlVisits(Mock.of<ReportExporter>({ exportVisits }));
const setUp = () => ({ const setUp = () => renderWithEvents(
user: userEvent.setup(),
...render(
<MemoryRouter> <MemoryRouter>
<ShortUrlVisits <ShortUrlVisits
{...Mock.all<ShortUrlVisitsProps>()} {...Mock.all<ShortUrlVisitsProps>()}
@ -32,8 +30,7 @@ describe('<ShortUrlVisits />', () => {
cancelGetShortUrlVisits={() => {}} cancelGetShortUrlVisits={() => {}}
/> />
</MemoryRouter>, </MemoryRouter>,
), );
});
it('wraps visits stats and header', () => { it('wraps visits stats and header', () => {
setUp(); setUp();

View file

@ -1,10 +1,10 @@
import { render, screen, waitFor } from '@testing-library/react'; import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { formatDistance, parseISO } from 'date-fns'; import { formatDistance, parseISO } from 'date-fns';
import { ShortUrlVisitsHeader } from '../../src/visits/ShortUrlVisitsHeader'; import { ShortUrlVisitsHeader } from '../../src/visits/ShortUrlVisitsHeader';
import { ShortUrlDetail } from '../../src/short-urls/reducers/shortUrlDetail'; import { ShortUrlDetail } from '../../src/short-urls/reducers/shortUrlDetail';
import { ShortUrlVisits } from '../../src/visits/reducers/shortUrlVisits'; import { ShortUrlVisits } from '../../src/visits/reducers/shortUrlVisits';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<ShortUrlVisitsHeader />', () => { describe('<ShortUrlVisitsHeader />', () => {
const dateCreated = '2018-01-01T10:00:00+00:00'; const dateCreated = '2018-01-01T10:00:00+00:00';
@ -23,12 +23,9 @@ describe('<ShortUrlVisitsHeader />', () => {
}, },
loading: false, loading: false,
}); });
return { return renderWithEvents(
user: userEvent.setup(),
...render(
<ShortUrlVisitsHeader shortUrlDetail={shortUrlDetail} shortUrlVisits={shortUrlVisits} goBack={goBack} />, <ShortUrlVisitsHeader shortUrlDetail={shortUrlDetail} shortUrlVisits={shortUrlVisits} goBack={goBack} />,
), );
};
}; };
it('shows when the URL was created', async () => { it('shows when the URL was created', async () => {

View file

@ -1,5 +1,4 @@
import { render, screen } from '@testing-library/react'; import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { formatISO } from 'date-fns'; import { formatISO } from 'date-fns';
import { MemoryRouter } from 'react-router-dom'; import { MemoryRouter } from 'react-router-dom';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
@ -10,6 +9,7 @@ import { MercureBoundProps } from '../../src/mercure/helpers/boundToMercureHub';
import { ReportExporter } from '../../src/common/services/ReportExporter'; import { ReportExporter } from '../../src/common/services/ReportExporter';
import { Visit } from '../../src/visits/types'; import { Visit } from '../../src/visits/types';
import { Settings } from '../../src/settings/reducers/settings'; import { Settings } from '../../src/settings/reducers/settings';
import { renderWithEvents } from '../__mocks__/setUpTest';
jest.mock('react-router-dom', () => ({ jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'), ...jest.requireActual('react-router-dom'),
@ -24,9 +24,7 @@ describe('<TagVisits />', () => {
Mock.of<ColorGenerator>({ isColorLightForKey: () => false, getColorForKey: () => 'red' }), Mock.of<ColorGenerator>({ isColorLightForKey: () => false, getColorForKey: () => 'red' }),
Mock.of<ReportExporter>({ exportVisits }), Mock.of<ReportExporter>({ exportVisits }),
); );
const setUp = () => ({ const setUp = () => renderWithEvents(
user: userEvent.setup(),
...render(
<MemoryRouter> <MemoryRouter>
<TagVisits <TagVisits
{...Mock.all<TagVisitsProps>()} {...Mock.all<TagVisitsProps>()}
@ -37,8 +35,7 @@ describe('<TagVisits />', () => {
cancelGetTagVisits={() => {}} cancelGetTagVisits={() => {}}
/> />
</MemoryRouter>, </MemoryRouter>,
), );
});
it('wraps visits stats and header', () => { it('wraps visits stats and header', () => {
setUp(); setUp();

View file

@ -1,6 +1,6 @@
import { screen } from '@testing-library/react'; import { screen } from '@testing-library/react';
import { DoughnutChart } from '../../../src/visits/charts/DoughnutChart'; import { DoughnutChart } from '../../../src/visits/charts/DoughnutChart';
import { setUpCanvas } from '../../__mocks__/setUpCanvas'; import { setUpCanvas } from '../../__mocks__/setUpTest';
describe('<DoughnutChart />', () => { describe('<DoughnutChart />', () => {
const stats = { const stats = {

View file

@ -1,5 +1,5 @@
import { HorizontalBarChart, HorizontalBarChartProps } from '../../../src/visits/charts/HorizontalBarChart'; import { HorizontalBarChart, HorizontalBarChartProps } from '../../../src/visits/charts/HorizontalBarChart';
import { setUpCanvas } from '../../__mocks__/setUpCanvas'; import { setUpCanvas } from '../../__mocks__/setUpTest';
describe('<HorizontalBarChart />', () => { describe('<HorizontalBarChart />', () => {
const setUp = (props: HorizontalBarChartProps) => setUpCanvas(<HorizontalBarChart {...props} />); const setUp = (props: HorizontalBarChartProps) => setUpCanvas(<HorizontalBarChart {...props} />);

View file

@ -4,7 +4,7 @@ import { formatISO, subDays, subMonths, subYears } from 'date-fns';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { LineChartCard } from '../../../src/visits/charts/LineChartCard'; import { LineChartCard } from '../../../src/visits/charts/LineChartCard';
import { NormalizedVisit } from '../../../src/visits/types'; import { NormalizedVisit } from '../../../src/visits/types';
import { setUpCanvas } from '../../__mocks__/setUpCanvas'; import { setUpCanvas } from '../../__mocks__/setUpTest';
describe('<LineChartCard />', () => { describe('<LineChartCard />', () => {
const setUp = (visits: NormalizedVisit[] = [], highlightedVisits: NormalizedVisit[] = []) => ({ const setUp = (visits: NormalizedVisit[] = [], highlightedVisits: NormalizedVisit[] = []) => ({

View file

@ -1,8 +1,8 @@
import { render, screen, waitFor } from '@testing-library/react'; import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { OpenMapModalBtn } from '../../../src/visits/helpers/OpenMapModalBtn'; import { OpenMapModalBtn } from '../../../src/visits/helpers/OpenMapModalBtn';
import { CityStats } from '../../../src/visits/types'; import { CityStats } from '../../../src/visits/types';
import { renderWithEvents } from '../../__mocks__/setUpTest';
describe('<OpenMapModalBtn />', () => { describe('<OpenMapModalBtn />', () => {
const title = 'Foo'; const title = 'Foo';
@ -10,10 +10,9 @@ describe('<OpenMapModalBtn />', () => {
Mock.of<CityStats>({ cityName: 'foo', count: 30, latLong: [5, 5] }), Mock.of<CityStats>({ cityName: 'foo', count: 30, latLong: [5, 5] }),
Mock.of<CityStats>({ cityName: 'bar', count: 45, latLong: [88, 88] }), Mock.of<CityStats>({ cityName: 'bar', count: 45, latLong: [88, 88] }),
]; ];
const setUp = (activeCities?: string[]) => ({ const setUp = (activeCities?: string[]) => renderWithEvents(
user: userEvent.setup(), <OpenMapModalBtn modalTitle={title} locations={locations} activeCities={activeCities} />,
...render(<OpenMapModalBtn modalTitle={title} locations={locations} activeCities={activeCities} />), );
});
it('renders tooltip on button hover and opens modal on click', async () => { it('renders tooltip on button hover and opens modal on click', async () => {
const { user } = setUp(); const { user } = setUp();

View file

@ -1,21 +1,18 @@
import { render, screen } from '@testing-library/react'; import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { OrphanVisitType, VisitsFilter } from '../../../src/visits/types'; import { OrphanVisitType, VisitsFilter } from '../../../src/visits/types';
import { VisitsFilterDropdown } from '../../../src/visits/helpers/VisitsFilterDropdown'; import { VisitsFilterDropdown } from '../../../src/visits/helpers/VisitsFilterDropdown';
import { renderWithEvents } from '../../__mocks__/setUpTest';
describe('<VisitsFilterDropdown />', () => { describe('<VisitsFilterDropdown />', () => {
const onChange = jest.fn(); const onChange = jest.fn();
const setUp = (selected: VisitsFilter = {}, isOrphanVisits = true, botsSupported = true) => ({ const setUp = (selected: VisitsFilter = {}, isOrphanVisits = true, botsSupported = true) => renderWithEvents(
user: userEvent.setup(),
...render(
<VisitsFilterDropdown <VisitsFilterDropdown
isOrphanVisits={isOrphanVisits} isOrphanVisits={isOrphanVisits}
botsSupported={botsSupported} botsSupported={botsSupported}
selected={selected} selected={selected}
onChange={onChange} onChange={onChange}
/>, />,
), );
});
beforeEach(jest.clearAllMocks); beforeEach(jest.clearAllMocks);