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

Feature/testing lib
This commit is contained in:
Alejandro Celaya 2022-07-05 21:12:04 +02:00 committed by GitHub
commit edef36bae8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 90 additions and 92 deletions

View file

@ -118,7 +118,7 @@ export const ShortUrlForm = (
const showBehaviorCard = showCrawlableControl || showForwardQueryControl; const showBehaviorCard = showCrawlableControl || showForwardQueryControl;
return ( return (
<form className="short-url-form" onSubmit={submit}> <form name="shortUrlForm" className="short-url-form" onSubmit={submit}>
{isBasicMode && basicComponents} {isBasicMode && basicComponents}
{!isBasicMode && ( {!isBasicMode && (
<> <>

View file

@ -1,67 +1,67 @@
import { shallow, ShallowWrapper } from 'enzyme'; import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { UserEvent } from '@testing-library/user-event/dist/types/setup';
import { formatISO } from 'date-fns'; import { formatISO } from 'date-fns';
import { identity } from 'ramda';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { Input } from 'reactstrap';
import { ShortUrlForm as createShortUrlForm, Mode } from '../../src/short-urls/ShortUrlForm'; import { ShortUrlForm as createShortUrlForm, Mode } from '../../src/short-urls/ShortUrlForm';
import { DateInput } from '../../src/utils/DateInput';
import { ShortUrlData } from '../../src/short-urls/data';
import { ReachableServer, SelectedServer } from '../../src/servers/data'; import { ReachableServer, SelectedServer } from '../../src/servers/data';
import { SimpleCard } from '../../src/utils/SimpleCard';
import { parseDate } from '../../src/utils/helpers/date'; import { parseDate } from '../../src/utils/helpers/date';
import { OptionalString } from '../../src/utils/utils'; import { OptionalString } from '../../src/utils/utils';
describe('<ShortUrlForm />', () => { describe('<ShortUrlForm />', () => {
let wrapper: ShallowWrapper;
const TagsSelector = () => null;
const DomainSelector = () => null;
const createShortUrl = jest.fn(async () => Promise.resolve()); const createShortUrl = jest.fn(async () => Promise.resolve());
const createWrapper = (selectedServer: SelectedServer = null, mode: Mode = 'create', title?: OptionalString) => { const ShortUrlForm = createShortUrlForm(() => <span>TagsSelector</span>, () => <span>DomainSelector</span>);
const ShortUrlForm = createShortUrlForm(TagsSelector, DomainSelector); const setUp = (selectedServer: SelectedServer = null, mode: Mode = 'create', title?: OptionalString) => ({
user: userEvent.setup(),
wrapper = shallow( ...render(
<ShortUrlForm <ShortUrlForm
selectedServer={selectedServer} selectedServer={selectedServer}
mode={mode} mode={mode}
saving={false} saving={false}
initialState={Mock.of<ShortUrlData>({ validateUrl: true, findIfExists: false, title })} initialState={{ validateUrl: true, findIfExists: false, title, longUrl: '' }}
onSave={createShortUrl} onSave={createShortUrl}
/>, />,
); ),
});
return wrapper;
};
afterEach(() => wrapper.unmount());
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);
it('saves short URL with data set in form controls', () => { it.each([
const wrapper = createWrapper(); [
async (user: UserEvent) => {
await user.type(screen.getByPlaceholderText('Custom slug'), 'my-slug');
},
{ customSlug: 'my-slug' },
],
[
async (user: UserEvent) => {
await user.type(screen.getByPlaceholderText('Short code length'), '15');
},
{ shortCodeLength: '15' },
],
])('saves short URL with data set in form controls', async (extraFields, extraExpectedValues) => {
const { user } = setUp();
const validSince = parseDate('2017-01-01', 'yyyy-MM-dd'); const validSince = parseDate('2017-01-01', 'yyyy-MM-dd');
const validUntil = parseDate('2017-01-06', 'yyyy-MM-dd'); const validUntil = parseDate('2017-01-06', 'yyyy-MM-dd');
wrapper.find(Input).first().simulate('change', { target: { value: 'https://long-domain.com/foo/bar' } }); await user.type(screen.getByPlaceholderText('URL to be shortened'), 'https://long-domain.com/foo/bar');
wrapper.find('TagsSelector').simulate('change', ['tag_foo', 'tag_bar']); await user.type(screen.getByPlaceholderText('Title'), 'the title');
wrapper.find('#customSlug').simulate('change', { target: { value: 'my-slug' } }); await user.type(screen.getByPlaceholderText('Maximum number of visits allowed'), '20');
wrapper.find(DomainSelector).simulate('change', 'example.com'); await user.type(screen.getByPlaceholderText('Enabled since...'), '2017-01-01');
wrapper.find('#maxVisits').simulate('change', { target: { value: '20' } }); await user.type(screen.getByPlaceholderText('Enabled until...'), '2017-01-06');
wrapper.find('#shortCodeLength').simulate('change', { target: { value: 15 } }); await extraFields(user);
wrapper.find(DateInput).at(0).simulate('change', validSince);
wrapper.find(DateInput).at(1).simulate('change', validUntil);
wrapper.find('form').simulate('submit', { preventDefault: identity });
expect(createShortUrl).toHaveBeenCalledTimes(1); expect(createShortUrl).not.toHaveBeenCalled();
await user.click(screen.getByRole('button', { name: 'Save' }));
expect(createShortUrl).toHaveBeenCalledWith({ expect(createShortUrl).toHaveBeenCalledWith({
longUrl: 'https://long-domain.com/foo/bar', longUrl: 'https://long-domain.com/foo/bar',
tags: ['tag_foo', 'tag_bar'], title: 'the title',
customSlug: 'my-slug',
domain: 'example.com',
validSince: formatISO(validSince), validSince: formatISO(validSince),
validUntil: formatISO(validUntil), validUntil: formatISO(validUntil),
maxVisits: 20, maxVisits: 20,
findIfExists: false, findIfExists: false,
shortCodeLength: 15,
validateUrl: true, validateUrl: true,
...extraExpectedValues,
}); });
}); });
@ -71,29 +71,30 @@ describe('<ShortUrlForm />', () => {
])( ])(
'renders expected amount of cards based on server capabilities and mode', 'renders expected amount of cards based on server capabilities and mode',
(mode, expectedAmountOfCards) => { (mode, expectedAmountOfCards) => {
const wrapper = createWrapper(null, mode); setUp(null, mode);
const cards = wrapper.find(SimpleCard); const cards = screen.queryAllByRole('heading');
expect(cards).toHaveLength(expectedAmountOfCards); expect(cards).toHaveLength(expectedAmountOfCards);
}, },
); );
it.each([ it.each([
[null, 'new title', 'new title'], [null, true, 'new title'],
[undefined, 'new title', 'new title'], [undefined, true, 'new title'],
['', 'new title', 'new title'], ['', true, 'new title'],
[null, '', undefined], [null, false, undefined],
[null, null, undefined], ['', false, undefined],
['', '', undefined], ['old title', false, null],
[undefined, undefined, undefined], ])('sends expected title based on original and new values', async (originalTitle, withNewTitle, expectedSentTitle) => {
['old title', null, null], const { user } = setUp(Mock.of<ReachableServer>({ version: '2.6.0' }), 'create', originalTitle);
['old title', undefined, null],
['old title', '', null],
])('sends expected title based on original and new values', (originalTitle, newTitle, expectedSentTitle) => {
const wrapper = createWrapper(Mock.of<ReachableServer>({ version: '2.6.0' }), 'create', originalTitle);
wrapper.find('#title').simulate('change', { target: { value: newTitle } }); await user.type(screen.getByPlaceholderText('URL to be shortened'), 'https://long-domain.com/foo/bar');
wrapper.find('form').simulate('submit', { preventDefault: identity }); if (withNewTitle) {
await user.type(screen.getByPlaceholderText('Title'), 'new title');
} else {
await user.clear(screen.getByPlaceholderText('Title'));
}
await user.click(screen.getByRole('button', { name: 'Save' }));
expect(createShortUrl).toHaveBeenCalledWith(expect.objectContaining({ expect(createShortUrl).toHaveBeenCalledWith(expect.objectContaining({
title: expectedSentTitle, title: expectedSentTitle,

View file

@ -1,71 +1,68 @@
import { shallow, ShallowWrapper } from 'enzyme'; import { fireEvent, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { ShortUrlsTable as shortUrlsTableCreator } from '../../src/short-urls/ShortUrlsTable'; import { ShortUrlsTable as shortUrlsTableCreator } from '../../src/short-urls/ShortUrlsTable';
import { ShortUrlsList } from '../../src/short-urls/reducers/shortUrlsList'; import { ShortUrlsList } from '../../src/short-urls/reducers/shortUrlsList';
import { ReachableServer, SelectedServer } from '../../src/servers/data'; import { ReachableServer, SelectedServer } from '../../src/servers/data';
import { ShortUrlsOrderableFields, SHORT_URLS_ORDERABLE_FIELDS } from '../../src/short-urls/data'; import { ShortUrlsOrderableFields, SHORT_URLS_ORDERABLE_FIELDS } from '../../src/short-urls/data';
describe('<ShortUrlsTable />', () => { describe('<ShortUrlsTable />', () => {
let wrapper: ShallowWrapper;
const shortUrlsList = Mock.all<ShortUrlsList>(); const shortUrlsList = Mock.all<ShortUrlsList>();
const orderByColumn = jest.fn(); const orderByColumn = jest.fn();
const ShortUrlsRow = () => null; const ShortUrlsTable = shortUrlsTableCreator(() => <span>ShortUrlsRow</span>);
const ShortUrlsTable = shortUrlsTableCreator(ShortUrlsRow); const setUp = (server: SelectedServer = null) => ({
user: userEvent.setup(),
const createWrapper = (server: SelectedServer = null) => { ...render(
wrapper = shallow(
<ShortUrlsTable shortUrlsList={shortUrlsList} selectedServer={server} orderByColumn={() => orderByColumn} />, <ShortUrlsTable shortUrlsList={shortUrlsList} selectedServer={server} orderByColumn={() => orderByColumn} />,
); ),
return wrapper;
};
beforeEach(() => createWrapper());
afterEach(jest.resetAllMocks);
afterEach(() => wrapper?.unmount());
it('should render inner table by default', () => {
expect(wrapper.find('table')).toHaveLength(1);
}); });
it('should render table header by default', () => { afterEach(jest.resetAllMocks);
expect(wrapper.find('table').find('thead')).toHaveLength(1);
it('should render inner table by default', () => {
setUp();
expect(screen.getByRole('table')).toBeInTheDocument();
});
it('should render row groups by default', () => {
setUp();
expect(screen.getAllByRole('rowgroup')).toHaveLength(2);
}); });
it('should render 6 table header cells by default', () => { it('should render 6 table header cells by default', () => {
expect(wrapper.find('table').find('thead').find('tr').find('th')).toHaveLength(6); setUp();
expect(screen.getAllByRole('columnheader')).toHaveLength(6);
}); });
it('should render 6 table header cells without order by icon by default', () => { it('should render table header cells without "order by" icon by default', () => {
const thElements = wrapper.find('table').find('thead').find('tr').find('th'); setUp();
expect(screen.queryByRole('img', { hidden: true })).not.toBeInTheDocument();
thElements.forEach((thElement) => {
expect(thElement.find(FontAwesomeIcon)).toHaveLength(0);
});
}); });
it('should render table header cells with conditional order by icon', () => { it('should render table header cells with conditional order by icon', () => {
const getThElementForSortableField = (orderableField: string) => wrapper.find('table') setUp();
.find('thead')
.find('tr') const getThElementForSortableField = (orderableField: string) => screen.getAllByRole('columnheader').find(
.find('th') ({ innerHTML }) => innerHTML.includes(SHORT_URLS_ORDERABLE_FIELDS[orderableField as ShortUrlsOrderableFields]),
.filterWhere((e) => e.text().includes(SHORT_URLS_ORDERABLE_FIELDS[orderableField as ShortUrlsOrderableFields])); );
const sortableFields = Object.keys(SHORT_URLS_ORDERABLE_FIELDS).filter((sortableField) => sortableField !== 'title'); const sortableFields = Object.keys(SHORT_URLS_ORDERABLE_FIELDS).filter((sortableField) => sortableField !== 'title');
expect.assertions(sortableFields.length); expect.assertions(sortableFields.length * 2);
sortableFields.forEach((sortableField) => { sortableFields.forEach((sortableField) => {
getThElementForSortableField(sortableField).simulate('click'); const element = getThElementForSortableField(sortableField);
expect(element).toBeDefined();
element && fireEvent.click(element);
expect(orderByColumn).toHaveBeenCalled(); expect(orderByColumn).toHaveBeenCalled();
}); });
}); });
it('should render composed title column', () => { it('should render composed title column', () => {
const wrapper = createWrapper(Mock.of<ReachableServer>({ version: '2.0.0' })); setUp(Mock.of<ReachableServer>({ version: '2.0.0' }));
const composedColumn = wrapper.find('table').find('th').at(2);
const text = composedColumn.text();
expect(text).toContain('Title'); const { innerHTML } = screen.getAllByRole('columnheader')[2];
expect(text).toContain('Long URL');
expect(innerHTML).toContain('Title');
expect(innerHTML).toContain('Long URL');
}); });
}); });