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

Feature/testing lib
This commit is contained in:
Alejandro Celaya
2022-07-07 19:06:01 +02:00
committed by GitHub
6 changed files with 78 additions and 130 deletions

View File

@@ -43,7 +43,7 @@ export const CreateShortUrlResult = (useTimeoutToggle: TimeoutToggle) => (
return ( return (
<Result type="success" className="mt-3"> <Result type="success" className="mt-3">
{canBeClosed && <FontAwesomeIcon icon={closeIcon} className="float-end pointer" onClick={resetCreateShortUrl} />} {canBeClosed && <FontAwesomeIcon icon={closeIcon} className="float-end pointer" onClick={resetCreateShortUrl} />}
<b>Great!</b> The short URL is <b>{shortUrl}</b> <span><b>Great!</b> The short URL is <b>{shortUrl}</b></span>
<CopyToClipboard text={shortUrl} onCopy={setShowCopyTooltip}> <CopyToClipboard text={shortUrl} onCopy={setShowCopyTooltip}>
<button <button

View File

@@ -1,56 +1,41 @@
import { shallow, ShallowWrapper } from 'enzyme'; import { render, screen } from '@testing-library/react';
import CopyToClipboard from 'react-copy-to-clipboard'; import userEvent from '@testing-library/user-event';
import { Tooltip } from 'reactstrap';
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 { Result } from '../../../src/utils/Result';
describe('<CreateShortUrlResult />', () => { describe('<CreateShortUrlResult />', () => {
let wrapper: ShallowWrapper;
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 createWrapper = (result: ShortUrl | null = null, error = false) => { const setUp = (result: ShortUrl | null = null, error = false) => ({
wrapper = shallow( user: userEvent.setup(),
<CreateShortUrlResult resetCreateShortUrl={() => {}} result={result} error={error} saving={false} />, ...render(<CreateShortUrlResult resetCreateShortUrl={() => {}} result={result} error={error} saving={false} />),
); });
return wrapper;
};
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);
afterEach(() => wrapper?.unmount());
it('renders an error when error is true', () => { it('renders an error when error is true', () => {
const wrapper = createWrapper(Mock.all<ShortUrl>(), true); setUp(Mock.all<ShortUrl>(), true);
const errorCard = wrapper.find(Result).filterWhere((result) => result.prop('type') === 'error'); expect(screen.getByText('An error occurred while creating the URL :(')).toBeInTheDocument();
expect(errorCard).toHaveLength(1);
expect(errorCard.html()).toContain('An error occurred while creating the URL :(');
}); });
it('renders nothing when no result is provided', () => { it('renders nothing when no result is provided', () => {
const wrapper = createWrapper(); const { container } = setUp();
expect(container.firstChild).toBeNull();
expect(wrapper.html()).toBeNull();
}); });
it('renders a result message when result is provided', () => { it('renders a result message when result is provided', () => {
const wrapper = createWrapper(Mock.of<ShortUrl>({ shortUrl: 'https://doma.in/abc123' })); setUp(Mock.of<ShortUrl>({ shortUrl: 'https://doma.in/abc123' }));
expect(screen.getByText(/The short URL is/)).toHaveTextContent('Great! The short URL is https://doma.in/abc123');
expect(wrapper.html()).toContain('<b>Great!</b> The short URL is <b>https://doma.in/abc123</b>');
expect(wrapper.find(CopyToClipboard)).toHaveLength(1);
expect(wrapper.find(Tooltip)).toHaveLength(1);
}); });
it('Invokes tooltip timeout when copy to clipboard button is clicked', () => { it('Invokes tooltip timeout when copy to clipboard button is clicked', async () => {
const wrapper = createWrapper(Mock.of<ShortUrl>({ shortUrl: 'https://doma.in/abc123' })); const { user } = setUp(Mock.of<ShortUrl>({ shortUrl: 'https://doma.in/abc123' }));
const copyBtn = wrapper.find(CopyToClipboard);
expect(copyToClipboard).not.toHaveBeenCalled(); expect(copyToClipboard).not.toHaveBeenCalled();
copyBtn.simulate('copy'); await user.click(screen.getByRole('button'));
expect(copyToClipboard).toHaveBeenCalledTimes(1); expect(copyToClipboard).toHaveBeenCalledTimes(1);
}); });
}); });

View File

@@ -1,51 +1,44 @@
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { shallow, ShallowWrapper } from 'enzyme'; import { render, screen, waitForElementToBeRemoved } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
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';
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useNavigate: jest.fn().mockReturnValue(jest.fn()),
useParams: jest.fn().mockReturnValue({}),
useLocation: jest.fn().mockReturnValue({}),
}));
describe('<ExportShortUrlsBtn />', () => { describe('<ExportShortUrlsBtn />', () => {
const listShortUrls = jest.fn(); const listShortUrls = jest.fn();
const buildShlinkApiClient = jest.fn().mockReturnValue({ listShortUrls }); const buildShlinkApiClient = jest.fn().mockReturnValue({ listShortUrls });
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);
let wrapper: ShallowWrapper; const setUp = (amount?: number, selectedServer?: SelectedServer) => ({
const createWrapper = (amount?: number, selectedServer?: SelectedServer) => { user: userEvent.setup(),
wrapper = shallow( ...render(
<ExportShortUrlsBtn selectedServer={selectedServer ?? Mock.all<SelectedServer>()} amount={amount} />, <MemoryRouter>
); <ExportShortUrlsBtn selectedServer={selectedServer ?? Mock.all<SelectedServer>()} amount={amount} />
</MemoryRouter>,
return wrapper; ),
}; });
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);
afterEach(() => wrapper?.unmount());
it.each([ it.each([
[undefined, 0], [undefined, '0'],
[1, 1], [1, '1'],
[4578, 4578], [4578, '4,578'],
])('renders expected amount', (amount, expectedAmount) => { ])('renders expected amount', (amount, expectedAmount) => {
const wrapper = createWrapper(amount); setUp(amount);
expect(screen.getByText(/Export/)).toHaveTextContent(`Export (${expectedAmount})`);
expect(wrapper.prop('amount')).toEqual(expectedAmount);
}); });
it.each([ it.each([
[null], [null],
[Mock.of<NotFoundServer>()], [Mock.of<NotFoundServer>()],
])('does nothing on click if selected server is not reachable', (selectedServer) => { ])('does nothing on click if selected server is not reachable', async (selectedServer) => {
const wrapper = createWrapper(0, selectedServer); const { user } = setUp(0, selectedServer);
wrapper.simulate('click'); await user.click(screen.getByRole('button'));
expect(listShortUrls).not.toHaveBeenCalled(); expect(listShortUrls).not.toHaveBeenCalled();
expect(exportShortUrls).not.toHaveBeenCalled(); expect(exportShortUrls).not.toHaveBeenCalled();
}); });
@@ -58,13 +51,13 @@ describe('<ExportShortUrlsBtn />', () => {
[41, 3], [41, 3],
[385, 20], [385, 20],
])('loads proper amount of pages based on the amount of results', async (amount, expectedPageLoads) => { ])('loads proper amount of pages based on the amount of results', async (amount, expectedPageLoads) => {
const wrapper = createWrapper(amount, Mock.of<ReachableServer>({ id: '123' }));
listShortUrls.mockResolvedValue({ data: [] }); listShortUrls.mockResolvedValue({ data: [] });
const { user } = setUp(amount, Mock.of<ReachableServer>({ id: '123' }));
await (wrapper.prop('onClick') as Function)(); await user.click(screen.getByRole('button'));
await waitForElementToBeRemoved(() => screen.getByText('Exporting...'));
expect(listShortUrls).toHaveBeenCalledTimes(expectedPageLoads); expect(listShortUrls).toHaveBeenCalledTimes(expectedPageLoads);
expect(exportShortUrls).toHaveBeenCalledTimes(1); expect(exportShortUrls).toHaveBeenCalled();
}); });
}); });

