Merge pull request #661 from acelaya-forks/feature/here-we-go-again

Feature/here we go again
This commit is contained in:
Alejandro Celaya 2022-06-04 19:18:18 +02:00 committed by GitHub
commit 4defeaf017
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 64 additions and 83 deletions

View File

@ -1,23 +1,20 @@
import { shallow, ShallowWrapper } from 'enzyme'; import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { Button, ModalHeader } from 'reactstrap';
import { DuplicatedServersModal } from '../../../src/servers/helpers/DuplicatedServersModal'; import { DuplicatedServersModal } from '../../../src/servers/helpers/DuplicatedServersModal';
import { ServerData } from '../../../src/servers/data'; import { ServerData } from '../../../src/servers/data';
describe('<DuplicatedServersModal />', () => { describe('<DuplicatedServersModal />', () => {
const onDiscard = jest.fn(); const onDiscard = jest.fn();
const onSave = jest.fn(); const onSave = jest.fn();
let wrapper: ShallowWrapper; const setUp = (duplicatedServers: ServerData[] = []) => ({
const createWrapper = (duplicatedServers: ServerData[] = []) => { user: userEvent.setup(),
wrapper = shallow( ...render(
<DuplicatedServersModal isOpen duplicatedServers={duplicatedServers} onDiscard={onDiscard} onSave={onSave} />, <DuplicatedServersModal isOpen duplicatedServers={duplicatedServers} onDiscard={onDiscard} onSave={onSave} />,
); ),
});
return wrapper;
};
beforeEach(jest.clearAllMocks); beforeEach(jest.clearAllMocks);
afterEach(() => wrapper?.unmount());
it.each([ it.each([
[[], 0], [[], 0],
@ -26,10 +23,8 @@ describe('<DuplicatedServersModal />', () => {
[[Mock.all<ServerData>(), Mock.all<ServerData>(), Mock.all<ServerData>()], 3], [[Mock.all<ServerData>(), Mock.all<ServerData>(), Mock.all<ServerData>()], 3],
[[Mock.all<ServerData>(), Mock.all<ServerData>(), Mock.all<ServerData>(), Mock.all<ServerData>()], 4], [[Mock.all<ServerData>(), Mock.all<ServerData>(), Mock.all<ServerData>(), Mock.all<ServerData>()], 4],
])('renders expected amount of items', (duplicatedServers, expectedItems) => { ])('renders expected amount of items', (duplicatedServers, expectedItems) => {
const wrapper = createWrapper(duplicatedServers); setUp(duplicatedServers);
const li = wrapper.find('li'); expect(screen.queryAllByRole('listitem')).toHaveLength(expectedItems);
expect(li).toHaveLength(expectedItems);
}); });
it.each([ it.each([
@ -52,55 +47,53 @@ describe('<DuplicatedServersModal />', () => {
}, },
], ],
])('renders expected texts based on amount of servers', (duplicatedServers, assertions) => { ])('renders expected texts based on amount of servers', (duplicatedServers, assertions) => {
const wrapper = createWrapper(duplicatedServers); setUp(duplicatedServers);
const header = wrapper.find(ModalHeader);
const p = wrapper.find('p');
const span = wrapper.find('span');
const discardBtn = wrapper.find(Button).first();
expect(header.html()).toContain(assertions.header); expect(screen.getByRole('heading')).toHaveTextContent(assertions.header);
expect(p.html()).toContain(assertions.firstParagraph); expect(screen.getByText(assertions.firstParagraph)).toBeInTheDocument();
expect(span.html()).toContain(assertions.lastParagraph); expect(screen.getByText(assertions.lastParagraph)).toBeInTheDocument();
expect(discardBtn.html()).toContain(assertions.discardBtn); expect(screen.getByRole('button', { name: assertions.discardBtn })).toBeInTheDocument();
}); });
it.each([ it.each([
[[]], [[]],
[[Mock.of<ServerData>({ url: 'url', apiKey: 'apiKey' })]], [[Mock.of<ServerData>({ url: 'url', apiKey: 'apiKey' })]],
[[
Mock.of<ServerData>({ url: 'url_1', apiKey: 'apiKey_1' }),
Mock.of<ServerData>({ url: 'url_2', apiKey: 'apiKey_2' }),
]],
])('displays provided server data', (duplicatedServers) => { ])('displays provided server data', (duplicatedServers) => {
const wrapper = createWrapper(duplicatedServers); setUp(duplicatedServers);
const li = wrapper.find('li');
if (duplicatedServers.length === 0) { if (duplicatedServers.length === 0) {
expect(li).toHaveLength(0); expect(screen.queryByRole('listitem')).not.toBeInTheDocument();
} else if (duplicatedServers.length === 1) { } else if (duplicatedServers.length === 1) {
expect(li.first().find('b').html()).toEqual(`<b>${duplicatedServers[0].url}</b>`); const [firstItem, secondItem] = screen.getAllByRole('listitem');
expect(li.last().find('b').html()).toEqual(`<b>${duplicatedServers[0].apiKey}</b>`);
expect(firstItem).toHaveTextContent(`URL: ${duplicatedServers[0].url}`);
expect(secondItem).toHaveTextContent(`API key: ${duplicatedServers[0].apiKey}`);
} else { } else {
expect.assertions(duplicatedServers.length); expect.assertions(duplicatedServers.length);
li.forEach((item, index) => { screen.getAllByRole('listitem').forEach((item, index) => {
const server = duplicatedServers[index]; const server = duplicatedServers[index];
expect(item).toHaveTextContent(`${server.url} - ${server.apiKey}`);
expect(item.html()).toContain(`<b>${server.url}</b> - <b>${server.apiKey}</b>`);
}); });
} }
}); });
it('invokes onDiscard when appropriate button is clicked', () => { it('invokes onDiscard when appropriate button is clicked', async () => {
const wrapper = createWrapper(); const { user } = setUp();
const btn = wrapper.find(Button).first();
btn.simulate('click');
expect(onDiscard).not.toHaveBeenCalled();
await user.click(screen.getByRole('button', { name: 'Discard' }));
expect(onDiscard).toHaveBeenCalled(); expect(onDiscard).toHaveBeenCalled();
}); });
it('invokes onSave when appropriate button is clicked', () => { it('invokes onSave when appropriate button is clicked', async () => {
const wrapper = createWrapper(); const { user } = setUp();
const btn = wrapper.find(Button).last();
btn.simulate('click');
expect(onSave).not.toHaveBeenCalled();
await user.click(screen.getByRole('button', { name: 'Save anyway' }));
expect(onSave).toHaveBeenCalled(); expect(onSave).toHaveBeenCalled();
}); });
}); });

