Migrated ShortUrlsRow test to react testing library

This commit is contained in:
Alejandro Celaya 2022-07-16 10:27:29 +02:00
parent 9ba74328ff
commit a038f5e618

View file

@ -1,35 +1,30 @@
import { shallow, ShallowWrapper } from 'enzyme'; import { screen } from '@testing-library/react';
import { assoc, toString } from 'ramda';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { ExternalLink } from 'react-external-link';
import { formatISO } from 'date-fns'; import { formatISO } from 'date-fns';
import { ShortUrlsRow as createShortUrlsRow } from '../../../src/short-urls/helpers/ShortUrlsRow'; import { ShortUrlsRow as createShortUrlsRow } from '../../../src/short-urls/helpers/ShortUrlsRow';
import { Tag } from '../../../src/tags/helpers/Tag';
import { ColorGenerator } from '../../../src/utils/services/ColorGenerator'; import { ColorGenerator } from '../../../src/utils/services/ColorGenerator';
import { TimeoutToggle } from '../../../src/utils/helpers/hooks'; import { TimeoutToggle } from '../../../src/utils/helpers/hooks';
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 { Time } from '../../../src/utils/Time';
import { parseDate } from '../../../src/utils/helpers/date'; import { parseDate } from '../../../src/utils/helpers/date';
import { renderWithEvents } from '../../__helpers__/setUpTest';
import { OptionalString } from '../../../src/utils/utils';
describe('<ShortUrlsRow />', () => { describe('<ShortUrlsRow />', () => {
let wrapper: ShallowWrapper;
const mockFunction = () => null;
const ShortUrlsRowMenu = mockFunction;
const timeoutToggle = jest.fn(() => true); const timeoutToggle = jest.fn(() => true);
const useTimeoutToggle = jest.fn(() => [false, timeoutToggle]) as TimeoutToggle; const useTimeoutToggle = jest.fn(() => [false, timeoutToggle]) as TimeoutToggle;
const colorGenerator = Mock.of<ColorGenerator>({ const colorGenerator = Mock.of<ColorGenerator>({
getColorForKey: jest.fn(), getColorForKey: jest.fn(() => 'red'),
setColorForKey: jest.fn(), setColorForKey: jest.fn(),
isColorLightForKey: jest.fn(() => false),
}); });
const server = Mock.of<ReachableServer>({ url: 'https://doma.in' }); const server = Mock.of<ReachableServer>({ url: 'https://doma.in' });
const shortUrl: ShortUrl = { const shortUrl: ShortUrl = {
shortCode: 'abc123', shortCode: 'abc123',
shortUrl: 'http://doma.in/abc123', shortUrl: 'https://doma.in/abc123',
longUrl: 'http://foo.com/bar', longUrl: 'https://foo.com/bar',
dateCreated: formatISO(parseDate('2018-05-23 18:30:41', 'yyyy-MM-dd HH:mm:ss')), dateCreated: formatISO(parseDate('2018-05-23 18:30:41', 'yyyy-MM-dd HH:mm:ss')),
tags: ['nodejs', 'reactjs'], tags: [],
visitsCount: 45, visitsCount: 45,
domain: null, domain: null,
meta: { meta: {
@ -38,99 +33,73 @@ describe('<ShortUrlsRow />', () => {
maxVisits: null, maxVisits: null,
}, },
}; };
const ShortUrlsRow = createShortUrlsRow(ShortUrlsRowMenu, colorGenerator, useTimeoutToggle); const ShortUrlsRow = createShortUrlsRow(() => <span>ShortUrlsRowMenu</span>, colorGenerator, useTimeoutToggle);
const createWrapper = (title?: string | null) => { const setUp = (title?: OptionalString, tags: string[] = []) => renderWithEvents(
wrapper = shallow( <table>
<ShortUrlsRow selectedServer={server} shortUrl={{ ...shortUrl, title }} onTagClick={mockFunction} />, <tbody>
); <ShortUrlsRow selectedServer={server} shortUrl={{ ...shortUrl, title, tags }} onTagClick={() => null} />
</tbody>
return wrapper; </table>,
}; );
beforeEach(() => createWrapper());
afterEach(() => wrapper.unmount());
it.each([ it.each([
[null, 6], [null, 6],
[undefined, 6], [undefined, 6],
['The title', 7], ['The title', 7],
])('renders expected amount of columns', (title, expectedAmount) => { ])('renders expected amount of columns', (title, expectedAmount) => {
const wrapper = createWrapper(title); setUp(title);
const cols = wrapper.find('td'); expect(screen.getAllByRole('cell')).toHaveLength(expectedAmount);
expect(cols).toHaveLength(expectedAmount);
}); });
it('renders date in first column', () => { it('renders date in first column', () => {
const col = wrapper.find('td').first(); setUp();
const date = col.find(Time); expect(screen.getAllByRole('cell')[0]).toHaveTextContent('2018-05-23 18:30');
expect(date.html()).toContain('>2018-05-23 18:30</time>');
}); });
it('renders short URL in second row', () => { it.each([
const col = wrapper.find('td').at(1); [1, shortUrl.shortUrl],
const link = col.find(ExternalLink); [2, shortUrl.longUrl],
])('renders expected links on corresponding columns', (colIndex, expectedLink) => {
setUp();
expect(link.prop('href')).toEqual(shortUrl.shortUrl); const col = screen.getAllByRole('cell')[colIndex];
const link = col.querySelector('a');
expect(link).toHaveAttribute('href', expectedLink);
}); });
it('renders long URL in third row', () => { it.each([
const col = wrapper.find('td').at(2); ['My super cool title', 'My super cool title'],
const link = col.find(ExternalLink); [undefined, shortUrl.longUrl],
])('renders title when short URL has it', (title, expectedContent) => {
setUp(title);
expect(link.prop('href')).toEqual(shortUrl.longUrl); const titleSharedCol = screen.getAllByRole('cell')[2];
expect(titleSharedCol.querySelector('a')).toHaveAttribute('href', shortUrl.longUrl);
expect(titleSharedCol).toHaveTextContent(expectedContent);
}); });
it('renders title when short URL has it', () => { it.each([
const wrapper = createWrapper('My super cool title'); [[], ['No tags']],
const cols = wrapper.find('td'); [['nodejs', 'reactjs'], ['nodejs', 'reactjs']],
const titleSharedCol = cols.at(2).find(ExternalLink); ])('renders list of tags in fourth row', (tags, expectedContents) => {
const dedicatedShortUrlCol = cols.at(3).find(ExternalLink); setUp(undefined, tags);
const cell = screen.getAllByRole('cell')[3];
expect(titleSharedCol).toHaveLength(1); expectedContents.forEach((content) => expect(cell).toHaveTextContent(content));
expect(dedicatedShortUrlCol).toHaveLength(1);
expect(titleSharedCol.prop('href')).toEqual(shortUrl.longUrl);
expect(dedicatedShortUrlCol.prop('href')).toEqual(shortUrl.longUrl);
expect(titleSharedCol.html()).toContain('My super cool title');
expect(dedicatedShortUrlCol.prop('children')).not.toBeDefined();
});
describe('renders list of tags in fourth row', () => {
it('with tags', () => {
const col = wrapper.find('td').at(3);
const tags = col.find(Tag);
expect(tags).toHaveLength(shortUrl.tags.length);
shortUrl.tags.forEach((tagValue, index) => {
const tag = tags.at(index);
expect(tag.prop('text')).toEqual(tagValue);
});
});
it('without tags', () => {
wrapper.setProps({ shortUrl: assoc('tags', [], shortUrl) });
const col = wrapper.find('td').at(3);
expect(col.text()).toContain('No tags');
});
}); });
it('renders visits count in fifth row', () => { it('renders visits count in fifth row', () => {
const col = wrapper.find('td').at(4); setUp();
expect(screen.getAllByRole('cell')[4]).toHaveTextContent(`${shortUrl.visitsCount}`);
expect(col.html()).toContain(toString(shortUrl.visitsCount));
}); });
it('updates state when copied to clipboard', () => { it('updates state when copied to clipboard', async () => {
const col = wrapper.find('td').at(1); const { user } = setUp();
const menu = col.find(CopyToClipboardIcon);
expect(menu).toHaveLength(1);
expect(timeoutToggle).not.toHaveBeenCalled(); expect(timeoutToggle).not.toHaveBeenCalled();
menu.simulate('copy'); await user.click(screen.getByRole('img', { hidden: true }));
expect(timeoutToggle).toHaveBeenCalledTimes(1); expect(timeoutToggle).toHaveBeenCalledTimes(1);
}); });
}); });