From a14e612a38ed3c8e6007ff153a169f39bc08686e Mon Sep 17 00:00:00 2001 From: Alejandro Celaya Date: Thu, 14 Jul 2022 22:14:42 +0200 Subject: [PATCH 1/4] Migrated DateRangeSelector test to react testing library --- test/utils/dates/DateRangeSelector.test.tsx | 66 +++++++++------------ 1 file changed, 29 insertions(+), 37 deletions(-) diff --git a/test/utils/dates/DateRangeSelector.test.tsx b/test/utils/dates/DateRangeSelector.test.tsx index 4d2a8a49..868c03c0 100644 --- a/test/utils/dates/DateRangeSelector.test.tsx +++ b/test/utils/dates/DateRangeSelector.test.tsx @@ -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('', () => { - let wrapper: ShallowWrapper; const onDatesChange = jest.fn(); - const createWrapper = (props: Partial = {}) => { - wrapper = shallow( + const setUp = async (props: Partial = {}) => { + const result = renderWithEvents( (props)} defaultText="Default text" @@ -18,22 +15,20 @@ describe('', () => { />, ); - 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('', () => { ['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); }); }); From 065c908153081beb1b074c40eafe54142f8dcb22 Mon Sep 17 00:00:00 2001 From: Alejandro Celaya Date: Fri, 15 Jul 2022 21:42:16 +0200 Subject: [PATCH 2/4] Migrated QrCodeModal test to react testing library --- test/short-urls/helpers/QrCodeModal.test.tsx | 96 ++++++++------------ 1 file changed, 39 insertions(+), 57 deletions(-) diff --git a/test/short-urls/helpers/QrCodeModal.test.tsx b/test/short-urls/helpers/QrCodeModal.test.tsx index 213aea9e..bdf120e3 100644 --- a/test/short-urls/helpers/QrCodeModal.test.tsx +++ b/test/short-urls/helpers/QrCodeModal.test.tsx @@ -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('', () => { - let wrapper: ShallowWrapper; const saveImage = jest.fn().mockReturnValue(Promise.resolve()); const QrCodeModal = createQrCodeModal(Mock.of({ saveImage })); const shortUrl = 'https://doma.in/abc123'; - const createWrapper = (version: SemVer = '2.6.0') => { - const selectedServer = Mock.of({ version }); + const setUp = (version: SemVer = '2.6.0') => renderWithEvents( + ({ shortUrl })} + selectedServer={Mock.of({ version })} + toggle={() => {}} + />, + ); - wrapper = shallow( - ({ 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('', () => { ['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('', () => { [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); }); }); From 6236d36372dd910d8d6618e873655f3b5ab5bf76 Mon Sep 17 00:00:00 2001 From: Alejandro Celaya Date: Fri, 15 Jul 2022 22:00:30 +0200 Subject: [PATCH 3/4] Migrated DeleteShortUrlModal test to react testing library --- .../helpers/DeleteShortUrlModal.test.tsx | 64 ++++++++----------- 1 file changed, 26 insertions(+), 38 deletions(-) diff --git a/test/short-urls/helpers/DeleteShortUrlModal.test.tsx b/test/short-urls/helpers/DeleteShortUrlModal.test.tsx index fcbf9900..c3a3bd51 100644 --- a/test/short-urls/helpers/DeleteShortUrlModal.test.tsx +++ b/test/short-urls/helpers/DeleteShortUrlModal.test.tsx @@ -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('', () => { - let wrapper: ShallowWrapper; const shortUrl = Mock.of({ tags: [], shortCode: 'abc123', longUrl: 'https://long-domain.com/foo/bar', }); const deleteShortUrl = jest.fn(async () => Promise.resolve()); - const createWrapper = (shortUrlDeletion: Partial) => { - wrapper = shallow( - (shortUrlDeletion)} - toggle={() => {}} - deleteShortUrl={deleteShortUrl} - resetDeleteShortUrl={() => {}} - />, - ); + const setUp = (shortUrlDeletion: Partial) => renderWithEvents( + (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({ 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); }); }); From 90a643761ab50d276ac27d0d76f42e2d8b23c8e5 Mon Sep 17 00:00:00 2001 From: Alejandro Celaya Date: Fri, 15 Jul 2022 22:11:13 +0200 Subject: [PATCH 4/4] Migrated ShortUrlsRowMenu test to react testing library --- .../helpers/ShortUrlsRowMenu.test.tsx | 55 ++++++------------- 1 file changed, 16 insertions(+), 39 deletions(-) diff --git a/test/short-urls/helpers/ShortUrlsRowMenu.test.tsx b/test/short-urls/helpers/ShortUrlsRowMenu.test.tsx index 0a967ad9..3a996b3c 100644 --- a/test/short-urls/helpers/ShortUrlsRowMenu.test.tsx +++ b/test/short-urls/helpers/ShortUrlsRowMenu.test.tsx @@ -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('', () => { - let wrapper: ShallowWrapper; - const DeleteShortUrlModal = () => null; - const QrCodeModal = () => null; + const ShortUrlsRowMenu = createShortUrlsRowMenu(() => DeleteShortUrlModal, () => QrCodeModal); const selectedServer = Mock.of({ id: 'abc123' }); const shortUrl = Mock.of({ shortCode: 'abc123', shortUrl: 'https://doma.in/abc123', }); - const createWrapper = () => { - const ShortUrlsRowMenu = createShortUrlsRowMenu(DeleteShortUrlModal, QrCodeModal); - - wrapper = shallow(); - - return wrapper; - }; - - afterEach(() => wrapper?.unmount()); + const setUp = () => renderWithEvents( + + + , + ); 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); }); });