Merge pull request #683 from acelaya-forks/feature/testing-lib

Feature/testing lib
This commit is contained in:
Alejandro Celaya 2022-07-09 23:18:49 +02:00 committed by GitHub
commit 3ac148f7cd
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
57 changed files with 426 additions and 567 deletions

View file

@ -1,5 +1,6 @@
import { ReactElement } from 'react';
import { render } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
export const setUpCanvas = (element: ReactElement) => {
const result = render(element);
@ -8,3 +9,8 @@ export const setUpCanvas = (element: ReactElement) => {
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 userEvent from '@testing-library/user-event';
import { screen } from '@testing-library/react';
import { AppUpdateBanner } from '../../src/common/AppUpdateBanner';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<AppUpdateBanner />', () => {
const toggle = jest.fn();
const forceUpdate = jest.fn();
const setUp = () => ({
user: userEvent.setup(),
...render(<AppUpdateBanner isOpen toggle={toggle} forceUpdate={forceUpdate} />),
});
const setUp = () => renderWithEvents(<AppUpdateBanner isOpen toggle={toggle} forceUpdate={forceUpdate} />);
afterEach(jest.clearAllMocks);

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,26 +1,25 @@
import { shallow, ShallowWrapper } from 'enzyme';
import { ReactElement } from 'react';
import { screen } from '@testing-library/react';
import { FC } from 'react';
import { Mock } from 'ts-mockery';
import { useNavigate } from 'react-router-dom';
import { MemoryRouter, useNavigate } from 'react-router-dom';
import { ShortUrlsList as createShortUrlsList } from '../../src/short-urls/ShortUrlsList';
import { ShortUrlsOrderableFields, ShortUrl, ShortUrlsOrder } from '../../src/short-urls/data';
import { ShortUrl, ShortUrlsOrder } from '../../src/short-urls/data';
import { MercureBoundProps } from '../../src/mercure/helpers/boundToMercureHub';
import { ShortUrlsList as ShortUrlsListModel } from '../../src/short-urls/reducers/shortUrlsList';
import { Paginator } from '../../src/short-urls/Paginator';
import { ReachableServer } from '../../src/servers/data';
import { Settings } from '../../src/settings/reducers/settings';
import { ShortUrlsTableProps } from '../../src/short-urls/ShortUrlsTable';
import { renderWithEvents } from '../__mocks__/setUpTest';
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useNavigate: jest.fn().mockReturnValue(jest.fn()),
useParams: jest.fn().mockReturnValue({}),
useLocation: jest.fn().mockReturnValue({ search: '?tags=test%20tag&search=example.com' }),
}));
describe('<ShortUrlsList />', () => {
let wrapper: ShallowWrapper;
const ShortUrlsTable = () => null;
const ShortUrlsFilteringBar = () => null;
const ShortUrlsTable: FC<ShortUrlsTableProps> = ({ onTagClick }) => <span onClick={() => onTagClick?.('foo')}>ShortUrlsTable</span>;
const ShortUrlsFilteringBar = () => <span>ShortUrlsFilteringBar</span>;
const listShortUrlsMock = jest.fn();
const navigate = jest.fn();
const shortUrlsList = Mock.of<ShortUrlsListModel>({
@ -33,85 +32,62 @@ describe('<ShortUrlsList />', () => {
tags: ['test tag'],
}),
],
pagination: {},
pagination: { pagesCount: 3 },
},
});
const ShortUrlsList = createShortUrlsList(ShortUrlsTable, ShortUrlsFilteringBar);
const createWrapper = (defaultOrdering: ShortUrlsOrder = {}) => shallow(
<ShortUrlsList
{...Mock.of<MercureBoundProps>({ mercureInfo: { loading: true } })}
listShortUrls={listShortUrlsMock}
shortUrlsList={shortUrlsList}
selectedServer={Mock.of<ReachableServer>({ id: '1' })}
settings={Mock.of<Settings>({ shortUrlsList: { defaultOrdering } })}
/>,
).dive(); // Dive is needed as this component is wrapped in a HOC
const setUp = (defaultOrdering: ShortUrlsOrder = {}) => renderWithEvents(
<MemoryRouter>
<ShortUrlsList
{...Mock.of<MercureBoundProps>({ mercureInfo: { loading: true } })}
listShortUrls={listShortUrlsMock}
shortUrlsList={shortUrlsList}
selectedServer={Mock.of<ReachableServer>({ id: '1' })}
settings={Mock.of<Settings>({ shortUrlsList: { defaultOrdering } })}
/>
</MemoryRouter>,
);
beforeEach(() => {
(useNavigate as any).mockReturnValue(navigate);
wrapper = createWrapper();
});
afterEach(jest.clearAllMocks);
afterEach(() => wrapper?.unmount());
it('wraps expected components', () => {
expect(wrapper.find(ShortUrlsTable)).toHaveLength(1);
expect(wrapper.find(Paginator)).toHaveLength(1);
expect(wrapper.find(ShortUrlsFilteringBar)).toHaveLength(1);
setUp();
expect(screen.getByText('ShortUrlsTable')).toBeInTheDocument();
expect(screen.getByText('ShortUrlsFilteringBar')).toBeInTheDocument();
});
it('passes current query to paginator', () => {
expect(wrapper.find(Paginator).prop('currentQueryString')).toEqual('?tags=test%20tag&search=example.com');
setUp();
const links = screen.getAllByRole('link');
expect(links.length > 0).toEqual(true);
links.forEach(
(link) => expect(link).toHaveAttribute('href', expect.stringContaining('?tags=test%20tag&search=example.com')),
);
});
it('gets list refreshed every time a tag is clicked', () => {
wrapper.find(ShortUrlsTable).simulate('tagClick', 'foo');
wrapper.find(ShortUrlsTable).simulate('tagClick', 'bar');
wrapper.find(ShortUrlsTable).simulate('tagClick', 'baz');
it('gets list refreshed every time a tag is clicked', async () => {
const { user } = setUp();
expect(navigate).toHaveBeenCalledTimes(3);
expect(navigate).toHaveBeenNthCalledWith(1, expect.stringContaining(`tags=${encodeURIComponent('test tag,foo')}`));
expect(navigate).toHaveBeenNthCalledWith(2, expect.stringContaining(`tags=${encodeURIComponent('test tag,bar')}`));
expect(navigate).toHaveBeenNthCalledWith(3, expect.stringContaining(`tags=${encodeURIComponent('test tag,baz')}`));
});
it('invokes order icon rendering', () => {
const renderIcon = (field: ShortUrlsOrderableFields) =>
(wrapper.find(ShortUrlsTable).prop('renderOrderIcon') as (field: ShortUrlsOrderableFields) => ReactElement)(field);
expect(renderIcon('visits').props.currentOrder).toEqual({});
(wrapper.find(ShortUrlsFilteringBar).prop('handleOrderBy') as Function)('visits');
expect(renderIcon('visits').props.currentOrder).toEqual({ field: 'visits' });
(wrapper.find(ShortUrlsFilteringBar).prop('handleOrderBy') as Function)('visits', 'ASC');
expect(renderIcon('visits').props.currentOrder).toEqual({ field: 'visits', dir: 'ASC' });
});
it('handles order through table', () => {
const orderByColumn: (field: ShortUrlsOrderableFields) => Function = wrapper.find(ShortUrlsTable).prop('orderByColumn');
expect(wrapper.find(ShortUrlsFilteringBar).prop('order')).toEqual({});
orderByColumn('visits')();
expect(wrapper.find(ShortUrlsFilteringBar).prop('order')).toEqual({ field: 'visits', dir: 'ASC' });
orderByColumn('title')();
expect(wrapper.find(ShortUrlsFilteringBar).prop('order')).toEqual({ field: 'title', dir: 'ASC' });
orderByColumn('shortCode')();
expect(wrapper.find(ShortUrlsFilteringBar).prop('order')).toEqual({ field: 'shortCode', dir: 'ASC' });
expect(navigate).not.toHaveBeenCalled();
await user.click(screen.getByText('ShortUrlsTable'));
expect(navigate).toHaveBeenCalledWith(expect.stringContaining(`tags=${encodeURIComponent('test tag,foo')}`));
});
it.each([
[Mock.of<ShortUrlsOrder>({ field: 'visits', dir: 'ASC' }), 'visits', 'ASC'],
[Mock.of<ShortUrlsOrder>({ field: 'title', dir: 'DESC' }), 'title', 'DESC'],
[Mock.of<ShortUrlsOrder>(), undefined, undefined],
])('has expected initial ordering', (initialOrderBy, field, dir) => {
const wrapper = createWrapper(initialOrderBy);
expect(wrapper.find(ShortUrlsFilteringBar).prop('order')).toEqual({ field, dir });
])('has expected initial ordering based on settings', (initialOrderBy, field, dir) => {
setUp(initialOrderBy);
expect(listShortUrlsMock).toHaveBeenCalledWith(expect.objectContaining({
orderBy: { field, dir },
}));
});
});

