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

Feature/testing lib
This commit is contained in:
Alejandro Celaya 2022-07-16 10:01:41 +02:00 committed by GitHub
commit 9ba74328ff
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 110 additions and 171 deletions

View file

@ -1,87 +1,75 @@
import { shallow, ShallowWrapper } from 'enzyme';
import { identity } from 'ramda';
import { screen } from '@testing-library/react';
import { Mock } from 'ts-mockery';
import { DeleteShortUrlModal } from '../../../src/short-urls/helpers/DeleteShortUrlModal';
import { ShortUrl } from '../../../src/short-urls/data';
import { ShortUrlDeletion } from '../../../src/short-urls/reducers/shortUrlDeletion';
import { ProblemDetailsError } from '../../../src/api/types';
import { Result } from '../../../src/utils/Result';
import { renderWithEvents } from '../../__helpers__/setUpTest';
describe('<DeleteShortUrlModal />', () => {
let wrapper: ShallowWrapper;
const shortUrl = Mock.of<ShortUrl>({
tags: [],
shortCode: 'abc123',
longUrl: 'https://long-domain.com/foo/bar',
});
const deleteShortUrl = jest.fn(async () => Promise.resolve());
const createWrapper = (shortUrlDeletion: Partial<ShortUrlDeletion>) => {
wrapper = shallow(
<DeleteShortUrlModal
isOpen
shortUrl={shortUrl}
shortUrlDeletion={Mock.of<ShortUrlDeletion>(shortUrlDeletion)}
toggle={() => {}}
deleteShortUrl={deleteShortUrl}
resetDeleteShortUrl={() => {}}
/>,
);
const setUp = (shortUrlDeletion: Partial<ShortUrlDeletion>) => renderWithEvents(
<DeleteShortUrlModal
isOpen
shortUrl={shortUrl}
shortUrlDeletion={Mock.of<ShortUrlDeletion>(shortUrlDeletion)}
deleteShortUrl={deleteShortUrl}
toggle={() => {}}
resetDeleteShortUrl={() => {}}
/>,
);
return wrapper;
};
afterEach(() => wrapper?.unmount());
afterEach(jest.clearAllMocks);
it('shows generic error when non-threshold error occurs', () => {
const wrapper = createWrapper({
setUp({
loading: false,
error: true,
shortCode: 'abc123',
errorData: Mock.of<ProblemDetailsError>({ type: 'OTHER_ERROR' }),
});
const error = wrapper.find(Result).filterWhere((result) => result.prop('type') === 'error');
expect(error).toHaveLength(1);
expect(error.html()).toContain('Something went wrong while deleting the URL :(');
expect(screen.getByText('Something went wrong while deleting the URL :(')).toBeInTheDocument();
});
it('disables submit button when loading', () => {
const wrapper = createWrapper({
setUp({
loading: true,
error: false,
shortCode: 'abc123',
});
const submit = wrapper.find('.btn-danger');
expect(submit).toHaveLength(1);
expect(submit.prop('disabled')).toEqual(true);
expect(submit.html()).toContain('Deleting...');
expect(screen.getByRole('button', { name: 'Deleting...' })).toHaveAttribute('disabled');
});
it('enables submit button when proper short code is provided', () => {
it('enables submit button when proper short code is provided', async () => {
const shortCode = 'abc123';
const wrapper = createWrapper({
const { user } = setUp({
loading: false,
error: false,
shortCode,
});
const getDeleteBtn = () => screen.getByRole('button', { name: 'Delete' });
expect(wrapper.find('.btn-danger').prop('disabled')).toEqual(true);
wrapper.find('.form-control').simulate('change', { target: { value: shortCode } });
expect(wrapper.find('.btn-danger').prop('disabled')).toEqual(false);
expect(getDeleteBtn()).toHaveAttribute('disabled');
await user.type(screen.getByPlaceholderText(/^Insert the short code/), shortCode);
expect(getDeleteBtn()).not.toHaveAttribute('disabled');
});
it('tries to delete short URL when form is submit', () => {
it('tries to delete short URL when form is submit', async () => {
const shortCode = 'abc123';
const wrapper = createWrapper({
const { user } = setUp({
loading: false,
error: false,
shortCode,
});
expect(deleteShortUrl).not.toHaveBeenCalled();
wrapper.find('form').simulate('submit', { preventDefault: identity });
await user.type(screen.getByPlaceholderText(/^Insert the short code/), shortCode);
await user.click(screen.getByRole('button', { name: 'Delete' }));
expect(deleteShortUrl).toHaveBeenCalledTimes(1);
});
});

View file

@ -1,45 +1,34 @@
import { shallow, ShallowWrapper } from 'enzyme';
import { ExternalLink } from 'react-external-link';
import { Button, FormGroup, Modal, ModalBody, ModalHeader, Row } from 'reactstrap';
import { fireEvent, screen } from '@testing-library/react';
import { Mock } from 'ts-mockery';
import { QrCodeModal as createQrCodeModal } from '../../../src/short-urls/helpers/QrCodeModal';
import { ShortUrl } from '../../../src/short-urls/data';
import { ReachableServer } from '../../../src/servers/data';
import { CopyToClipboardIcon } from '../../../src/utils/CopyToClipboardIcon';
import { SemVer } from '../../../src/utils/helpers/version';
import { ImageDownloader } from '../../../src/common/services/ImageDownloader';
import { QrFormatDropdown } from '../../../src/short-urls/helpers/qr-codes/QrFormatDropdown';
import { QrErrorCorrectionDropdown } from '../../../src/short-urls/helpers/qr-codes/QrErrorCorrectionDropdown';
import { renderWithEvents } from '../../__helpers__/setUpTest';
describe('<QrCodeModal />', () => {
let wrapper: ShallowWrapper;
const saveImage = jest.fn().mockReturnValue(Promise.resolve());
const QrCodeModal = createQrCodeModal(Mock.of<ImageDownloader>({ saveImage }));
const shortUrl = 'https://doma.in/abc123';
const createWrapper = (version: SemVer = '2.6.0') => {
const selectedServer = Mock.of<ReachableServer>({ version });
const setUp = (version: SemVer = '2.6.0') => renderWithEvents(
<QrCodeModal
isOpen
shortUrl={Mock.of<ShortUrl>({ shortUrl })}
selectedServer={Mock.of<ReachableServer>({ version })}
toggle={() => {}}
/>,
);
wrapper = shallow(
<QrCodeModal
shortUrl={Mock.of<ShortUrl>({ shortUrl })}
isOpen
toggle={() => {}}
selectedServer={selectedServer}
/>,
);
return wrapper;
};
afterEach(() => wrapper?.unmount());
afterEach(jest.clearAllMocks);
it('shows an external link to the URL in the header', () => {
const wrapper = createWrapper();
const externalLink = wrapper.find(ModalHeader).find(ExternalLink);
setUp();
const externalLink = screen.getByRole('heading').querySelector('a');
expect(externalLink).toHaveLength(1);
expect(externalLink.prop('href')).toEqual(shortUrl);
expect(externalLink).toBeInTheDocument();
expect(externalLink).toHaveAttribute('href', shortUrl);
expect(externalLink).toHaveAttribute('rel', 'noopener noreferrer');
});
it.each([
@ -47,22 +36,16 @@ describe('<QrCodeModal />', () => {
['2.6.0' as SemVer, 0, '/qr-code?size=300&format=png'],
['2.6.0' as SemVer, 10, '/qr-code?size=300&format=png&margin=10'],
['2.8.0' as SemVer, 0, '/qr-code?size=300&format=png&errorCorrection=L'],
])('displays an image with the QR code of the URL', (version, margin, expectedUrl) => {
const wrapper = createWrapper(version);
const formControls = wrapper.find('.form-control-range');
])('displays an image with the QR code of the URL', async (version, margin, expectedUrl) => {
const { container } = setUp(version);
const marginControl = container.parentNode?.querySelectorAll('.form-control-range').item(1);
if (formControls.length > 1) {
formControls.at(1).simulate('change', { target: { value: `${margin}` } });
if (marginControl) {
fireEvent.change(marginControl, { target: { value: `${margin}` } });
}
const modalBody = wrapper.find(ModalBody);
const img = modalBody.find('img');
const linkInBody = modalBody.find(ExternalLink);
const copyToClipboard = modalBody.find(CopyToClipboardIcon);
expect(img.prop('src')).toEqual(`${shortUrl}${expectedUrl}`);
expect(linkInBody.prop('href')).toEqual(`${shortUrl}${expectedUrl}`);
expect(copyToClipboard.prop('text')).toEqual(`${shortUrl}${expectedUrl}`);
expect(screen.getByRole('img')).toHaveAttribute('src', `${shortUrl}${expectedUrl}`);
expect(screen.getByText(`${shortUrl}${expectedUrl}`)).toHaveAttribute('href', `${shortUrl}${expectedUrl}`);
});
it.each([
@ -73,37 +56,36 @@ describe('<QrCodeModal />', () => {
[200, 50, undefined],
[720, 100, 'xl'],
])('renders expected size', (size, margin, modalSize) => {
const wrapper = createWrapper();
const formControls = wrapper.find('.form-control-range');
const sizeInput = formControls.at(0);
const marginInput = formControls.at(1);
const { container } = setUp();
const formControls = container.parentNode?.querySelectorAll('.form-control-range');
const sizeInput = formControls?.[0];
const marginInput = formControls?.[1];
sizeInput.simulate('change', { target: { value: `${size}` } });
marginInput.simulate('change', { target: { value: `${margin}` } });
sizeInput && fireEvent.change(sizeInput, { target: { value: `${size}` } });
marginInput && fireEvent.change(marginInput, { target: { value: `${margin}` } });
expect(wrapper.find('label').at(0).text()).toEqual(`Size: ${size}px`);
expect(wrapper.find('label').at(1).text()).toEqual(`Margin: ${margin}px`);
expect(wrapper.find(Modal).prop('size')).toEqual(modalSize);
expect(screen.getByText(`Size: ${size}px`)).toBeInTheDocument();
expect(screen.getByText(`Margin: ${margin}px`)).toBeInTheDocument();
modalSize && expect(screen.getByRole('document')).toHaveClass(`modal-${modalSize}`);
});
it.each([
['2.6.0' as SemVer, 1, 'col-md-4'],
['2.8.0' as SemVer, 2, 'col-md-6'],
])('shows expected components based on server version', (version, expectedAmountOfDropdowns, expectedRangeClass) => {
const wrapper = createWrapper(version);
const dropdownsLength = wrapper.find(QrFormatDropdown).length + wrapper.find(QrErrorCorrectionDropdown).length;
const firstCol = wrapper.find(Row).find(FormGroup).first();
const { container } = setUp(version);
const dropdowns = screen.getAllByRole('button');
const firstCol = container.parentNode?.querySelectorAll('.d-grid').item(0);
expect(dropdownsLength).toEqual(expectedAmountOfDropdowns);
expect(firstCol.prop('className')).toEqual(`d-grid ${expectedRangeClass}`);
expect(dropdowns).toHaveLength(expectedAmountOfDropdowns + 1); // Add one because of the close button
expect(firstCol).toHaveClass(expectedRangeClass);
});
it('saves the QR code image when clicking the Download button', () => {
const wrapper = createWrapper('2.9.0');
const downloadBtn = wrapper.find(Button);
it('saves the QR code image when clicking the Download button', async () => {
const { user } = setUp('2.9.0');
expect(saveImage).not.toHaveBeenCalled();
downloadBtn.simulate('click');
await user.click(screen.getByRole('button', { name: /^Download/ }));
expect(saveImage).toHaveBeenCalledTimes(1);
});
});

View file

@ -1,58 +1,35 @@
import { shallow, ShallowWrapper } from 'enzyme';
import { DropdownItem } from 'reactstrap';
import { screen } from '@testing-library/react';
import { Mock } from 'ts-mockery';
import { MemoryRouter } from 'react-router-dom';
import { ShortUrlsRowMenu as createShortUrlsRowMenu } from '../../../src/short-urls/helpers/ShortUrlsRowMenu';
import { ReachableServer } from '../../../src/servers/data';
import { ShortUrl } from '../../../src/short-urls/data';
import { DropdownBtnMenu } from '../../../src/utils/DropdownBtnMenu';
import { renderWithEvents } from '../../__helpers__/setUpTest';
describe('<ShortUrlsRowMenu />', () => {
let wrapper: ShallowWrapper;
const DeleteShortUrlModal = () => null;
const QrCodeModal = () => null;
const ShortUrlsRowMenu = createShortUrlsRowMenu(() => <i>DeleteShortUrlModal</i>, () => <i>QrCodeModal</i>);
const selectedServer = Mock.of<ReachableServer>({ id: 'abc123' });
const shortUrl = Mock.of<ShortUrl>({
shortCode: 'abc123',
shortUrl: 'https://doma.in/abc123',
});
const createWrapper = () => {
const ShortUrlsRowMenu = createShortUrlsRowMenu(DeleteShortUrlModal, QrCodeModal);
wrapper = shallow(<ShortUrlsRowMenu selectedServer={selectedServer} shortUrl={shortUrl} />);
return wrapper;
};
afterEach(() => wrapper?.unmount());
const setUp = () => renderWithEvents(
<MemoryRouter>
<ShortUrlsRowMenu selectedServer={selectedServer} shortUrl={shortUrl} />
</MemoryRouter>,
);
it('renders modal windows', () => {
const wrapper = createWrapper();
const deleteShortUrlModal = wrapper.find(DeleteShortUrlModal);
const qrCodeModal = wrapper.find(QrCodeModal);
setUp();
expect(deleteShortUrlModal).toHaveLength(1);
expect(qrCodeModal).toHaveLength(1);
expect(screen.getByText('DeleteShortUrlModal')).toBeInTheDocument();
expect(screen.getByText('QrCodeModal')).toBeInTheDocument();
});
it('renders correct amount of menu items', () => {
const wrapper = createWrapper();
const items = wrapper.find(DropdownItem);
it('renders correct amount of menu items', async () => {
const { user } = setUp();
expect(items).toHaveLength(5);
expect(items.find('[divider]')).toHaveLength(1);
});
describe('toggles state when toggling modals or the dropdown', () => {
const assert = (modalComponent: Function) => {
const wrapper = createWrapper();
expect(wrapper.find(modalComponent).prop('isOpen')).toEqual(false);
(wrapper.find(modalComponent).prop('toggle') as Function)();
expect(wrapper.find(modalComponent).prop('isOpen')).toEqual(true);
};
it('DeleteShortUrlModal', () => assert(DeleteShortUrlModal));
it('QrCodeModal', () => assert(QrCodeModal));
it('ShortUrlRowMenu', () => assert(DropdownBtnMenu));
await user.click(screen.getByRole('button'));
expect(screen.getAllByRole('menuitem')).toHaveLength(4);
});
});

View file

@ -1,16 +1,13 @@
import { shallow, ShallowWrapper } from 'enzyme';
import { DropdownItem } from 'reactstrap';
import { screen } from '@testing-library/react';
import { Mock } from 'ts-mockery';
import { DateRangeSelector, DateRangeSelectorProps } from '../../../src/utils/dates/DateRangeSelector';
import { DateInterval } from '../../../src/utils/dates/types';
import { DateIntervalDropdownItems } from '../../../src/utils/dates/DateIntervalDropdownItems';
import { DateRangeRow } from '../../../src/utils/dates/DateRangeRow';
import { renderWithEvents } from '../../__helpers__/setUpTest';
describe('<DateRangeSelector />', () => {
let wrapper: ShallowWrapper;
const onDatesChange = jest.fn();
const createWrapper = (props: Partial<DateRangeSelectorProps> = {}) => {
wrapper = shallow(
const setUp = async (props: Partial<DateRangeSelectorProps> = {}) => {
const result = renderWithEvents(
<DateRangeSelector
{...Mock.of<DateRangeSelectorProps>(props)}
defaultText="Default text"
@ -18,22 +15,20 @@ describe('<DateRangeSelector />', () => {
/>,
);
return wrapper;
await result.user.click(screen.getByRole('button'));
return result;
};
afterEach(jest.clearAllMocks);
afterEach(() => wrapper?.unmount());
it('renders proper amount of items', () => {
const wrapper = createWrapper();
const items = wrapper.find(DropdownItem);
const dateIntervalItems = wrapper.find(DateIntervalDropdownItems);
it('renders proper amount of items', async () => {
const { container } = await setUp();
expect(items).toHaveLength(3);
expect(dateIntervalItems).toHaveLength(1);
expect(items.filter('[divider]')).toHaveLength(1);
expect(items.filter('[header]')).toHaveLength(1);
expect(items.filter('[text]')).toHaveLength(1);
expect(screen.getAllByRole('menuitem')).toHaveLength(8);
expect(screen.getByRole('heading')).toHaveTextContent('Custom:');
expect(container.querySelector('.dropdown-divider')).toBeInTheDocument();
expect(container.querySelector('.dropdown-item-text')).toBeInTheDocument();
});
it.each([
@ -47,30 +42,27 @@ describe('<DateRangeSelector />', () => {
['last180Days' as DateInterval, 1],
['last365Days' as DateInterval, 1],
[{ startDate: new Date() }, 0],
])('sets proper element as active based on provided date range', (initialDateRange, expectedActiveIntervalItems) => {
const wrapper = createWrapper({ initialDateRange });
const dateIntervalItems = wrapper.find(DateIntervalDropdownItems).filterWhere(
(item) => item.prop('active') !== undefined,
);
expect(dateIntervalItems).toHaveLength(expectedActiveIntervalItems);
])('sets proper element as active based on provided date range', async (initialDateRange, expectedActiveItems) => {
const { container } = await setUp({ initialDateRange });
expect(container.querySelectorAll('.active')).toHaveLength(expectedActiveItems);
});
it('triggers onDatesChange callback when selecting an element', () => {
const wrapper = createWrapper();
const dates = wrapper.find(DateRangeRow);
const dateIntervalItems = wrapper.find(DateIntervalDropdownItems);
it('triggers onDatesChange callback when selecting an element', async () => {
const { user } = await setUp();
await user.click(screen.getByPlaceholderText('Since...'));
await user.click(screen.getAllByRole('option')[0]);
await user.click(screen.getByPlaceholderText('Until...'));
await user.click(screen.getAllByRole('option')[0]);
await user.click(screen.getAllByRole('menuitem')[0]);
dates.simulate('startDateChange', null);
dates.simulate('endDateChange', null);
dateIntervalItems.simulate('change');
expect(onDatesChange).toHaveBeenCalledTimes(3);
});
it('propagates default text to DateIntervalDropdownItems', () => {
const wrapper = createWrapper();
const dateIntervalItems = wrapper.find(DateIntervalDropdownItems);
expect(dateIntervalItems.prop('allText')).toEqual('Default text');
it('propagates default text to DateIntervalDropdownItems', async () => {
await setUp();
expect(screen.getAllByText('Default text')).toHaveLength(2);
});
});