View File

@ -1,49 +1,43 @@
import { shallow, ShallowWrapper } from 'enzyme'; import { render, screen } from '@testing-library/react';
import { BrowserRouter } from 'react-router-dom'; import { MemoryRouter } from 'react-router-dom';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { ServerError as createServerError } from '../../../src/servers/helpers/ServerError'; import { ServerError as createServerError } from '../../../src/servers/helpers/ServerError';
import { NonReachableServer, NotFoundServer } from '../../../src/servers/data'; import { NonReachableServer, NotFoundServer } from '../../../src/servers/data';
describe('<ServerError />', () => { describe('<ServerError />', () => {
let wrapper: ShallowWrapper;
const ServerError = createServerError(() => null); const ServerError = createServerError(() => null);
afterEach(() => wrapper?.unmount());
it.each([ it.each([
[ [
Mock.all<NotFoundServer>(), Mock.all<NotFoundServer>(),
{ {
'Could not find this Shlink server.': true, found: ['Could not find this Shlink server.'],
'Oops! Could not connect to this Shlink server.': false, notFound: [
'Make sure you have internet connection, and the server is properly configured and on-line.': false, 'Oops! Could not connect to this Shlink server.',
'Alternatively, if you think you may have miss-configured this server': false, 'Make sure you have internet connection, and the server is properly configured and on-line.',
/^Alternatively, if you think you may have miss-configured this server/,
],
}, },
], ],
[ [
Mock.of<NonReachableServer>({ id: 'abc123' }), Mock.of<NonReachableServer>({ id: 'abc123' }),
{ {
'Could not find this Shlink server.': false, found: [
'Oops! Could not connect to this Shlink server.': true, 'Oops! Could not connect to this Shlink server.',
'Make sure you have internet connection, and the server is properly configured and on-line.': true, 'Make sure you have internet connection, and the server is properly configured and on-line.',
'Alternatively, if you think you may have miss-configured this server': true, /^Alternatively, if you think you may have miss-configured this server/,
],
notFound: ['Could not find this Shlink server.'],
}, },
], ],
])('renders expected information based on provided server type', (selectedServer, textsToFind) => { ])('renders expected information based on provided server type', (selectedServer, { found, notFound }) => {
wrapper = shallow( render(
<BrowserRouter> <MemoryRouter>
<ServerError servers={{}} selectedServer={selectedServer} /> <ServerError servers={{}} selectedServer={selectedServer} />
</BrowserRouter>, </MemoryRouter>,
); );
const wrapperText = wrapper.html();
const textPairs = Object.entries(textsToFind);
textPairs.forEach(([text, shouldBeFound]) => { found.forEach((text) => expect(screen.getByText(text)).toBeInTheDocument());
if (shouldBeFound) { notFound.forEach((text) => expect(screen.queryByText(text)).not.toBeInTheDocument());
expect(wrapperText).toContain(text);
} else {
expect(wrapperText).not.toContain(text);
}
});
}); });
}); });

View File

@ -1,30 +1,24 @@
import { shallow, ShallowWrapper } from 'enzyme'; import { fireEvent, render, screen } from '@testing-library/react';
import { ServerForm } from '../../../src/servers/helpers/ServerForm'; import { ServerForm } from '../../../src/servers/helpers/ServerForm';
import { InputFormGroup } from '../../../src/utils/forms/InputFormGroup';
describe('<ServerForm />', () => { describe('<ServerForm />', () => {
let wrapper: ShallowWrapper;
const onSubmit = jest.fn(); const onSubmit = jest.fn();
const setUp = () => render(<ServerForm onSubmit={onSubmit}>Something</ServerForm>);
beforeEach(() => {
wrapper = shallow(<ServerForm onSubmit={onSubmit}><span>Something</span></ServerForm>);
});
afterEach(() => wrapper?.unmount());
afterEach(jest.resetAllMocks); afterEach(jest.resetAllMocks);
it('renders components', () => { it('renders components', () => {
expect(wrapper.find(InputFormGroup)).toHaveLength(3); setUp();
expect(wrapper.find('span')).toHaveLength(1);
expect(screen.getAllByRole('textbox')).toHaveLength(3);
expect(screen.getByText('Something')).toBeInTheDocument();
}); });
it('invokes submit callback when submit event is triggered', () => { it('invokes submit callback when submit event is triggered', async () => {
const form = wrapper.find('form'); setUp();
const preventDefault = jest.fn();
form.simulate('submit', { preventDefault }); expect(onSubmit).not.toHaveBeenCalled();
fireEvent.submit(screen.getByRole('form'), { preventDefault: jest.fn() });
expect(preventDefault).toHaveBeenCalled();
expect(onSubmit).toHaveBeenCalled(); expect(onSubmit).toHaveBeenCalled();
}); });
}); });