View file

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

View file

@ -1,11 +1,10 @@
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { screen } from '@testing-library/react';
import { UseExistingIfFoundInfoIcon } from '../../src/short-urls/UseExistingIfFoundInfoIcon';
import { renderWithEvents } from '../__mocks__/setUpTest';
describe('<UseExistingIfFoundInfoIcon />', () => {
it('shows modal when icon is clicked', async () => {
const user = userEvent.setup();
render(<UseExistingIfFoundInfoIcon />);
const { user } = renderWithEvents(<UseExistingIfFoundInfoIcon />);
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
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 userEvent from '@testing-library/user-event';
import { screen } from '@testing-library/react';
import { Mock } from 'ts-mockery';
import { CreateShortUrlResult as createResult } from '../../../src/short-urls/helpers/CreateShortUrlResult';
import { ShortUrl } from '../../../src/short-urls/data';
import { TimeoutToggle } from '../../../src/utils/helpers/hooks';
import { renderWithEvents } from '../../__mocks__/setUpTest';
describe('<CreateShortUrlResult />', () => {
const copyToClipboard = jest.fn();
const useTimeoutToggle = jest.fn(() => [false, copyToClipboard]) as TimeoutToggle;
const CreateShortUrlResult = createResult(useTimeoutToggle);
const setUp = (result: ShortUrl | null = null, error = false) => ({
user: userEvent.setup(),
...render(<CreateShortUrlResult resetCreateShortUrl={() => {}} result={result} error={error} saving={false} />),
});
const setUp = (result: ShortUrl | null = null, error = false) => renderWithEvents(
<CreateShortUrlResult resetCreateShortUrl={() => {}} result={result} error={error} saving={false} />,
);
afterEach(jest.clearAllMocks);

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,64 +1,56 @@
import { shallow, ShallowWrapper } from 'enzyme';
import { Button, Modal, ModalBody, ModalFooter } from 'reactstrap';
import { screen } from '@testing-library/react';
import { DeleteTagConfirmModal } from '../../../src/tags/helpers/DeleteTagConfirmModal';
import { TagDeletion } from '../../../src/tags/reducers/tagDelete';
import { renderWithEvents } from '../../__mocks__/setUpTest';
describe('<DeleteTagConfirmModal />', () => {
let wrapper: ShallowWrapper;
const tag = 'nodejs';
const deleteTag = jest.fn();
const tagDeleted = jest.fn();
const createWrapper = (tagDelete: TagDeletion) => {
wrapper = shallow(
<DeleteTagConfirmModal
tag={tag}
toggle={() => ''}
isOpen
deleteTag={deleteTag}
tagDeleted={tagDeleted}
tagDelete={tagDelete}
/>,
);
const setUp = (tagDelete: TagDeletion) => renderWithEvents(
<DeleteTagConfirmModal
tag={tag}
toggle={() => ''}
isOpen
deleteTag={deleteTag}
tagDeleted={tagDeleted}
tagDelete={tagDelete}
/>,
);
return wrapper;
};
afterEach(() => wrapper?.unmount());
afterEach(jest.resetAllMocks);
it('asks confirmation for provided tag to be deleted', () => {
wrapper = createWrapper({ error: false, deleting: false });
const body = wrapper.find(ModalBody);
const footer = wrapper.find(ModalFooter);
const delBtn = footer.find(Button).last();
setUp({ error: false, deleting: false });
expect(body.html()).toContain(`Are you sure you want to delete tag <b>${tag}</b>?`);
expect(delBtn.prop('disabled')).toEqual(false);
expect(delBtn.html()).toContain('>Delete tag<');
const delBtn = screen.getByRole('button', { name: 'Delete tag' });
expect(screen.getByText(/^Are you sure you want to delete tag/)).toBeInTheDocument();
expect(screen.queryByText('Something went wrong while deleting the tag :(')).not.toBeInTheDocument();
expect(delBtn).toBeInTheDocument();
expect(delBtn).not.toHaveClass('disabled');
expect(delBtn).not.toHaveAttribute('disabled');
});
it('shows error message when deletion failed', () => {
wrapper = createWrapper({ error: true, deleting: false });
const body = wrapper.find(ModalBody);
expect(body.html()).toContain('Something went wrong while deleting the tag :(');
setUp({ error: true, deleting: false });
expect(screen.getByText('Something went wrong while deleting the tag :(')).toBeInTheDocument();
});
it('shows loading status while deleting', () => {
wrapper = createWrapper({ error: false, deleting: true });
const footer = wrapper.find(ModalFooter);
const delBtn = footer.find(Button).last();
setUp({ error: false, deleting: true });
expect(delBtn.prop('disabled')).toEqual(true);
expect(delBtn.html()).toContain('>Deleting tag...<');
const delBtn = screen.getByRole('button', { name: 'Deleting tag...' });
expect(delBtn).toBeInTheDocument();
expect(delBtn).toHaveClass('disabled');
expect(delBtn).toHaveAttribute('disabled');
});
it('deletes tag modal when btn is clicked', async () => {
wrapper = createWrapper({ error: false, deleting: true });
const footer = wrapper.find(ModalFooter);
const delBtn = footer.find(Button).last();
it('hides tag modal when btn is clicked', async () => {
const { user } = setUp({ error: false, deleting: false });
await delBtn.simulate('click');
await user.click(screen.getByRole('button', { name: 'Delete tag' }));
expect(deleteTag).toHaveBeenCalledTimes(1);
expect(deleteTag).toHaveBeenCalledWith(tag);
@ -66,11 +58,11 @@ describe('<DeleteTagConfirmModal />', () => {
expect(tagDeleted).toHaveBeenCalledWith(tag);
});
it('does no further actions when modal is closed without deleting tag', () => {
wrapper = createWrapper({ error: false, deleting: false });
const modal = wrapper.find(Modal);
it('does no further actions when modal is closed without deleting tag', async () => {
const { user } = setUp({ error: false, deleting: false });
await user.click(screen.getByLabelText('Close'));
modal.simulate('closed');
expect(deleteTag).not.toHaveBeenCalled();
expect(tagDeleted).not.toHaveBeenCalled();
});

View file

@ -1,10 +1,10 @@
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { screen } from '@testing-library/react';
import { Mock } from 'ts-mockery';
import { ReactNode } from 'react';
import { ColorGenerator } from '../../../src/utils/services/ColorGenerator';
import { MAIN_COLOR } from '../../../src/utils/theme';
import { Tag } from '../../../src/tags/helpers/Tag';
import { renderWithEvents } from '../../__mocks__/setUpTest';
const hexToRgb = (hex: string) => {
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 getColorForKey = jest.fn(() => MAIN_COLOR);
const colorGenerator = Mock.of<ColorGenerator>({ getColorForKey, isColorLightForKey });
const setUp = (text: string, clearable?: boolean, children?: ReactNode) => ({
user: userEvent.setup(),
...render(
<Tag text={text} clearable={clearable} colorGenerator={colorGenerator} onClick={onClick} onClose={onClose}>
{children}
</Tag>,
),
});
const setUp = (text: string, clearable?: boolean, children?: ReactNode) => renderWithEvents(
<Tag text={text} clearable={clearable} colorGenerator={colorGenerator} onClick={onClick} onClose={onClose}>
{children}
</Tag>,
);
afterEach(jest.clearAllMocks);

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,5 +1,5 @@
import { HorizontalBarChart, HorizontalBarChartProps } from '../../../src/visits/charts/HorizontalBarChart';
import { setUpCanvas } from '../../__mocks__/setUpCanvas';
import { setUpCanvas } from '../../__mocks__/setUpTest';
describe('<HorizontalBarChart />', () => {
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 { LineChartCard } from '../../../src/visits/charts/LineChartCard';
import { NormalizedVisit } from '../../../src/visits/types';
import { setUpCanvas } from '../../__mocks__/setUpCanvas';
import { setUpCanvas } from '../../__mocks__/setUpTest';
describe('<LineChartCard />', () => {
const setUp = (visits: NormalizedVisit[] = [], highlightedVisits: NormalizedVisit[] = []) => ({

View file

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

View file

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