Merge pull request #658 from acelaya-forks/feature/rtl

Migrated CreateServer test to react testing library
This commit is contained in:
Alejandro Celaya 2022-05-29 16:13:17 +02:00 committed by GitHub
commit 876018390d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
14 changed files with 106 additions and 100 deletions

View file

@ -4,7 +4,7 @@ import { Button } from 'reactstrap';
import { useNavigate } from 'react-router-dom';
import { Result } from '../utils/Result';
import { NoMenuLayout } from '../common/NoMenuLayout';
import { StateFlagTimeout, useGoBack, useToggle } from '../utils/helpers/hooks';
import { TimeoutToggle, useGoBack, useToggle } from '../utils/helpers/hooks';
import { ServerForm } from './helpers/ServerForm';
import { ImportServersBtnProps } from './helpers/ImportServersBtn';
import { ServerData, ServersMap, ServerWithId } from './data';
@ -26,14 +26,14 @@ const ImportResult = ({ type }: { type: 'error' | 'success' }) => (
</div>
);
export const CreateServer = (ImportServersBtn: FC<ImportServersBtnProps>, useStateFlagTimeout: StateFlagTimeout) => (
export const CreateServer = (ImportServersBtn: FC<ImportServersBtnProps>, useTimeoutToggle: TimeoutToggle) => (
{ servers, createServer }: CreateServerProps,
) => {
const navigate = useNavigate();
const goBack = useGoBack();
const hasServers = !!Object.keys(servers).length;
const [serversImported, setServersImported] = useStateFlagTimeout(false, SHOW_IMPORT_MSG_TIME);
const [errorImporting, setErrorImporting] = useStateFlagTimeout(false, SHOW_IMPORT_MSG_TIME);
const [serversImported, setServersImported] = useTimeoutToggle(false, SHOW_IMPORT_MSG_TIME);
const [errorImporting, setErrorImporting] = useTimeoutToggle(false, SHOW_IMPORT_MSG_TIME);
const [isConfirmModalOpen, toggleConfirmModal] = useToggle();
const [serverData, setServerData] = useState<ServerData | undefined>();
const save = () => {

View file

@ -7,7 +7,7 @@ import { NoMenuLayout } from '../common/NoMenuLayout';
import { SimpleCard } from '../utils/SimpleCard';
import { SearchField } from '../utils/SearchField';
import { Result } from '../utils/Result';
import { StateFlagTimeout } from '../utils/helpers/hooks';
import { TimeoutToggle } from '../utils/helpers/hooks';
import { ImportServersBtnProps } from './helpers/ImportServersBtn';
import { ServersMap } from './data';
import { ManageServersRowProps } from './ManageServersRow';
@ -22,7 +22,7 @@ const SHOW_IMPORT_MSG_TIME = 4000;
export const ManageServers = (
serversExporter: ServersExporter,
ImportServersBtn: FC<ImportServersBtnProps>,
useStateFlagTimeout: StateFlagTimeout,
useTimeoutToggle: TimeoutToggle,
ManageServersRow: FC<ManageServersRowProps>,
): FC<ManageServersProps> => ({ servers }) => {
const allServers = Object.values(servers);
@ -31,7 +31,7 @@ export const ManageServers = (
allServers.filter(({ name, url }) => `${name} ${url}`.match(searchTerm)),
);
const hasAutoConnect = serversList.some(({ autoConnect }) => !!autoConnect);
const [errorImporting, setErrorImporting] = useStateFlagTimeout(false, SHOW_IMPORT_MSG_TIME);
const [errorImporting, setErrorImporting] = useTimeoutToggle(false, SHOW_IMPORT_MSG_TIME);
useEffect(() => {
setServersList(Object.values(servers));

View file

@ -25,7 +25,7 @@ const provideServices = (bottle: Bottle, connect: ConnectDecorator) => {
ManageServers,
'ServersExporter',
'ImportServersBtn',
'useStateFlagTimeout',
'useTimeoutToggle',
'ManageServersRow',
);
bottle.decorator('ManageServers', withoutSelectedServer);
@ -36,7 +36,7 @@ const provideServices = (bottle: Bottle, connect: ConnectDecorator) => {
bottle.serviceFactory('ManageServersRowDropdown', ManageServersRowDropdown, 'DeleteServerModal');
bottle.decorator('ManageServersRowDropdown', connect(null, ['setAutoConnect']));
bottle.serviceFactory('CreateServer', CreateServer, 'ImportServersBtn', 'useStateFlagTimeout');
bottle.serviceFactory('CreateServer', CreateServer, 'ImportServersBtn', 'useTimeoutToggle');
bottle.decorator('CreateServer', withoutSelectedServer);
bottle.decorator('CreateServer', connect(['selectedServer', 'servers'], ['createServer', 'resetSelectedServer']));

View file

@ -6,7 +6,7 @@ import { useEffect } from 'react';
import CopyToClipboard from 'react-copy-to-clipboard';
import { Tooltip } from 'reactstrap';
import { ShortUrlCreation } from '../reducers/shortUrlCreation';
import { StateFlagTimeout } from '../../utils/helpers/hooks';
import { TimeoutToggle } from '../../utils/helpers/hooks';
import { Result } from '../../utils/Result';
import './CreateShortUrlResult.scss';
import { ShlinkApiError } from '../../api/ShlinkApiError';
@ -16,10 +16,10 @@ export interface CreateShortUrlResultProps extends ShortUrlCreation {
canBeClosed?: boolean;
}
export const CreateShortUrlResult = (useStateFlagTimeout: StateFlagTimeout) => (
export const CreateShortUrlResult = (useTimeoutToggle: TimeoutToggle) => (
{ error, errorData, result, resetCreateShortUrl, canBeClosed = false }: CreateShortUrlResultProps,
) => {
const [showCopyTooltip, setShowCopyTooltip] = useStateFlagTimeout();
const [showCopyTooltip, setShowCopyTooltip] = useTimeoutToggle();
useEffect(() => {
resetCreateShortUrl();

View file

@ -2,7 +2,7 @@ import { FC, useEffect, useRef } from 'react';
import { isEmpty } from 'ramda';
import { ExternalLink } from 'react-external-link';
import { ColorGenerator } from '../../utils/services/ColorGenerator';
import { StateFlagTimeout } from '../../utils/helpers/hooks';
import { TimeoutToggle } from '../../utils/helpers/hooks';
import { Tag } from '../../tags/helpers/Tag';
import { SelectedServer } from '../../servers/data';
import { CopyToClipboardIcon } from '../../utils/CopyToClipboardIcon';
@ -21,10 +21,10 @@ export interface ShortUrlsRowProps {
export const ShortUrlsRow = (
ShortUrlsRowMenu: FC<ShortUrlsRowMenuProps>,
colorGenerator: ColorGenerator,
useStateFlagTimeout: StateFlagTimeout,
useTimeoutToggle: TimeoutToggle,
) => ({ shortUrl, selectedServer, onTagClick }: ShortUrlsRowProps) => {
const [copiedToClipboard, setCopiedToClipboard] = useStateFlagTimeout();
const [active, setActive] = useStateFlagTimeout(false, 500);
const [copiedToClipboard, setCopiedToClipboard] = useTimeoutToggle();
const [active, setActive] = useTimeoutToggle(false, 500);
const isFirstRun = useRef(true);
const renderTags = (tags: string[]) => {

View file

@ -27,9 +27,9 @@ const provideServices = (bottle: Bottle, connect: ConnectDecorator) => {
));
bottle.serviceFactory('ShortUrlsTable', ShortUrlsTable, 'ShortUrlsRow');
bottle.serviceFactory('ShortUrlsRow', ShortUrlsRow, 'ShortUrlsRowMenu', 'ColorGenerator', 'useStateFlagTimeout');
bottle.serviceFactory('ShortUrlsRow', ShortUrlsRow, 'ShortUrlsRowMenu', 'ColorGenerator', 'useTimeoutToggle');
bottle.serviceFactory('ShortUrlsRowMenu', ShortUrlsRowMenu, 'DeleteShortUrlModal', 'QrCodeModal');
bottle.serviceFactory('CreateShortUrlResult', CreateShortUrlResult, 'useStateFlagTimeout');
bottle.serviceFactory('CreateShortUrlResult', CreateShortUrlResult, 'useTimeoutToggle');
bottle.serviceFactory('ShortUrlForm', ShortUrlForm, 'TagsSelector', 'DomainSelector');
bottle.serviceFactory('CreateShortUrl', CreateShortUrl, 'ShortUrlForm', 'CreateShortUrlResult');

View file

@ -1,6 +1,7 @@
import { FC, PropsWithChildren } from 'react';
import { InputType } from 'reactstrap/types/lib/Input';
import { LabeledFormGroup } from './LabeledFormGroup';
import { useDomId } from '../helpers/hooks';
export type InputFormGroupProps = PropsWithChildren<{
value: string;
@ -14,9 +15,13 @@ export type InputFormGroupProps = PropsWithChildren<{
export const InputFormGroup: FC<InputFormGroupProps> = (
{ children, value, onChange, type, required, placeholder, className, labelClassName },
) => (
<LabeledFormGroup label={<>{children}:</>} className={className ?? ''} labelClassName={labelClassName}>
) => {
const id = useDomId();
return (
<LabeledFormGroup label={<>{children}:</>} className={className ?? ''} labelClassName={labelClassName} id={id}>
<input
id={id}
className="form-control"
type={type ?? 'text'}
value={value}
@ -25,4 +30,5 @@ export const InputFormGroup: FC<InputFormGroupProps> = (
onChange={(e) => onChange(e.target.value)}
/>
</LabeledFormGroup>
);
);
};

View file

@ -5,14 +5,15 @@ type LabeledFormGroupProps = PropsWithChildren<{
noMargin?: boolean;
className?: string;
labelClassName?: string;
id?: string;
}>;
/* eslint-disable jsx-a11y/label-has-associated-control */
export const LabeledFormGroup: FC<LabeledFormGroupProps> = (
{ children, label, className = '', labelClassName = '', noMargin = false },
{ children, label, className = '', labelClassName = '', noMargin = false, id },
) => (
<div className={`${className} ${noMargin ? '' : 'mb-3'}`}>
<label className={`form-label ${labelClassName}`}>{label}</label>
<label className={`form-label ${labelClassName}`} htmlFor={id}>{label}</label>
{children}
</div>
);

View file

@ -6,12 +6,12 @@ import { parseQuery, stringifyQuery } from './query';
const DEFAULT_DELAY = 2000;
export type StateFlagTimeout = (initialValue?: boolean, delay?: number) => [ boolean, () => void ];
export type TimeoutToggle = (initialValue?: boolean, delay?: number) => [boolean, () => void];
export const useStateFlagTimeout = (
export const useTimeoutToggle = (
setTimeout: (callback: Function, timeout: number) => number,
clearTimeout: (timer: number) => void,
): StateFlagTimeout => (initialValue = false, delay = DEFAULT_DELAY) => {
): TimeoutToggle => (initialValue = false, delay = DEFAULT_DELAY) => {
const [flag, setFlag] = useState<boolean>(initialValue);
const timeout = useRef<number | undefined>(undefined);
const callback = () => {
@ -31,7 +31,6 @@ type ToggleResult = [ boolean, () => void, () => void, () => void ];
export const useToggle = (initialValue = false): ToggleResult => {
const [flag, setFlag] = useState<boolean>(initialValue);
return [flag, () => setFlag(!flag), () => setFlag(true), () => setFlag(false)];
};
@ -80,7 +79,6 @@ export const useEffectExceptFirstTime = (callback: EffectCallback, deps: Depende
export const useGoBack = () => {
const navigate = useNavigate();
return () => navigate(-1);
};

View file

@ -1,5 +1,5 @@
import Bottle from 'bottlejs';
import { useStateFlagTimeout } from '../helpers/hooks';
import { useTimeoutToggle } from '../helpers/hooks';
import { LocalStorage } from './LocalStorage';
import { ColorGenerator } from './ColorGenerator';
import { csvToJson, jsonToCsv } from '../helpers/csvjson';
@ -14,7 +14,7 @@ const provideServices = (bottle: Bottle) => {
bottle.constant('setTimeout', global.setTimeout);
bottle.constant('clearTimeout', global.clearTimeout);
bottle.serviceFactory('useStateFlagTimeout', useStateFlagTimeout, 'setTimeout', 'clearTimeout');
bottle.serviceFactory('useTimeoutToggle', useTimeoutToggle, 'setTimeout', 'clearTimeout');
};
export default provideServices;

View file

@ -1,83 +1,84 @@
import { shallow, ShallowWrapper } from 'enzyme';
import userEvent from '@testing-library/user-event';
import { fireEvent, render, 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 { ServerForm } from '../../src/servers/helpers/ServerForm';
import { ServerWithId } from '../../src/servers/data';
import { DuplicatedServersModal } from '../../src/servers/helpers/DuplicatedServersModal';
jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom'), useNavigate: jest.fn() }));
describe('<CreateServer />', () => {
let wrapper: ShallowWrapper;
const ImportServersBtn = () => null;
const createServerMock = jest.fn();
const navigate = jest.fn();
const servers = { foo: Mock.all<ServerWithId>() };
const createWrapper = (serversImported = false, importFailed = false) => {
const servers = { foo: Mock.of<ServerWithId>({ url: 'https://existing_url.com', apiKey: 'existing_api_key' }) };
const setUp = (serversImported = false, importFailed = false) => {
(useNavigate as any).mockReturnValue(navigate);
const useStateFlagTimeout = jest.fn()
.mockReturnValueOnce([serversImported, () => ''])
.mockReturnValueOnce([importFailed, () => ''])
.mockReturnValue([]);
const CreateServer = createCreateServer(ImportServersBtn, useStateFlagTimeout);
let callCount = 0;
const useTimeoutToggle = jest.fn().mockImplementation(() => {
const result = [callCount % 2 === 0 ? serversImported : importFailed, () => null];
callCount += 1;
return result;
});
const CreateServer = createCreateServer(() => <>ImportServersBtn</>, useTimeoutToggle);
wrapper = shallow(<CreateServer createServer={createServerMock} servers={servers} />);
return wrapper;
return {
user: userEvent.setup(),
...render(<CreateServer createServer={createServerMock} servers={servers} />),
};
};
beforeEach(jest.clearAllMocks);
afterEach(() => wrapper?.unmount());
it('renders components', () => {
const wrapper = createWrapper();
expect(wrapper.find(ServerForm)).toHaveLength(1);
expect(wrapper.find('ImportResult')).toHaveLength(0);
});
it('shows success message when imported is true', () => {
const wrapper = createWrapper(true);
const result = wrapper.find('ImportResult');
setUp(true);
expect(result).toHaveLength(1);
expect(result.prop('type')).toEqual('success');
expect(screen.getByText('Servers properly imported. You can now select one from the list :)')).toBeInTheDocument();
expect(
screen.queryByText('The servers could not be imported. Make sure the format is correct.'),
).not.toBeInTheDocument();
});
it('shows error message when import failed', () => {
const wrapper = createWrapper(false, true);
const result = wrapper.find('ImportResult');
setUp(false, true);
expect(result).toHaveLength(1);
expect(result.prop('type')).toEqual('error');
expect(
screen.queryByText('Servers properly imported. You can now select one from the list :)'),
).not.toBeInTheDocument();
expect(screen.getByText('The servers could not be imported. Make sure the format is correct.')).toBeInTheDocument();
});
it('creates server data when form is submitted', () => {
const wrapper = createWrapper();
const form = wrapper.find(ServerForm);
it('creates server data when form is submitted', async () => {
const { user } = setUp();
expect(wrapper.find(DuplicatedServersModal).prop('duplicatedServers')).toEqual([]);
form.simulate('submit', {});
expect(wrapper.find(DuplicatedServersModal).prop('duplicatedServers')).toEqual([{}]);
expect(createServerMock).not.toHaveBeenCalled();
await user.type(screen.getByLabelText(/^Name/), 'the_name');
await user.type(screen.getByLabelText(/^URL/), 'https://the_url.com');
await user.type(screen.getByLabelText(/^API key/), 'the_api_key');
fireEvent.submit(screen.getByRole('form'));
expect(createServerMock).toHaveBeenCalledWith(expect.objectContaining({
name: 'the_name',
url: 'https://the_url.com',
apiKey: 'the_api_key',
}));
expect(navigate).toHaveBeenCalledWith(expect.stringMatching(/^\/server\//));
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
it('saves server and redirects on modal save', () => {
const wrapper = createWrapper();
it('displays dialog when trying to create a duplicated server', async () => {
const { user } = setUp();
wrapper.find(ServerForm).simulate('submit', {});
wrapper.find(DuplicatedServersModal).simulate('save');
await user.type(screen.getByLabelText(/^Name/), 'the_name');
await user.type(screen.getByLabelText(/^URL/), 'https://existing_url.com');
await user.type(screen.getByLabelText(/^API key/), 'existing_api_key');
fireEvent.submit(screen.getByRole('form'));
expect(createServerMock).toHaveBeenCalledTimes(1);
expect(navigate).toHaveBeenCalledTimes(1);
});
it('goes back on modal discard', () => {
const wrapper = createWrapper();
wrapper.find(DuplicatedServersModal).simulate('discard');
await waitFor(() => expect(screen.getByRole('dialog')).toBeInTheDocument());
await user.click(screen.getByRole('button', { name: 'Discard' }));
expect(createServerMock).not.toHaveBeenCalled();
expect(navigate).toHaveBeenCalledWith(-1);
});
});

View file

@ -12,8 +12,8 @@ describe('<ManageServers />', () => {
const serversExporter = Mock.of<ServersExporter>({ exportServers });
const ImportServersBtn = () => null;
const ManageServersRow = () => null;
const useStateFlagTimeout = jest.fn().mockReturnValue([false, jest.fn()]);
const ManageServers = createManageServers(serversExporter, ImportServersBtn, useStateFlagTimeout, ManageServersRow);
const useTimeoutToggle = jest.fn().mockReturnValue([false, jest.fn()]);
const ManageServers = createManageServers(serversExporter, ImportServersBtn, useTimeoutToggle, ManageServersRow);
let wrapper: ShallowWrapper;
const createServerMock = (value: string, autoConnect = false) => Mock.of<ServerWithId>(
{ id: value, name: value, url: value, autoConnect },
@ -82,7 +82,7 @@ describe('<ManageServers />', () => {
});
it('shows an error message if an error occurs while importing servers', () => {
useStateFlagTimeout.mockReturnValue([true, jest.fn()]);
useTimeoutToggle.mockReturnValue([true, jest.fn()]);
const wrapper = createWrapper({ foo: createServerMock('foo') });
const result = wrapper.find(Result);

View file

@ -4,14 +4,14 @@ import { Tooltip } from 'reactstrap';
import { Mock } from 'ts-mockery';
import { CreateShortUrlResult as createResult } from '../../../src/short-urls/helpers/CreateShortUrlResult';
import { ShortUrl } from '../../../src/short-urls/data';
import { StateFlagTimeout } from '../../../src/utils/helpers/hooks';
import { TimeoutToggle } from '../../../src/utils/helpers/hooks';
import { Result } from '../../../src/utils/Result';
describe('<CreateShortUrlResult />', () => {
let wrapper: ShallowWrapper;
const copyToClipboard = jest.fn();
const useStateFlagTimeout = jest.fn(() => [false, copyToClipboard]) as StateFlagTimeout;
const CreateShortUrlResult = createResult(useStateFlagTimeout);
const useTimeoutToggle = jest.fn(() => [false, copyToClipboard]) as TimeoutToggle;
const CreateShortUrlResult = createResult(useTimeoutToggle);
const createWrapper = (result: ShortUrl | null = null, error = false) => {
wrapper = shallow(
<CreateShortUrlResult resetCreateShortUrl={() => {}} result={result} error={error} saving={false} />,

View file

@ -6,7 +6,7 @@ import { formatISO } from 'date-fns';
import { ShortUrlsRow as createShortUrlsRow } from '../../../src/short-urls/helpers/ShortUrlsRow';
import { Tag } from '../../../src/tags/helpers/Tag';
import { ColorGenerator } from '../../../src/utils/services/ColorGenerator';
import { StateFlagTimeout } from '../../../src/utils/helpers/hooks';
import { TimeoutToggle } from '../../../src/utils/helpers/hooks';
import { ShortUrl } from '../../../src/short-urls/data';
import { ReachableServer } from '../../../src/servers/data';
import { CopyToClipboardIcon } from '../../../src/utils/CopyToClipboardIcon';
@ -17,8 +17,8 @@ describe('<ShortUrlsRow />', () => {
let wrapper: ShallowWrapper;
const mockFunction = () => null;
const ShortUrlsRowMenu = mockFunction;
const stateFlagTimeout = jest.fn(() => true);
const useStateFlagTimeout = jest.fn(() => [false, stateFlagTimeout]) as StateFlagTimeout;
const timeoutToggle = jest.fn(() => true);
const useTimeoutToggle = jest.fn(() => [false, timeoutToggle]) as TimeoutToggle;
const colorGenerator = Mock.of<ColorGenerator>({
getColorForKey: jest.fn(),
setColorForKey: jest.fn(),
@ -38,7 +38,7 @@ describe('<ShortUrlsRow />', () => {
maxVisits: null,
},
};
const ShortUrlsRow = createShortUrlsRow(ShortUrlsRowMenu, colorGenerator, useStateFlagTimeout);
const ShortUrlsRow = createShortUrlsRow(ShortUrlsRowMenu, colorGenerator, useTimeoutToggle);
const createWrapper = (title?: string | null) => {
wrapper = shallow(
<ShortUrlsRow selectedServer={server} shortUrl={{ ...shortUrl, title }} onTagClick={mockFunction} />,
@ -129,8 +129,8 @@ describe('<ShortUrlsRow />', () => {
const menu = col.find(CopyToClipboardIcon);
expect(menu).toHaveLength(1);
expect(stateFlagTimeout).not.toHaveBeenCalled();
expect(timeoutToggle).not.toHaveBeenCalled();
menu.simulate('copy');
expect(stateFlagTimeout).toHaveBeenCalledTimes(1);
expect(timeoutToggle).toHaveBeenCalledTimes(1);
});
});