mirror of
https://github.com/shlinkio/shlink-web-client.git
synced 2025-01-10 18:27:25 +03:00
Merge pull request #689 from acelaya-forks/feature/testing-lib
Feature/testing lib
This commit is contained in:
commit
5d288de390
20 changed files with 265 additions and 1190 deletions
2
.github/workflows/deploy-preview.yml
vendored
2
.github/workflows/deploy-preview.yml
vendored
|
@ -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
|
||||
|
|
2
.github/workflows/publish-release.yml
vendored
2
.github/workflows/publish-release.yml
vendored
|
@ -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:
|
||||
|
|
|
@ -9,7 +9,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|||
* [#671](https://github.com/shlinkio/shlink-web-client/pull/671) Added proper color-scheme in root element based on selected theme.
|
||||
|
||||
### Changed
|
||||
* *Nothing*
|
||||
* [#688](https://github.com/shlinkio/shlink-web-client/pull/688) Finalized migration from enzyme to react-testing-library.
|
||||
|
||||
### Deprecated
|
||||
* *Nothing*
|
||||
|
|
|
@ -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>"
|
||||
|
|
|
@ -1,4 +0,0 @@
|
|||
import * as util from 'util';
|
||||
|
||||
global.TextEncoder = util.TextEncoder;
|
||||
global.TextDecoder = util.TextDecoder;
|
|
@ -1,4 +0,0 @@
|
|||
import Enzyme from 'enzyme';
|
||||
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
|
||||
|
||||
Enzyme.configure({ adapter: new Adapter() });
|
|
@ -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
819
package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
@ -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",
|
||||
|
|
|
@ -34,7 +34,7 @@ export const EditTagModal = ({ getColorForKey }: ColorGenerator) => (
|
|||
|
||||
return (
|
||||
<Modal isOpen={isOpen} toggle={toggle} centered onClosed={hideColorPicker}>
|
||||
<form onSubmit={saveTag}>
|
||||
<form name="editTag" onSubmit={saveTag}>
|
||||
<ModalHeader toggle={toggle}>Edit tag</ModalHeader>
|
||||
<ModalBody>
|
||||
<InputGroup>
|
||||
|
|
|
@ -19,6 +19,8 @@ export const Tag: FC<TagProps> = ({ text, children, clearable, className = '', c
|
|||
onClick={onClick}
|
||||
>
|
||||
{children ?? text}
|
||||
{clearable && <span aria-label="Close" className="close tag__close-selected-tag" onClick={onClose}>×</span>}
|
||||
{clearable && (
|
||||
<span aria-label={`Remove ${text}`} className="close tag__close-selected-tag" onClick={onClose}>×</span>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
|
|
|
@ -139,7 +139,7 @@ export const VisitsStats: FC<VisitsStatsProps> = ({
|
|||
}
|
||||
|
||||
if (isEmpty(visits)) {
|
||||
return <Message>There are no visits matching current filter :(</Message>;
|
||||
return <Message>There are no visits matching current filter</Message>;
|
||||
}
|
||||
|
||||
return (
|
||||
|
|
|
@ -2,15 +2,15 @@ import { screen } from '@testing-library/react';
|
|||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { Mock } from 'ts-mockery';
|
||||
import { TagCard as createTagCard } from '../../src/tags/TagCard';
|
||||
import { ColorGenerator } from '../../src/utils/services/ColorGenerator';
|
||||
import { ReachableServer } from '../../src/servers/data';
|
||||
import { renderWithEvents } from '../__helpers__/setUpTest';
|
||||
import { colorGeneratorMock } from '../utils/services/__mocks__/ColorGenerator.mock';
|
||||
|
||||
describe('<TagCard />', () => {
|
||||
const TagCard = createTagCard(
|
||||
({ isOpen }) => <span>DeleteTagConfirmModal {isOpen ? '[Open]' : '[Closed]'}</span>,
|
||||
({ isOpen }) => <span>EditTagModal {isOpen ? '[Open]' : '[Closed]'}</span>,
|
||||
Mock.of<ColorGenerator>({ getColorForKey: () => '' }),
|
||||
colorGeneratorMock,
|
||||
);
|
||||
const setUp = (tag = 'ssr') => renderWithEvents(
|
||||
<MemoryRouter>
|
||||
|
|
|
@ -1,46 +1,34 @@
|
|||
import { shallow, ShallowWrapper } from 'enzyme';
|
||||
import { screen, waitFor } from '@testing-library/react';
|
||||
import { Mock } from 'ts-mockery';
|
||||
import { Button, Input, Modal, ModalHeader, Popover } from 'reactstrap';
|
||||
import { HexColorPicker } from 'react-colorful';
|
||||
import { TagEdition } from '../../../src/tags/reducers/tagEdit';
|
||||
import { EditTagModal as createEditTagModal } from '../../../src/tags/helpers/EditTagModal';
|
||||
import { ColorGenerator } from '../../../src/utils/services/ColorGenerator';
|
||||
import { Result } from '../../../src/utils/Result';
|
||||
import { ProblemDetailsError } from '../../../src/api/types';
|
||||
import { ShlinkApiError } from '../../../src/api/ShlinkApiError';
|
||||
import { renderWithEvents } from '../../__helpers__/setUpTest';
|
||||
|
||||
describe('<EditTagModal />', () => {
|
||||
const EditTagModal = createEditTagModal(Mock.of<ColorGenerator>({ getColorForKey: jest.fn(() => 'red') }));
|
||||
const EditTagModal = createEditTagModal(Mock.of<ColorGenerator>({ getColorForKey: jest.fn(() => 'green') }));
|
||||
const editTag = jest.fn().mockReturnValue(Promise.resolve());
|
||||
const tagEdited = jest.fn().mockReturnValue(Promise.resolve());
|
||||
const toggle = jest.fn();
|
||||
let wrapper: ShallowWrapper;
|
||||
const createWrapper = (tagEdit: Partial<TagEdition> = {}) => {
|
||||
const setUp = (tagEdit: Partial<TagEdition> = {}) => {
|
||||
const edition = Mock.of<TagEdition>(tagEdit);
|
||||
|
||||
wrapper = shallow(
|
||||
return renderWithEvents(
|
||||
<EditTagModal isOpen tag="foo" tagEdit={edition} editTag={editTag} tagEdited={tagEdited} toggle={toggle} />,
|
||||
);
|
||||
|
||||
return wrapper;
|
||||
};
|
||||
|
||||
afterEach(jest.clearAllMocks);
|
||||
afterEach(() => wrapper?.unmount());
|
||||
|
||||
it('allows modal to be toggled with different mechanisms', () => {
|
||||
const wrapper = createWrapper();
|
||||
const modal = wrapper.find(Modal);
|
||||
const modalHeader = wrapper.find(ModalHeader);
|
||||
const cancelBtn = wrapper.find(Button).findWhere((btn) => btn.prop('type') === 'button');
|
||||
it('allows modal to be toggled with different mechanisms', async () => {
|
||||
const { user } = setUp();
|
||||
|
||||
expect(toggle).not.toHaveBeenCalled();
|
||||
|
||||
(modal.prop('toggle') as Function)();
|
||||
(modalHeader.prop('toggle') as Function)();
|
||||
cancelBtn.simulate('click');
|
||||
await user.click(screen.getByLabelText('Close'));
|
||||
await user.click(screen.getByRole('button', { name: 'Cancel' }));
|
||||
|
||||
expect(toggle).toHaveBeenCalledTimes(3);
|
||||
expect(toggle).toHaveBeenCalledTimes(2);
|
||||
expect(editTag).not.toHaveBeenCalled();
|
||||
expect(tagEdited).not.toHaveBeenCalled();
|
||||
});
|
||||
|
@ -48,62 +36,54 @@ describe('<EditTagModal />', () => {
|
|||
it.each([
|
||||
[true, 'Saving...'],
|
||||
[false, 'Save'],
|
||||
])('renders submit button in expected state', (editing, expectedText) => {
|
||||
const wrapper = createWrapper({ editing });
|
||||
const submitBtn = wrapper.find(Button).findWhere((btn) => btn.prop('color') === 'primary');
|
||||
|
||||
expect(submitBtn.html()).toContain(expectedText);
|
||||
expect(submitBtn.prop('disabled')).toEqual(editing);
|
||||
])('renders submit button in expected state', (editing, name) => {
|
||||
setUp({ editing });
|
||||
expect(screen.getByRole('button', { name })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each([
|
||||
[true, 1],
|
||||
[false, 0],
|
||||
])('displays error result in case of error', (error, expectedResultCount) => {
|
||||
const wrapper = createWrapper({ error, errorData: Mock.all<ProblemDetailsError>() });
|
||||
const result = wrapper.find(Result);
|
||||
const apiError = wrapper.find(ShlinkApiError);
|
||||
|
||||
expect(result).toHaveLength(expectedResultCount);
|
||||
expect(apiError).toHaveLength(expectedResultCount);
|
||||
setUp({ error, errorData: Mock.all<ProblemDetailsError>() });
|
||||
expect(screen.queryAllByText('Something went wrong while editing the tag :(')).toHaveLength(expectedResultCount);
|
||||
});
|
||||
|
||||
it('updates tag value when text changes', () => {
|
||||
const wrapper = createWrapper();
|
||||
it('updates tag value when text changes', async () => {
|
||||
const { user } = setUp();
|
||||
const getInput = () => screen.getByPlaceholderText('Tag');
|
||||
|
||||
expect(wrapper.find(Input).prop('value')).toEqual('foo');
|
||||
wrapper.find(Input).simulate('change', { target: { value: 'bar' } });
|
||||
expect(wrapper.find(Input).prop('value')).toEqual('bar');
|
||||
expect(getInput()).toHaveValue('foo');
|
||||
await user.clear(getInput());
|
||||
await user.type(getInput(), 'bar');
|
||||
expect(getInput()).toHaveValue('bar');
|
||||
});
|
||||
|
||||
it('invokes all functions on form submit', async () => {
|
||||
const wrapper = createWrapper();
|
||||
const form = wrapper.find('form');
|
||||
const { user } = setUp();
|
||||
|
||||
expect(editTag).not.toHaveBeenCalled();
|
||||
expect(tagEdited).not.toHaveBeenCalled();
|
||||
|
||||
await form.simulate('submit', { preventDefault: jest.fn() });
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
|
||||
expect(editTag).toHaveBeenCalled();
|
||||
expect(tagEdited).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('changes color when changing on color picker', () => {
|
||||
const wrapper = createWrapper();
|
||||
it('changes color when changing on color picker', async () => {
|
||||
const { user } = setUp();
|
||||
const colorBtn = screen.getByRole('img', { hidden: true });
|
||||
// const initialColor = colorBtn.parentElement?.style.backgroundColor;
|
||||
|
||||
expect(wrapper.find(HexColorPicker).prop('color')).toEqual('red');
|
||||
wrapper.find(HexColorPicker).simulate('change', 'blue');
|
||||
expect(wrapper.find(HexColorPicker).prop('color')).toEqual('blue');
|
||||
});
|
||||
await user.click(colorBtn);
|
||||
await waitFor(() => screen.getByRole('tooltip'));
|
||||
await user.click(screen.getByLabelText('Hue'));
|
||||
await user.click(screen.getByLabelText('Color'));
|
||||
await user.click(colorBtn);
|
||||
await waitFor(() => expect(screen.queryByRole('tooltip')).not.toBeInTheDocument());
|
||||
|
||||
it('allows toggling popover with different mechanisms', () => {
|
||||
const wrapper = createWrapper();
|
||||
|
||||
expect(wrapper.find(Popover).prop('isOpen')).toEqual(false);
|
||||
(wrapper.find(Popover).prop('toggle') as Function)();
|
||||
expect(wrapper.find(Popover).prop('isOpen')).toEqual(true);
|
||||
wrapper.find('div').simulate('click');
|
||||
expect(wrapper.find(Popover).prop('isOpen')).toEqual(false);
|
||||
// I need to figure this one out
|
||||
// await waitFor(() => expect(initialColor).not.toEqual(colorBtn.parentElement?.style.backgroundColor));
|
||||
});
|
||||
});
|
||||
|
|
|
@ -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}`));
|
||||
});
|
||||
|
||||
|
|
|
@ -1,77 +1,81 @@
|
|||
import { shallow, ShallowWrapper } from 'enzyme';
|
||||
import { screen } from '@testing-library/react';
|
||||
import { Mock } from 'ts-mockery';
|
||||
import { TagsSelector as createTagsSelector } from '../../../src/tags/helpers/TagsSelector';
|
||||
import { ColorGenerator } from '../../../src/utils/services/ColorGenerator';
|
||||
import { TagsList } from '../../../src/tags/reducers/tagsList';
|
||||
import { Settings } from '../../../src/settings/reducers/settings';
|
||||
import { renderWithEvents } from '../../__helpers__/setUpTest';
|
||||
import { colorGeneratorMock } from '../../utils/services/__mocks__/ColorGenerator.mock';
|
||||
|
||||
describe('<TagsSelector />', () => {
|
||||
const onChange = jest.fn();
|
||||
const TagsSelector = createTagsSelector(Mock.all<ColorGenerator>());
|
||||
const TagsSelector = createTagsSelector(colorGeneratorMock);
|
||||
const tags = ['foo', 'bar'];
|
||||
const tagsList = Mock.of<TagsList>({ tags: [...tags, 'baz'] });
|
||||
let wrapper: ShallowWrapper;
|
||||
const setUp = () => renderWithEvents(
|
||||
<TagsSelector
|
||||
selectedTags={tags}
|
||||
tagsList={tagsList}
|
||||
settings={Mock.all<Settings>()}
|
||||
listTags={jest.fn()}
|
||||
onChange={onChange}
|
||||
/>,
|
||||
);
|
||||
|
||||
beforeEach(jest.clearAllMocks);
|
||||
beforeEach(() => {
|
||||
wrapper = shallow(
|
||||
<TagsSelector
|
||||
selectedTags={tags}
|
||||
tagsList={tagsList}
|
||||
settings={Mock.all<Settings>()}
|
||||
listTags={jest.fn()}
|
||||
onChange={onChange}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
afterEach(jest.clearAllMocks);
|
||||
|
||||
afterEach(() => wrapper?.unmount());
|
||||
|
||||
it('has expected props', () => {
|
||||
expect(wrapper.prop('placeholderText')).toEqual('Add tags to the URL');
|
||||
expect(wrapper.prop('allowNew')).toEqual(true);
|
||||
expect(wrapper.prop('addOnBlur')).toEqual(true);
|
||||
expect(wrapper.prop('minQueryLength')).toEqual(1);
|
||||
it('has an input for tags', () => {
|
||||
setUp();
|
||||
expect(screen.getByPlaceholderText('Add tags to the URL')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('contains expected tags', () => {
|
||||
expect(wrapper.prop('tags')).toEqual([
|
||||
{
|
||||
id: 'foo',
|
||||
name: 'foo',
|
||||
},
|
||||
{
|
||||
id: 'bar',
|
||||
name: 'bar',
|
||||
},
|
||||
]);
|
||||
setUp();
|
||||
|
||||
expect(screen.getByText('foo')).toBeInTheDocument();
|
||||
expect(screen.getByText('bar')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('contains expected suggestions', () => {
|
||||
expect(wrapper.prop('suggestions')).toEqual([
|
||||
{
|
||||
id: 'baz',
|
||||
name: 'baz',
|
||||
},
|
||||
]);
|
||||
it('contains expected suggestions', async () => {
|
||||
const { container, user } = setUp();
|
||||
|
||||
expect(container.querySelector('.react-tags__suggestions')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('baz')).not.toBeInTheDocument();
|
||||
|
||||
await user.type(screen.getByPlaceholderText('Add tags to the URL'), 'ba');
|
||||
|
||||
expect(container.querySelector('.react-tags__suggestions')).toBeInTheDocument();
|
||||
expect(screen.getByText('baz')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['The-New-Tag', [...tags, 'the-new-tag']],
|
||||
['comma,separated,tags', [...tags, 'comma', 'separated', 'tags']],
|
||||
['foo', tags],
|
||||
])('invokes onChange when new tags are added', (newTag, expectedTags) => {
|
||||
wrapper.simulate('addition', { name: newTag });
|
||||
])('invokes onChange when new tags are added', async (newTag, expectedTags) => {
|
||||
const { user } = setUp();
|
||||
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
await user.type(screen.getByPlaceholderText('Add tags to the URL'), newTag);
|
||||
await user.type(screen.getByPlaceholderText('Add tags to the URL'), '{Enter}');
|
||||
expect(onChange).toHaveBeenCalledWith(expectedTags);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[0, 'bar'],
|
||||
[1, 'foo'],
|
||||
])('invokes onChange when tags are deleted', (index, expected) => {
|
||||
wrapper.simulate('delete', index);
|
||||
it('splits tags when several comma-separated ones are pasted', async () => {
|
||||
const { user } = setUp();
|
||||
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
await user.click(screen.getByPlaceholderText('Add tags to the URL'));
|
||||
await user.paste('comma,separated,tags');
|
||||
await user.type(screen.getByPlaceholderText('Add tags to the URL'), '{Enter}');
|
||||
expect(onChange).toHaveBeenCalledWith([...tags, 'comma', 'separated', 'tags']);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['foo', 'bar'],
|
||||
['bar', 'foo'],
|
||||
])('invokes onChange when tags are deleted', async (removedLabel, expected) => {
|
||||
const { user } = setUp();
|
||||
|
||||
await user.click(screen.getByLabelText(`Remove ${removedLabel}`));
|
||||
expect(onChange).toHaveBeenCalledWith([expected]);
|
||||
});
|
||||
});
|
||||
|
|
|
@ -1,48 +1,39 @@
|
|||
import { shallow, ShallowWrapper } from 'enzyme';
|
||||
import { screen } from '@testing-library/react';
|
||||
import { Mock } from 'ts-mockery';
|
||||
import { ButtonDropdown, DropdownMenu, DropdownToggle } from 'reactstrap';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import { faEllipsisV as menuIcon } from '@fortawesome/free-solid-svg-icons';
|
||||
import { DropdownBtnMenu, DropdownBtnMenuProps } from '../../src/utils/DropdownBtnMenu';
|
||||
import { renderWithEvents } from '../__helpers__/setUpTest';
|
||||
|
||||
describe('<DropdownBtnMenu />', () => {
|
||||
let wrapper: ShallowWrapper;
|
||||
const createWrapper = (props: Partial<DropdownBtnMenuProps>) => {
|
||||
wrapper = shallow(<DropdownBtnMenu {...Mock.of<DropdownBtnMenuProps>(props)}>the children</DropdownBtnMenu>);
|
||||
|
||||
return wrapper;
|
||||
};
|
||||
|
||||
afterAll(() => wrapper?.unmount());
|
||||
const setUp = (props: Partial<DropdownBtnMenuProps> = {}) => renderWithEvents(
|
||||
<DropdownBtnMenu {...Mock.of<DropdownBtnMenuProps>({ toggle: jest.fn(), ...props })}>the children</DropdownBtnMenu>,
|
||||
);
|
||||
|
||||
it('renders expected components', () => {
|
||||
const wrapper = createWrapper({});
|
||||
const toggle = wrapper.find(DropdownToggle);
|
||||
const icon = wrapper.find(FontAwesomeIcon);
|
||||
setUp();
|
||||
const toggle = screen.getByRole('button');
|
||||
|
||||
expect(wrapper.find(ButtonDropdown)).toHaveLength(1);
|
||||
expect(toggle).toHaveLength(1);
|
||||
expect(toggle.prop('size')).toEqual('sm');
|
||||
expect(toggle.prop('caret')).toEqual(true);
|
||||
expect(toggle.prop('outline')).toEqual(true);
|
||||
expect(toggle.prop('className')).toEqual('dropdown-btn-menu__dropdown-toggle');
|
||||
expect(icon).toHaveLength(1);
|
||||
expect(icon.prop('icon')).toEqual(menuIcon);
|
||||
expect(toggle).toBeInTheDocument();
|
||||
expect(toggle).toHaveClass('btn-sm');
|
||||
expect(toggle).toHaveClass('dropdown-btn-menu__dropdown-toggle');
|
||||
expect(screen.getByRole('img', { hidden: true })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders expected children', () => {
|
||||
const menu = createWrapper({}).find(DropdownMenu);
|
||||
|
||||
expect(menu.prop('children')).toEqual('the children');
|
||||
setUp();
|
||||
expect(screen.getByText('the children')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each([
|
||||
[undefined, true],
|
||||
[true, true],
|
||||
[false, false],
|
||||
])('renders menu to right when expected', (right, expectedRight) => {
|
||||
const wrapper = createWrapper({ right });
|
||||
])('renders menu to the end when expected', (right, expectedEnd) => {
|
||||
setUp({ right });
|
||||
|
||||
expect(wrapper.find(DropdownMenu).prop('end')).toEqual(expectedRight);
|
||||
if (expectedEnd) {
|
||||
expect(screen.getByRole('menu', { hidden: true })).toHaveClass('dropdown-menu-end');
|
||||
} else {
|
||||
expect(screen.getByRole('menu', { hidden: true })).not.toHaveClass('dropdown-menu-end');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
|
@ -1,39 +1,34 @@
|
|||
import { shallow, ShallowWrapper } from 'enzyme';
|
||||
import { screen } from '@testing-library/react';
|
||||
import { DateRangeRow } from '../../../src/utils/dates/DateRangeRow';
|
||||
import { DateInput } from '../../../src/utils/DateInput';
|
||||
import { renderWithEvents } from '../../__helpers__/setUpTest';
|
||||
|
||||
describe('<DateRangeRow />', () => {
|
||||
let wrapper: ShallowWrapper;
|
||||
const onEndDateChange = jest.fn();
|
||||
const onStartDateChange = jest.fn();
|
||||
const setUp = () => renderWithEvents(
|
||||
<DateRangeRow onEndDateChange={onEndDateChange} onStartDateChange={onStartDateChange} />,
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
wrapper = shallow(<DateRangeRow onEndDateChange={onEndDateChange} onStartDateChange={onStartDateChange} />);
|
||||
});
|
||||
afterEach(() => {
|
||||
wrapper.unmount();
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
afterEach(jest.clearAllMocks);
|
||||
|
||||
it('renders two date inputs', () => {
|
||||
const dateInput = wrapper.find(DateInput);
|
||||
|
||||
expect(dateInput).toHaveLength(2);
|
||||
setUp();
|
||||
expect(screen.getAllByRole('textbox')).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('invokes start date callback when change event is triggered on first input', () => {
|
||||
const dateInput = wrapper.find(DateInput).first();
|
||||
it('invokes start date callback when change event is triggered on first input', async () => {
|
||||
const { user } = setUp();
|
||||
|
||||
expect(onStartDateChange).not.toHaveBeenCalled();
|
||||
dateInput.simulate('change');
|
||||
await user.type(screen.getByPlaceholderText('Since...'), '2020-05-05');
|
||||
expect(onStartDateChange).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('invokes end date callback when change event is triggered on second input', () => {
|
||||
const dateInput = wrapper.find(DateInput).last();
|
||||
it('invokes end date callback when change event is triggered on second input', async () => {
|
||||
const { user } = setUp();
|
||||
|
||||
expect(onEndDateChange).not.toHaveBeenCalled();
|
||||
dateInput.simulate('change');
|
||||
await user.type(screen.getByPlaceholderText('Until...'), '2022-05-05');
|
||||
expect(onEndDateChange).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
|
|
@ -1,116 +1,83 @@
|
|||
import { shallow, ShallowWrapper } from 'enzyme';
|
||||
import { Progress } from 'reactstrap';
|
||||
import { sum } from 'ramda';
|
||||
import { screen } from '@testing-library/react';
|
||||
import { Mock } from 'ts-mockery';
|
||||
import { Route } from 'react-router-dom';
|
||||
import { Router } from 'react-router-dom';
|
||||
import { createMemoryHistory } from 'history';
|
||||
import { VisitsStats } from '../../src/visits/VisitsStats';
|
||||
import { Message } from '../../src/utils/Message';
|
||||
import { Visit, VisitsInfo } from '../../src/visits/types';
|
||||
import { LineChartCard } from '../../src/visits/charts/LineChartCard';
|
||||
import { VisitsTable } from '../../src/visits/VisitsTable';
|
||||
import { Result } from '../../src/utils/Result';
|
||||
import { Settings } from '../../src/settings/reducers/settings';
|
||||
import { SelectedServer } from '../../src/servers/data';
|
||||
import { SortableBarChartCard } from '../../src/visits/charts/SortableBarChartCard';
|
||||
import { DoughnutChartCard } from '../../src/visits/charts/DoughnutChartCard';
|
||||
import { ExportBtn } from '../../src/utils/ExportBtn';
|
||||
import { renderWithEvents } from '../__helpers__/setUpTest';
|
||||
import { rangeOf } from '../../src/utils/utils';
|
||||
|
||||
describe('<VisitsStats />', () => {
|
||||
const visits = [Mock.all<Visit>(), Mock.all<Visit>(), Mock.all<Visit>()];
|
||||
|
||||
let wrapper: ShallowWrapper;
|
||||
const visits = rangeOf(3, () => Mock.of<Visit>({ date: '2020-01-01' }));
|
||||
const getVisitsMock = jest.fn();
|
||||
const exportCsv = jest.fn();
|
||||
const setUp = (visitsInfo: Partial<VisitsInfo>, activeRoute = '/by-time') => {
|
||||
const history = createMemoryHistory();
|
||||
history.push(activeRoute);
|
||||
|
||||
const createComponent = (visitsInfo: Partial<VisitsInfo>) => {
|
||||
wrapper = shallow(
|
||||
<VisitsStats
|
||||
getVisits={getVisitsMock}
|
||||
visitsInfo={Mock.of<VisitsInfo>(visitsInfo)}
|
||||
cancelGetVisits={() => {}}
|
||||
settings={Mock.all<Settings>()}
|
||||
exportCsv={exportCsv}
|
||||
selectedServer={Mock.all<SelectedServer>()}
|
||||
/>,
|
||||
return renderWithEvents(
|
||||
<Router location={history.location} navigator={history}>
|
||||
<VisitsStats
|
||||
getVisits={getVisitsMock}
|
||||
visitsInfo={Mock.of<VisitsInfo>(visitsInfo)}
|
||||
cancelGetVisits={() => {}}
|
||||
settings={Mock.all<Settings>()}
|
||||
exportCsv={exportCsv}
|
||||
selectedServer={Mock.all<SelectedServer>()}
|
||||
/>
|
||||
</Router>,
|
||||
);
|
||||
|
||||
return wrapper;
|
||||
};
|
||||
|
||||
afterEach(() => wrapper?.unmount());
|
||||
|
||||
it('renders a preloader when visits are loading', () => {
|
||||
const wrapper = createComponent({ loading: true, visits: [] });
|
||||
const loadingMessage = wrapper.find(Message);
|
||||
const progress = wrapper.find(Progress);
|
||||
setUp({ loading: true, visits: [] });
|
||||
|
||||
expect(loadingMessage).toHaveLength(1);
|
||||
expect(loadingMessage.html()).toContain('Loading...');
|
||||
expect(progress).toHaveLength(0);
|
||||
expect(screen.getByText('Loading...')).toBeInTheDocument();
|
||||
expect(screen.queryByText(/^This is going to take a while/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders a warning and progress bar when loading large amounts of visits', () => {
|
||||
const wrapper = createComponent({ loading: true, loadingLarge: true, visits: [], progress: 25 });
|
||||
const loadingMessage = wrapper.find(Message);
|
||||
const progress = wrapper.find(Progress);
|
||||
setUp({ loading: true, loadingLarge: true, visits: [], progress: 25 });
|
||||
|
||||
expect(loadingMessage).toHaveLength(1);
|
||||
expect(loadingMessage.html()).toContain('This is going to take a while... :S');
|
||||
expect(progress).toHaveLength(1);
|
||||
expect(progress.prop('value')).toEqual(25);
|
||||
expect(screen.queryByText('Loading...')).not.toBeInTheDocument();
|
||||
expect(screen.getByText(/^This is going to take a while/)).toBeInTheDocument();
|
||||
expect(screen.getByRole('progressbar')).toHaveAttribute('aria-valuenow', '25');
|
||||
});
|
||||
|
||||
it('renders an error message when visits could not be loaded', () => {
|
||||
const wrapper = createComponent({ loading: false, error: true, visits: [] });
|
||||
const errorMessage = wrapper.find(Result).filterWhere((result) => result.prop('type') === 'error');
|
||||
|
||||
expect(errorMessage).toHaveLength(1);
|
||||
expect(errorMessage.html()).toContain('An error occurred while loading visits :(');
|
||||
setUp({ loading: false, error: true, visits: [] });
|
||||
expect(screen.getByText('An error occurred while loading visits :(')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders a message when visits are loaded but the list is empty', () => {
|
||||
const wrapper = createComponent({ loading: false, error: false, visits: [] });
|
||||
const message = wrapper.find(Message);
|
||||
|
||||
expect(message).toHaveLength(1);
|
||||
expect(message.html()).toContain('There are no visits matching current filter :(');
|
||||
setUp({ loading: false, error: false, visits: [] });
|
||||
expect(screen.getByText('There are no visits matching current filter')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders expected amount of charts', () => {
|
||||
const wrapper = createComponent({ loading: false, error: false, visits });
|
||||
const total = sum(wrapper.find(Route).map((element) => {
|
||||
const ElementComponents = () => element.prop('element');
|
||||
// @ts-expect-error Wrapped element
|
||||
const wrappedElement = shallow(<ElementComponents />);
|
||||
|
||||
const charts = wrappedElement.find(DoughnutChartCard);
|
||||
const sortableCharts = wrappedElement.find(SortableBarChartCard);
|
||||
const lineChart = wrappedElement.find(LineChartCard);
|
||||
const table = wrappedElement.find(VisitsTable);
|
||||
|
||||
return charts.length + sortableCharts.length + lineChart.length + table.length;
|
||||
}));
|
||||
|
||||
expect(total).toEqual(7);
|
||||
it.each([
|
||||
['/by-time', 2],
|
||||
['/by-context', 4],
|
||||
['/by-location', 3],
|
||||
['/list', 1],
|
||||
])('renders expected amount of charts', (route, expectedCharts) => {
|
||||
const { container } = setUp({ loading: false, error: false, visits }, route);
|
||||
expect(container.querySelectorAll('.card')).toHaveLength(expectedCharts);
|
||||
});
|
||||
|
||||
it('holds the map button content generator on cities chart extraHeaderContent', () => {
|
||||
const wrapper = createComponent({ loading: false, error: false, visits });
|
||||
const ElementComponent = () => wrapper.find(Route).findWhere((element) => element.prop('path') === 'by-location')
|
||||
.prop('element');
|
||||
const citiesChart = shallow(<ElementComponent />).find(SortableBarChartCard).find('[title="Cities"]');
|
||||
const extraHeaderContent = citiesChart.prop('extraHeaderContent');
|
||||
|
||||
expect(extraHeaderContent).toHaveLength(1);
|
||||
expect(typeof extraHeaderContent).toEqual('function');
|
||||
it('holds the map button on cities chart header', () => {
|
||||
setUp({ loading: false, error: false, visits }, '/by-location');
|
||||
expect(
|
||||
screen.getAllByRole('img', { hidden: true }).some((icon) => icon.classList.contains('fa-map-location-dot')),
|
||||
).toEqual(true);
|
||||
});
|
||||
|
||||
it('exports CSV when export btn is clicked', () => {
|
||||
const wrapper = createComponent({ visits });
|
||||
const exportBtn = wrapper.find(ExportBtn).last();
|
||||
it('exports CSV when export btn is clicked', async () => {
|
||||
const { user } = setUp({ visits });
|
||||
|
||||
expect(exportBtn).toHaveLength(1);
|
||||
exportBtn.simulate('click');
|
||||
expect(exportCsv).not.toHaveBeenCalled();
|
||||
await user.click(screen.getByRole('button', { name: /Export/ }));
|
||||
expect(exportCsv).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
|
|
@ -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();
|
||||
});
|
||||
});
|
||||
|
|
Loading…
Reference in a new issue