View File

@@ -1,43 +1,28 @@
import { shallow, ShallowWrapper } from 'enzyme'; import { render } from '@testing-library/react';
import { UncontrolledTooltip } from 'reactstrap';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { ShortUrlVisitsCount } from '../../../src/short-urls/helpers/ShortUrlVisitsCount'; import { ShortUrlVisitsCount } from '../../../src/short-urls/helpers/ShortUrlVisitsCount';
import { ShortUrl } from '../../../src/short-urls/data'; import { ShortUrl } from '../../../src/short-urls/data';
describe('<ShortUrlVisitsCount />', () => { describe('<ShortUrlVisitsCount />', () => {
let wrapper: ShallowWrapper; const setUp = (visitsCount: number, shortUrl: ShortUrl) => render(
<ShortUrlVisitsCount visitsCount={visitsCount} shortUrl={shortUrl} />,
const createWrapper = (visitsCount: number, shortUrl: ShortUrl) => { );
wrapper = shallow(<ShortUrlVisitsCount visitsCount={visitsCount} shortUrl={shortUrl} />);
return wrapper;
};
afterEach(() => wrapper?.unmount());
it.each([undefined, {}])('just returns visits when no maxVisits is provided', (meta) => { it.each([undefined, {}])('just returns visits when no maxVisits is provided', (meta) => {
const visitsCount = 45; const visitsCount = 45;
const wrapper = createWrapper(visitsCount, Mock.of<ShortUrl>({ meta })); const { container } = setUp(visitsCount, Mock.of<ShortUrl>({ meta }));
const maxVisitsHelper = wrapper.find('.short-urls-visits-count__max-visits-control');
const maxVisitsTooltip = wrapper.find(UncontrolledTooltip);
expect(wrapper.html()).toEqual( expect(container.firstChild).toHaveTextContent(`${visitsCount}`);
`<span><strong class="short-url-visits-count__amount">${visitsCount}</strong></span>`, expect(container.querySelector('.short-urls-visits-count__max-visits-control')).not.toBeInTheDocument();
);
expect(maxVisitsHelper).toHaveLength(0);
expect(maxVisitsTooltip).toHaveLength(0);
}); });
it('displays the maximum amount of visits when present', () => { it('displays the maximum amount of visits when present', () => {
const visitsCount = 45; const visitsCount = 45;
const maxVisits = 500; const maxVisits = 500;
const meta = { maxVisits }; const meta = { maxVisits };
const wrapper = createWrapper(visitsCount, Mock.of<ShortUrl>({ meta })); const { container } = setUp(visitsCount, Mock.of<ShortUrl>({ meta }));
const maxVisitsHelper = wrapper.find('.short-urls-visits-count__max-visits-control');
const maxVisitsTooltip = wrapper.find(UncontrolledTooltip);
expect(wrapper.html()).toContain(`/ ${maxVisits}`); expect(container.firstChild).toHaveTextContent(`/ ${maxVisits}`);
expect(maxVisitsHelper).toHaveLength(1); expect(container.querySelector('.short-urls-visits-count__max-visits-control')).toBeInTheDocument();
expect(maxVisitsTooltip).toHaveLength(1);
}); });
}); });

