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

View file

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

View file

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

View file

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