Migrated VisitsTable test to react-testing-library, and removed latest references to enzyme

This commit is contained in:
Alejandro Celaya 2022-07-17 11:50:26 +02:00
parent 1ffd71e81f
commit 72399e7ccd
10 changed files with 87 additions and 951 deletions

View file

@ -19,7 +19,7 @@ jobs:
node-version: 16.15
- name: Build
run: |
npm ci --force && \
npm ci && \
node ./scripts/set-homepage.js /shlink-web-client/${GITHUB_HEAD_REF#refs/heads/} && \
rm src/service-worker.ts && \
npm run build

View file

@ -16,7 +16,7 @@ jobs:
with:
node-version: 16.15
- name: Generate release assets
run: npm ci --force && VERSION=${GITHUB_REF#refs/tags/v} npm run build:dist
run: npm ci && VERSION=${GITHUB_REF#refs/tags/v} npm run build:dist
- name: Publish release with assets
uses: docker://antonyurchenko/git-release:latest
env:

View file

@ -2,8 +2,7 @@ FROM node:16.15-alpine as node
COPY . /shlink-web-client
ARG VERSION="latest"
ENV VERSION ${VERSION}
# TODO Remove --force once enzyme was removed
RUN cd /shlink-web-client && npm ci --force && NODE_ENV=production npm run build
RUN cd /shlink-web-client && npm ci && NODE_ENV=production npm run build
FROM nginx:1.21-alpine
LABEL maintainer="Alejandro Celaya <alejandro@alejandrocelaya.com>"

View file

@ -1,4 +0,0 @@
import * as util from 'util';
global.TextEncoder = util.TextEncoder;
global.TextDecoder = util.TextDecoder;

View file

@ -1,4 +0,0 @@
import Enzyme from 'enzyme';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
Enzyme.configure({ adapter: new Adapter() });

View file

@ -15,7 +15,6 @@ module.exports = {
lines: 90,
},
},
setupFiles: ['<rootDir>/config/jest/setupBeforeEnzyme.js', '<rootDir>/config/jest/setupEnzyme.js'],
setupFilesAfterEnv: ['<rootDir>/config/jest/setupTests.ts'],
testMatch: ['<rootDir>/test/**/*.test.{ts,tsx}'],
testEnvironment: 'jsdom',

819
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -75,7 +75,6 @@
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.1.1",
"@testing-library/user-event": "^14.1.1",
"@types/enzyme": "^3.10.11",
"@types/jest": "^27.4.1",
"@types/json2csv": "^5.0.3",
"@types/leaflet": "^1.7.9",
@ -88,11 +87,9 @@
"@types/react-dom": "^18.0.3",
"@types/react-tag-autocomplete": "^6.1.1",
"@types/uuid": "^8.3.4",
"@wojtekmaj/enzyme-adapter-react-17": "0.6.5",
"adm-zip": "^0.5.9",
"babel-jest": "^28.0.3",
"chalk": "^5.0.1",
"enzyme": "^3.11.0",
"eslint": "^8.12.0",
"identity-obj-proxy": "^3.0.0",
"jest": "^28.0.3",

View file

@ -75,7 +75,7 @@ describe('<Tag />', () => {
container.firstElementChild && await user.click(container.firstElementChild);
expect(onClick).toHaveBeenCalledTimes(1);
await user.click(screen.getByLabelText('Close'));
await user.click(screen.getByLabelText(/^Remove/));
expect(onClose).toHaveBeenCalledTimes(1);
});
@ -86,7 +86,7 @@ describe('<Tag />', () => {
])('includes a close component when the tag is clearable', (clearable, expectedCloseBtnAmount, expectedCursor) => {
const { container } = setUp('foo', clearable);
expect(screen.queryAllByLabelText('Close')).toHaveLength(expectedCloseBtnAmount);
expect(screen.queryAllByLabelText(/^Remove/)).toHaveLength(expectedCloseBtnAmount);
expect(container.firstChild).toHaveAttribute('style', expect.stringContaining(`cursor: ${expectedCursor}`));
});

View file

@ -1,168 +1,141 @@
import { shallow, ShallowWrapper } from 'enzyme';
import { screen, waitFor } from '@testing-library/react';
import { Mock } from 'ts-mockery';
import { VisitsTable, VisitsTableProps } from '../../src/visits/VisitsTable';
import { rangeOf } from '../../src/utils/utils';
import { SimplePaginator } from '../../src/common/SimplePaginator';
import { SearchField } from '../../src/utils/SearchField';
import { NormalizedVisit } from '../../src/visits/types';
import { ReachableServer, SelectedServer } from '../../src/servers/data';
import { SemVer } from '../../src/utils/helpers/version';
import { renderWithEvents } from '../__helpers__/setUpTest';
describe('<VisitsTable />', () => {
const matchMedia = () => Mock.of<MediaQueryList>({ matches: false });
const setSelectedVisits = jest.fn();
let wrapper: ShallowWrapper;
const wrapperFactory = (props: Partial<VisitsTableProps> = {}) => {
wrapper = shallow(
<VisitsTable
visits={[]}
selectedServer={Mock.all<SelectedServer>()}
{...props}
matchMedia={matchMedia}
setSelectedVisits={setSelectedVisits}
/>,
);
return wrapper;
};
const createWrapper = (visits: NormalizedVisit[], selectedVisits: NormalizedVisit[] = []) => wrapperFactory(
const setUpFactory = (props: Partial<VisitsTableProps> = {}) => renderWithEvents(
<VisitsTable
visits={[]}
selectedServer={Mock.all<SelectedServer>()}
{...props}
matchMedia={matchMedia}
setSelectedVisits={setSelectedVisits}
/>,
);
const setUp = (visits: NormalizedVisit[], selectedVisits: NormalizedVisit[] = []) => setUpFactory(
{ visits, selectedVisits },
);
const createOrphanVisitsWrapper = (isOrphanVisits: boolean, version: SemVer) => wrapperFactory({
const setUpForOrphanVisits = (isOrphanVisits: boolean, version: SemVer) => setUpFactory({
isOrphanVisits,
selectedServer: Mock.of<ReachableServer>({ printableVersion: version, version }),
});
const createServerVersionWrapper = (version: SemVer) => wrapperFactory({
const setUpForServerVersion = (version: SemVer) => setUpFactory({
selectedServer: Mock.of<ReachableServer>({ printableVersion: version, version }),
});
const createWrapperWithBots = () => wrapperFactory({
const setUpWithBots = () => setUpFactory({
selectedServer: Mock.of<ReachableServer>({ printableVersion: '2.7.0', version: '2.7.0' }),
visits: [
Mock.of<NormalizedVisit>({ potentialBot: false }),
Mock.of<NormalizedVisit>({ potentialBot: true }),
Mock.of<NormalizedVisit>({ potentialBot: false, date: '2022-05-05' }),
Mock.of<NormalizedVisit>({ potentialBot: true, date: '2022-05-05' }),
],
});
afterEach(jest.resetAllMocks);
afterEach(() => wrapper?.unmount());
it.each([
['2.6.0' as SemVer, ['Date', 'Country', 'City', 'Browser', 'OS', 'Referrer']],
['2.7.0' as SemVer, ['fa-robot', 'Date', 'Country', 'City', 'Browser', 'OS', 'Referrer']],
])('renders columns as expected', (version, expectedColumns) => {
const wrapper = createServerVersionWrapper(version);
const th = wrapper.find('thead').find('th');
expect(th).toHaveLength(expectedColumns.length + 1);
expectedColumns.forEach((column, index) => {
expect(th.at(index + 1).html()).toContain(column);
});
['2.6.0' as SemVer, 6],
['2.7.0' as SemVer, 7],
])('renders expected amount of columns', (version, expectedColumns) => {
setUpForServerVersion(version);
expect(screen.getAllByRole('columnheader')).toHaveLength(expectedColumns + 1);
});
it('shows warning when no visits are found', () => {
const wrapper = createWrapper([]);
const td = wrapper.find('tbody').find('td');
expect(td).toHaveLength(1);
expect(td.text()).toContain('No visits found with current filtering');
setUp([]);
expect(screen.getByText('No visits found with current filtering')).toBeInTheDocument();
});
it.each([
[50, 3],
[21, 2],
[30, 2],
[60, 3],
[115, 6],
])('renders the expected amount of pages', (visitsCount, expectedAmountOfPages) => {
const wrapper = createWrapper(
rangeOf(visitsCount, () => Mock.of<NormalizedVisit>({ browser: '', date: '', referer: '' })),
[50, 5, 1],
[21, 4, 1],
[30, 4, 1],
[60, 5, 1],
[115, 7, 2], // This one will have ellipsis
])('renders the expected amount of pages', (visitsCount, expectedAmountOfPageItems, expectedDisabledItems) => {
const { container } = setUp(
rangeOf(visitsCount, () => Mock.of<NormalizedVisit>({ browser: '', date: '2022-01-01', referer: '' })),
);
const tr = wrapper.find('tbody').find('tr');
const paginator = wrapper.find(SimplePaginator);
expect(tr).toHaveLength(20);
expect(paginator.prop('pagesCount')).toEqual(expectedAmountOfPages);
expect(container.querySelectorAll('.page-item')).toHaveLength(expectedAmountOfPageItems);
expect(container.querySelectorAll('.disabled')).toHaveLength(expectedDisabledItems);
});
it.each(
rangeOf(20, (value) => [value]),
)('does not render footer when there is only one page to render', (visitsCount) => {
const wrapper = createWrapper(
rangeOf(visitsCount, () => Mock.of<NormalizedVisit>({ browser: '', date: '', referer: '' })),
const { container } = setUp(
rangeOf(visitsCount, () => Mock.of<NormalizedVisit>({ browser: '', date: '2022-01-01', referer: '' })),
);
const tr = wrapper.find('tbody').find('tr');
const paginator = wrapper.find(SimplePaginator);
expect(tr).toHaveLength(visitsCount);
expect(paginator).toHaveLength(0);
expect(container.querySelector('tfoot')).not.toBeInTheDocument();
expect(screen.queryByLabelText('pagination')).not.toBeInTheDocument();
});
it('selected rows are highlighted', () => {
const visits = rangeOf(10, () => Mock.of<NormalizedVisit>({ browser: '', date: '', referer: '' }));
const wrapper = createWrapper(
visits,
[visits[1], visits[2]],
);
it('selected rows are highlighted', async () => {
const visits = rangeOf(10, () => Mock.of<NormalizedVisit>({ browser: '', date: '2022-01-01', referer: '' }));
const { container, user } = setUp(visits, [visits[1], visits[2]]);
expect(wrapper.find('.text-primary')).toHaveLength(3);
expect(wrapper.find('.table-active')).toHaveLength(2);
// Initial situation
expect(container.querySelectorAll('.table-active')).toHaveLength(2);
// Select one extra
wrapper.find('tr').at(5).simulate('click');
await user.click(screen.getAllByRole('row')[5]);
expect(setSelectedVisits).toHaveBeenCalledWith([visits[1], visits[2], visits[4]]);
// Deselect one
wrapper.find('tr').at(3).simulate('click');
await user.click(screen.getAllByRole('row')[3]);
expect(setSelectedVisits).toHaveBeenCalledWith([visits[1]]);
// Select all
wrapper.find('thead').find('th').at(0).simulate('click');
await user.click(screen.getAllByRole('columnheader')[0]);
expect(setSelectedVisits).toHaveBeenCalledWith(visits);
});
it('orders visits when column is clicked', () => {
const wrapper = createWrapper(rangeOf(9, (index) => Mock.of<NormalizedVisit>({
it('orders visits when column is clicked', async () => {
const { user } = setUp(rangeOf(9, (index) => Mock.of<NormalizedVisit>({
browser: '',
date: `${9 - index}`,
date: `2022-01-0${10 - index}`,
referer: `${index}`,
country: `Country_${index}`,
})));
const getFirstColumnValue = () => screen.getAllByRole('row')[2]?.querySelectorAll('td')[2]?.textContent;
const clickColumn = async (index: number) => user.click(screen.getAllByRole('columnheader')[index]);
expect(wrapper.find('tbody').find('tr').at(0).find('td')
.at(2)
.text()).toContain('Country_1');
wrapper.find('thead').find('th').at(1).simulate('click'); // Date column ASC
expect(wrapper.find('tbody').find('tr').at(0).find('td')
.at(2)
.text()).toContain('Country_9');
wrapper.find('thead').find('th').at(6).simulate('click'); // Referer column - ASC
expect(wrapper.find('tbody').find('tr').at(0).find('td')
.at(2)
.text()).toContain('Country_1');
wrapper.find('thead').find('th').at(6).simulate('click'); // Referer column - DESC
expect(wrapper.find('tbody').find('tr').at(0).find('td')
.at(2)
.text()).toContain('Country_9');
wrapper.find('thead').find('th').at(6).simulate('click'); // Referer column - reset
expect(wrapper.find('tbody').find('tr').at(0).find('td')
.at(2)
.text()).toContain('Country_1');
expect(getFirstColumnValue()).toContain('Country_1');
await clickColumn(1); // Date column ASC
expect(getFirstColumnValue()).toContain('Country_9');
await clickColumn(6); // Referer column - ASC
expect(getFirstColumnValue()).toContain('Country_1');
await clickColumn(6); // Referer column - DESC
expect(getFirstColumnValue()).toContain('Country_9');
await clickColumn(6); // Referer column - reset
expect(getFirstColumnValue()).toContain('Country_1');
});
it('filters list when writing in search box', () => {
const wrapper = createWrapper([
...rangeOf(7, () => Mock.of<NormalizedVisit>({ browser: 'aaa', date: 'aaa', referer: 'aaa' })),
...rangeOf(2, () => Mock.of<NormalizedVisit>({ browser: 'bbb', date: 'bbb', referer: 'bbb' })),
it('filters list when writing in search box', async () => {
const { user } = setUp([
...rangeOf(7, () => Mock.of<NormalizedVisit>({ browser: 'aaa', date: '2022-01-01', referer: 'aaa' })),
...rangeOf(2, () => Mock.of<NormalizedVisit>({ browser: 'bbb', date: '2022-01-01', referer: 'bbb' })),
]);
const searchField = wrapper.find(SearchField);
const searchField = screen.getByPlaceholderText('Search...');
const searchText = async (text: string) => {
await user.clear(searchField);
text.length > 0 && await user.type(searchField, text);
};
expect(wrapper.find('tbody').find('tr')).toHaveLength(7 + 2);
searchField.simulate('change', 'aa');
expect(wrapper.find('tbody').find('tr')).toHaveLength(7);
searchField.simulate('change', 'bb');
expect(wrapper.find('tbody').find('tr')).toHaveLength(2);
searchField.simulate('change', '');
expect(wrapper.find('tbody').find('tr')).toHaveLength(7 + 2);
expect(screen.getAllByRole('row')).toHaveLength(9 + 2);
await searchText('aa');
await waitFor(() => expect(screen.getAllByRole('row')).toHaveLength(7 + 2));
await searchText('bb');
await waitFor(() => expect(screen.getAllByRole('row')).toHaveLength(2 + 2));
await searchText('');
await waitFor(() => expect(screen.getAllByRole('row')).toHaveLength(9 + 2));
});
it.each([
@ -171,20 +144,15 @@ describe('<VisitsTable />', () => {
[true, '2.7.0' as SemVer, 9],
[false, '2.7.0' as SemVer, 8],
])('displays proper amount of columns for orphan and non-orphan visits', (isOrphanVisits, version, expectedCols) => {
const wrapper = createOrphanVisitsWrapper(isOrphanVisits, version);
const rowsWithColspan = wrapper.find('[colSpan]');
const cols = wrapper.find('th');
expect(cols).toHaveLength(expectedCols);
expect(rowsWithColspan).toHaveLength(2);
rowsWithColspan.forEach((row) => expect(row.prop('colSpan')).toEqual(expectedCols));
setUpForOrphanVisits(isOrphanVisits, version);
expect(screen.getAllByRole('columnheader')).toHaveLength(expectedCols);
});
it('displays bots icon when a visit is a potential bot', () => {
const wrapper = createWrapperWithBots();
const rows = wrapper.find('tbody').find('tr');
setUpWithBots();
const [,, nonBotVisitRow, botVisitRow] = screen.getAllByRole('row');
expect(rows.at(0).find('td').at(1).text()).not.toContain('FontAwesomeIcon');
expect(rows.at(1).find('td').at(1).text()).toContain('FontAwesomeIcon');
expect(nonBotVisitRow.querySelectorAll('td')[1]).toBeEmptyDOMElement();
expect(botVisitRow.querySelectorAll('td')[1]).not.toBeEmptyDOMElement();
});
});