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 node-version: 16.15
- name: Build - name: Build
run: | run: |
npm ci --force && \ npm ci && \
node ./scripts/set-homepage.js /shlink-web-client/${GITHUB_HEAD_REF#refs/heads/} && \ node ./scripts/set-homepage.js /shlink-web-client/${GITHUB_HEAD_REF#refs/heads/} && \
rm src/service-worker.ts && \ rm src/service-worker.ts && \
npm run build npm run build

View file

@ -16,7 +16,7 @@ jobs:
with: with:
node-version: 16.15 node-version: 16.15
- name: Generate release assets - 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 - name: Publish release with assets
uses: docker://antonyurchenko/git-release:latest uses: docker://antonyurchenko/git-release:latest
env: env:

View file

@ -2,8 +2,7 @@ FROM node:16.15-alpine as node
COPY . /shlink-web-client COPY . /shlink-web-client
ARG VERSION="latest" ARG VERSION="latest"
ENV VERSION ${VERSION} ENV VERSION ${VERSION}
# TODO Remove --force once enzyme was removed RUN cd /shlink-web-client && npm ci && NODE_ENV=production npm run build
RUN cd /shlink-web-client && npm ci --force && NODE_ENV=production npm run build
FROM nginx:1.21-alpine FROM nginx:1.21-alpine
LABEL maintainer="Alejandro Celaya <alejandro@alejandrocelaya.com>" 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, lines: 90,
}, },
}, },
setupFiles: ['<rootDir>/config/jest/setupBeforeEnzyme.js', '<rootDir>/config/jest/setupEnzyme.js'],
setupFilesAfterEnv: ['<rootDir>/config/jest/setupTests.ts'], setupFilesAfterEnv: ['<rootDir>/config/jest/setupTests.ts'],
testMatch: ['<rootDir>/test/**/*.test.{ts,tsx}'], testMatch: ['<rootDir>/test/**/*.test.{ts,tsx}'],
testEnvironment: 'jsdom', 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/jest-dom": "^5.16.4",
"@testing-library/react": "^13.1.1", "@testing-library/react": "^13.1.1",
"@testing-library/user-event": "^14.1.1", "@testing-library/user-event": "^14.1.1",
"@types/enzyme": "^3.10.11",
"@types/jest": "^27.4.1", "@types/jest": "^27.4.1",
"@types/json2csv": "^5.0.3", "@types/json2csv": "^5.0.3",
"@types/leaflet": "^1.7.9", "@types/leaflet": "^1.7.9",
@ -88,11 +87,9 @@
"@types/react-dom": "^18.0.3", "@types/react-dom": "^18.0.3",
"@types/react-tag-autocomplete": "^6.1.1", "@types/react-tag-autocomplete": "^6.1.1",
"@types/uuid": "^8.3.4", "@types/uuid": "^8.3.4",
"@wojtekmaj/enzyme-adapter-react-17": "0.6.5",
"adm-zip": "^0.5.9", "adm-zip": "^0.5.9",
"babel-jest": "^28.0.3", "babel-jest": "^28.0.3",
"chalk": "^5.0.1", "chalk": "^5.0.1",
"enzyme": "^3.11.0",
"eslint": "^8.12.0", "eslint": "^8.12.0",
"identity-obj-proxy": "^3.0.0", "identity-obj-proxy": "^3.0.0",
"jest": "^28.0.3", "jest": "^28.0.3",

View file

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