View File

@@ -1,4 +1,5 @@
import { shallow, ShallowWrapper } from 'enzyme'; 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 { 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';
@@ -8,30 +9,19 @@ import { NormalizedTag } from '../../src/tags/data';
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 TagCard = () => null; const TagsCards = createTagsCards(() => <span>TagCard</span>);
const TagsCards = createTagsCards(TagCard); const setUp = () => ({
let wrapper: ShallowWrapper; user: userEvent.setup(),
...render(<TagsCards sortedTags={sortedTags} selectedServer={Mock.all<SelectedServer>()} />),
beforeEach(() => {
wrapper = shallow(<TagsCards sortedTags={sortedTags} selectedServer={Mock.all<SelectedServer>()} />);
}); });
afterEach(() => wrapper?.unmount());
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 amountOfGroups = 4; const amountOfGroups = 4;
const cards = wrapper.find(TagCard); const cards = screen.getAllByText('TagCard');
const groups = wrapper.find('.col-md-6'); const groups = container.querySelectorAll('.col-md-6');
expect(cards).toHaveLength(amountOfTags); expect(cards).toHaveLength(amountOfTags);
expect(groups).toHaveLength(amountOfGroups); expect(groups).toHaveLength(amountOfGroups);
}); });
it('displays card on toggle', () => {
const card = () => wrapper.find(TagCard).at(5);
expect(card().prop('displayed')).toEqual(false);
(card().prop('toggle') as Function)();
expect(card().prop('displayed')).toEqual(true);
});
}); });

View File

@@ -1,42 +1,37 @@
import { shallow, ShallowWrapper } from 'enzyme'; import { render, screen } from '@testing-library/react';
import { DropdownItem } from 'reactstrap'; import userEvent from '@testing-library/user-event';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faBars as listIcon, faThLarge as cardsIcon } from '@fortawesome/free-solid-svg-icons';
import { TagsModeDropdown } from '../../src/tags/TagsModeDropdown'; import { TagsModeDropdown } from '../../src/tags/TagsModeDropdown';
import { DropdownBtn } from '../../src/utils/DropdownBtn'; import { TagsMode } from '../../src/settings/reducers/settings';
describe('<TagsModeDropdown />', () => { describe('<TagsModeDropdown />', () => {
const onChange = jest.fn(); const onChange = jest.fn();
let wrapper: ShallowWrapper; const setUp = (mode: TagsMode) => ({
user: userEvent.setup(),
beforeEach(() => { ...render(<TagsModeDropdown mode={mode} onChange={onChange} />),
wrapper = shallow(<TagsModeDropdown mode="list" onChange={onChange} />);
}); });
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);
afterEach(() => wrapper?.unmount());
it('renders expected items', () => { it.each([
const btn = wrapper.find(DropdownBtn); ['cards' as TagsMode],
const items = wrapper.find(DropdownItem); ['list' as TagsMode],
const icons = wrapper.find(FontAwesomeIcon); ])('renders expected initial value', (mode) => {
setUp(mode);
expect(btn).toHaveLength(1); expect(screen.getByRole('button')).toHaveTextContent(`Display mode: ${mode}`);
expect(btn.prop('text')).toEqual('Display mode: list');
expect(items).toHaveLength(2);
expect(icons).toHaveLength(2);
expect(icons.first().prop('icon')).toEqual(cardsIcon);
expect(icons.last().prop('icon')).toEqual(listIcon);
}); });
it('changes active element on click', () => { it('changes active element on click', async () => {
const items = wrapper.find(DropdownItem); const { user } = setUp('list');
const clickItem = async (index: 0 | 1) => {
await user.click(screen.getByRole('button'));
await user.click(screen.getAllByRole('menuitem')[index]);
};
expect(onChange).not.toHaveBeenCalled(); expect(onChange).not.toHaveBeenCalled();
items.first().simulate('click'); await clickItem(0);
expect(onChange).toHaveBeenCalledWith('cards'); expect(onChange).toHaveBeenCalledWith('cards');
items.last().simulate('click'); await clickItem(1);
expect(onChange).toHaveBeenCalledWith('list'); expect(onChange).toHaveBeenCalledWith('list');
}); });
}); });