Replace @testing-library/jest-dom with built-in vitest browser assertions

This commit is contained in:
Alejandro Celaya
2026-08-16 19:32:41 +02:00
parent ba73644871
commit 585d7c6f63
30 changed files with 305 additions and 429 deletions

View File

@@ -1,7 +1,8 @@
import { fireEvent, screen, waitFor } from '@testing-library/react';
import { fireEvent, waitFor } from '@testing-library/react';
import { fromPartial } from '@total-typescript/shoehorn';
import { createMemoryHistory } from 'history';
import { Router } from 'react-router';
import { page } from 'vitest/browser';
import { CreateServer } from '../../src/servers/CreateServer';
import type { ServersMap } from '../../src/servers/data';
import { checkAccessibility } from '../__helpers__/accessibility';
@@ -41,35 +42,39 @@ describe('<CreateServer />', () => {
it('passes a11y checks', () => checkAccessibility(setUp()));
it('shows success message when imported is true', () => {
it('shows success message when imported is true', async () => {
setUp({ serversImported: true });
expect(screen.getByText('Servers properly imported. You can now select one from the list :)')).toBeInTheDocument();
expect(
screen.queryByText('The servers could not be imported. Make sure the format is correct.'),
).not.toBeInTheDocument();
expect(screen.queryByText('ImportServersBtn')).not.toBeInTheDocument();
await expect
.element(page.getByText('Servers properly imported. You can now select one from the list :)'))
.toBeInTheDocument();
await expect
.element(page.getByText('The servers could not be imported. Make sure the format is correct.'))
.not.toBeInTheDocument();
await expect.element(page.getByText('ImportServersBtn')).not.toBeInTheDocument();
});
it('shows error message when import failed', () => {
it('shows error message when import failed', async () => {
setUp({ importFailed: true });
expect(
screen.queryByText('Servers properly imported. You can now select one from the list :)'),
).not.toBeInTheDocument();
expect(screen.getByText('The servers could not be imported. Make sure the format is correct.')).toBeInTheDocument();
await expect
.element(page.getByText('Servers properly imported. You can now select one from the list :)'))
.not.toBeInTheDocument();
await expect
.element(page.getByText('The servers could not be imported. Make sure the format is correct.'))
.toBeInTheDocument();
});
it('creates server data when form is submitted', async () => {
const { user, history, store } = setUp();
const expectedServerId = 'the_name-the_url.com';
await user.type(screen.getByLabelText(/^Name/), 'the_name');
await user.type(screen.getByLabelText(/^URL/), 'https://the_url.com');
await user.type(screen.getByLabelText(/^API key/), 'the_api_key');
await user.type(page.getByLabelText(/^Name/), 'the_name');
await user.type(page.getByLabelText(/^URL/), 'https://the_url.com');
await user.type(page.getByLabelText(/^API key/), 'the_api_key');
expect(store.getState().servers[expectedServerId]).not.toBeDefined();
fireEvent.submit(screen.getByRole('form'));
fireEvent.submit(page.getByTestId('server-form').element());
expect(store.getState().servers[expectedServerId]).toEqual(
expect.objectContaining({
id: expectedServerId,
@@ -80,20 +85,20 @@ describe('<CreateServer />', () => {
);
expect(history.location.pathname).toEqual(`/server/${expectedServerId}`);
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
await expect.element(page.getByRole('dialog')).not.toBeInTheDocument();
});
it('displays dialog when trying to create a duplicated server', async () => {
const { user, history } = setUp();
await user.type(screen.getByLabelText(/^Name/), 'the_name');
await user.type(screen.getByLabelText(/^URL/), 'https://existing_url.com');
await user.type(screen.getByLabelText(/^API key/), 'existing_api_key');
await user.type(page.getByLabelText(/^Name/), 'the_name');
await user.type(page.getByLabelText(/^URL/), 'https://existing_url.com');
await user.type(page.getByLabelText(/^API key/), 'existing_api_key');
fireEvent.submit(screen.getByRole('form'));
fireEvent.submit(page.getByTestId('server-form').element());
await waitFor(() => expect(screen.getByRole('dialog')).toBeInTheDocument());
await user.click(screen.getByRole('button', { name: 'Discard' }));
await waitFor(() => expect(page.getByRole('dialog')).toBeInTheDocument());
await user.click(page.getByRole('button', { name: 'Discard' }));
expect(history.location.pathname).toEqual('/foo'); // Goes back to first route from history's initialEntries
});

View File

@@ -1,8 +1,8 @@
import { screen } from '@testing-library/react';
import { fromPartial } from '@total-typescript/shoehorn';
import { createMemoryHistory } from 'history';
import type { ReactNode } from 'react';
import { Router } from 'react-router';
import { page } from 'vitest/browser';
import { DeleteServerButton } from '../../src/servers/DeleteServerButton';
import { checkAccessibility } from '../__helpers__/accessibility';
import { renderWithStore } from '../__helpers__/setUpTest';
@@ -21,8 +21,9 @@ describe('<DeleteServerButton />', () => {
it('passes a11y checks', () => checkAccessibility(setUp('Delete me')));
it.each([['Foo bar'], ['baz'], ['something']])('renders expected content', (children) => {
it.each([['Foo bar'], ['baz'], ['something']])('renders expected content', async (children) => {
const { container } = setUp(children);
expect(container.firstChild).toBeTruthy();
expect(container.firstChild).toMatchSnapshot();
});
@@ -30,19 +31,19 @@ describe('<DeleteServerButton />', () => {
it('displays modal when button is clicked', async () => {
const { user } = setUp();
expect(screen.queryByText(/Are you sure you want to remove/)).not.toBeInTheDocument();
await user.click(screen.getByText('Remove this server'));
expect(screen.getByText(/Are you sure you want to remove/)).toBeInTheDocument();
await expect.element(page.getByText(/Are you sure you want to remove/)).not.toBeInTheDocument();
await user.click(page.getByText('Remove this server'));
await expect.element(page.getByText(/Are you sure you want to remove/)).toBeInTheDocument();
});
it('navigates to home when deletion is confirmed', async () => {
const { user, history } = setUp();
// Open modal
await user.click(screen.getByText('Remove this server'));
await user.click(page.getByText('Remove this server'));
expect(history.location.pathname).toEqual('/foo');
await user.click(screen.getByRole('button', { name: 'Delete' }));
await user.click(page.getByRole('button', { name: 'Delete' }));
expect(history.location.pathname).toEqual('/');
});
});

View File

@@ -1,5 +1,5 @@
import { screen } from '@testing-library/react';
import { fromPartial } from '@total-typescript/shoehorn';
import { page } from 'vitest/browser';
import type { ServerWithId } from '../../src/servers/data';
import { DeleteServerModal } from '../../src/servers/DeleteServerModal';
import { checkAccessibility } from '../__helpers__/accessibility';
@@ -18,28 +18,28 @@ describe('<DeleteServerModal />', () => {
it('passes a11y checks', () => checkAccessibility(setUp()));
it('renders a modal window', () => {
it('renders a modal window', async () => {
setUp();
expect(screen.getByRole('dialog')).toBeInTheDocument();
expect(screen.getByRole('heading')).toHaveTextContent('Remove server');
await expect.element(page.getByRole('dialog')).toBeInTheDocument();
await expect.element(page.getByRole('heading')).toHaveTextContent('Remove server');
});
it('displays the name of the server as part of the content', () => {
it('displays the name of the server as part of the content', async () => {
setUp();
expect(screen.getByText(/^Are you sure you want to remove/)).toBeInTheDocument();
expect(screen.getByText(serverName)).toBeInTheDocument();
await expect.element(page.getByText(/^Are you sure you want to remove/)).toBeInTheDocument();
await expect.element(page.getByText(serverName)).toBeInTheDocument();
});
it.each([[() => screen.getByRole('button', { name: 'Cancel' })], [() => screen.getByLabelText('Close dialog')]])(
it.each([[() => page.getByRole('button', { name: 'Cancel' })], [() => page.getByLabelText('Close dialog')]])(
'closes dialog when clicking cancel button',
async (getButton) => {
const { user, store } = setUp();
expect(screen.getByRole('dialog')).toBeInTheDocument();
await expect.element(page.getByRole('dialog')).toBeInTheDocument();
await user.click(getButton());
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
await expect.element(page.getByRole('dialog')).not.toBeInTheDocument();
// No server has been deleted
expect(Object.keys(store.getState().servers)).toHaveLength(1);
@@ -50,7 +50,7 @@ describe('<DeleteServerModal />', () => {
const { user, store } = setUp();
expect(Object.keys(store.getState().servers)).toHaveLength(1);
await user.click(screen.getByRole('button', { name: 'Delete' }));
await user.click(page.getByRole('button', { name: 'Delete' }));
expect(Object.keys(store.getState().servers)).toHaveLength(0);
});
});

View File

@@ -1,7 +1,8 @@
import { fireEvent, screen, waitFor } from '@testing-library/react';
import { fireEvent, waitFor } from '@testing-library/react';
import { fromPartial } from '@total-typescript/shoehorn';
import { createMemoryHistory } from 'history';
import { Router } from 'react-router';
import { page } from 'vitest/browser';
import type { ReachableServer, SelectedServer } from '../../src/servers/data';
import { isServerWithId } from '../../src/servers/data';
import { EditServer } from '../../src/servers/EditServer';
@@ -35,35 +36,35 @@ describe('<EditServer />', () => {
it('passes a11y checks', () => checkAccessibility(setUp()));
it('renders nothing if selected server is not reachable', () => {
it('renders nothing if selected server is not reachable', async () => {
setUp(fromPartial<SelectedServer>({}));
expect(screen.queryByText('Edit')).not.toBeInTheDocument();
expect(screen.queryByText('Cancel')).not.toBeInTheDocument();
expect(screen.queryByText('Save')).not.toBeInTheDocument();
await expect.element(page.getByText('Edit')).not.toBeInTheDocument();
await expect.element(page.getByText('Cancel')).not.toBeInTheDocument();
await expect.element(page.getByText('Save')).not.toBeInTheDocument();
});
it('renders server title', () => {
setUp();
expect(screen.getByText(`Edit "${defaultSelectedServer.name}"`)).toBeInTheDocument();
expect(page.getByText(`Edit "${defaultSelectedServer.name}"`)).toBeInTheDocument();
});
it('display the server info in the form components', () => {
it('display the server info in the form components', async () => {
setUp();
expect(screen.getByLabelText(/^Name/)).toBeInTheDocument();
expect(screen.getByLabelText(/^URL/)).toBeInTheDocument();
expect(screen.getByLabelText(/^API key/)).toBeInTheDocument();
await expect.element(page.getByLabelText(/^Name/)).toBeInTheDocument();
await expect.element(page.getByLabelText(/^URL/)).toBeInTheDocument();
await expect.element(page.getByLabelText(/^API key/)).toBeInTheDocument();
});
it('edits server and redirects to it when form is submitted', async () => {
const { user, history, store } = setUp();
await user.type(screen.getByLabelText(/^Name/), ' edited');
await user.type(screen.getByLabelText(/^URL/), ' edited');
await user.type(page.getByLabelText(/^Name/), ' edited');
await user.type(page.getByLabelText(/^URL/), ' edited');
// TODO Using fire event because userEvent.click on the Submit button does not submit the form
// await user.click(screen.getByRole('button', { name: 'Save' }));
fireEvent.submit(screen.getByRole('form'));
fireEvent.submit(page.getByTestId('server-form').element());
expect(store.getState().servers[defaultSelectedServer.id]).toEqual(
expect.objectContaining({
@@ -81,9 +82,9 @@ describe('<EditServer />', () => {
async ({ forwardCredentials }) => {
const { user, store } = setUp({ ...defaultSelectedServer, forwardCredentials });
await user.click(screen.getByText('Advanced options'));
await user.click(screen.getByLabelText('Forward credentials to this server on every request.'));
fireEvent.submit(screen.getByRole('form'));
await user.click(page.getByText('Advanced options'));
await user.click(page.getByLabelText('Forward credentials to this server on every request.'));
fireEvent.submit(page.getByTestId('server-form').element());
await waitFor(() =>
expect(store.getState().servers[defaultSelectedServer.id]).toEqual(

View File

@@ -1,6 +1,7 @@
import { screen, waitFor } from '@testing-library/react';
import { waitFor } from '@testing-library/react';
import { fromPartial } from '@total-typescript/shoehorn';
import { MemoryRouter } from 'react-router';
import { page } from 'vitest/browser';
import type { ServersMap, ServerWithId } from '../../src/servers/data';
import { ManageServers } from '../../src/servers/ManageServers';
import type { ServersExporter } from '../../src/servers/services/ServersExporter';
@@ -39,71 +40,70 @@ describe('<ManageServers />', () => {
baz: createServerMock('baz'),
});
const search = async (searchTerm: string) => {
await user.clear(screen.getByPlaceholderText('Search...'));
await user.type(screen.getByPlaceholderText('Search...'), searchTerm);
await user.clear(page.getByPlaceholder('Search...'));
await user.type(page.getByPlaceholder('Search...'), searchTerm);
};
// Add one for the header row
const expectRows = (amount: number) => expect(screen.getAllByRole('row')).toHaveLength(amount + 1);
const expectRows = (amount: number) => expect(page.getByRole('row').elements()).toHaveLength(amount + 1);
expectRows(3);
expect(screen.queryByText('No servers found.')).not.toBeInTheDocument();
await expect.element(page.getByText('No servers found.')).not.toBeInTheDocument();
await search('foo');
await waitFor(() => expectRows(1));
expect(screen.queryByText('No servers found.')).not.toBeInTheDocument();
await expect.element(page.getByText('No servers found.')).not.toBeInTheDocument();
await search('Ba');
await waitFor(() => expectRows(2));
expect(screen.queryByText('No servers found.')).not.toBeInTheDocument();
await expect.element(page.getByText('No servers found.')).not.toBeInTheDocument();
await search('invalid');
await waitFor(() => expectRows(1));
expect(screen.getByText('No servers found.')).toBeInTheDocument();
await expect.element(page.getByText('No servers found.')).toBeInTheDocument();
});
it.each([
[createServerMock('foo'), 3],
[createServerMock('foo', true), 4],
])('shows different amount of columns if there are at least one auto-connect server', (server, expectedCols) => {
setUp({ server });
it.only.each([[createServerMock('foo')], [createServerMock('foo', true)]])(
'shows different amount of columns if there are at least one auto-connect server',
async (server) => {
setUp({ server });
expect(screen.getAllByRole('columnheader')).toHaveLength(expectedCols);
if (server.autoConnect) {
expect(screen.getByTestId('auto-connect')).toBeInTheDocument();
} else {
expect(screen.queryByTestId('auto-connect')).not.toBeInTheDocument();
}
});
if (server.autoConnect) {
await expect.element(page.getByTestId('auto-connect')).toBeInTheDocument();
} else {
await expect.element(page.getByTestId('auto-connect')).not.toBeInTheDocument();
}
},
);
it.each([
[{}, 0],
[{ foo: createServerMock('foo') }, 1],
])('shows export button if the list of servers is not empty', (servers, expectedButtons) => {
setUp(servers);
expect(screen.queryAllByRole('button', { name: 'Export servers' })).toHaveLength(expectedButtons);
expect(page.getByRole('button', { name: 'Export servers' }).elements()).toHaveLength(expectedButtons);
});
it('allows exporting servers when clicking on button', async () => {
const { user } = setUp({ foo: createServerMock('foo') });
expect(exportServers).not.toHaveBeenCalled();
await user.click(screen.getByRole('button', { name: 'Export servers' }));
await user.click(page.getByRole('button', { name: 'Export servers' }));
expect(exportServers).toHaveBeenCalled();
});
it.each([[true], [false]])('shows an error message if an error occurs while importing servers', (hasError) => {
it.each([[true], [false]])('shows an error message if an error occurs while importing servers', async (hasError) => {
useTimeoutToggle.mockReturnValue([hasError, vi.fn()]);
setUp({ foo: createServerMock('foo') });
if (hasError) {
expect(
screen.getByText('The servers could not be imported. Make sure the format is correct.'),
).toBeInTheDocument();
await expect
.element(page.getByText('The servers could not be imported. Make sure the format is correct.'))
.toBeInTheDocument();
} else {
expect(
screen.queryByText('The servers could not be imported. Make sure the format is correct.'),
).not.toBeInTheDocument();
await expect
.element(page.getByText('The servers could not be imported. Make sure the format is correct.'))
.not.toBeInTheDocument();
}
});
});

View File

@@ -1,6 +1,6 @@
import { Table } from '@shlinkio/shlink-frontend-kit';
import { screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
import { page } from 'vitest/browser';
import type { ServerWithId } from '../../src/servers/data';
import { ManageServersRow } from '../../src/servers/ManageServersRow';
import { checkAccessibility } from '../__helpers__/accessibility';
@@ -29,12 +29,12 @@ describe('<ManageServersRow />', () => {
[false, 3],
])('renders expected amount of columns', (hasAutoConnect, expectedCols) => {
setUp(hasAutoConnect);
expect(screen.getAllByRole('cell')).toHaveLength(expectedCols);
expect(page.getByRole('cell').elements()).toHaveLength(expectedCols);
});
it('renders an options dropdown', () => {
it('renders an options dropdown', async () => {
setUp();
expect(screen.getByRole('button', { name: 'Options' })).toBeInTheDocument();
await expect.element(page.getByRole('button', { name: 'Options' })).toBeInTheDocument();
});
it.each([[true], [false]])('renders auto-connect icon only if server is autoConnect', (autoConnect) => {
@@ -42,13 +42,13 @@ describe('<ManageServersRow />', () => {
expect(container).toMatchSnapshot();
});
it('renders server props where appropriate', () => {
it('renders server props where appropriate', async () => {
setUp();
const link = screen.getByRole('link');
const link = page.getByRole('link');
expect(link).toHaveAttribute('href', `/server/${server.id}`);
expect(link).toHaveTextContent(server.name);
expect(screen.getByText(server.url)).toBeInTheDocument();
await expect.element(link).toHaveAttribute('href', `/server/${server.id}`);
await expect.element(link).toHaveTextContent(server.name);
await expect.element(page.getByText(server.url)).toBeInTheDocument();
});
});

View File

@@ -1,6 +1,6 @@
import { screen } from '@testing-library/react';
import { fromPartial } from '@total-typescript/shoehorn';
import { MemoryRouter } from 'react-router';
import { page } from 'vitest/browser';
import type { UserEvent } from 'vitest/browser';
import type { ServerWithId } from '../../src/servers/data';
import { ManageServersRowDropdown } from '../../src/servers/ManageServersRowDropdown';
@@ -21,7 +21,7 @@ describe('<ManageServersRowDropdown />', () => {
},
);
};
const toggleDropdown = (user: UserEvent) => user.click(screen.getByRole('button'));
const toggleDropdown = (user: UserEvent) => user.click(page.getByRole('button'));
it('passes a11y checks', async () => {
const { user, container } = setUp();
@@ -34,20 +34,24 @@ describe('<ManageServersRowDropdown />', () => {
it('renders expected amount of dropdown items', async () => {
const { user } = setUp();
expect(screen.queryByRole('menu')).not.toBeInTheDocument();
await expect.element(page.getByRole('menu')).not.toBeInTheDocument();
await toggleDropdown(user);
expect(screen.getByRole('menu')).toBeInTheDocument();
await expect.element(page.getByRole('menu')).toBeInTheDocument();
expect(screen.getAllByRole('menuitem')).toHaveLength(4);
expect(screen.getByRole('menuitem', { name: 'Connect' })).toHaveAttribute('href', '/server/abc123');
expect(screen.getByRole('menuitem', { name: 'Edit server' })).toHaveAttribute('href', '/server/abc123/edit');
expect(page.getByRole('menuitem').elements()).toHaveLength(4);
await expect
.element(page.getByRole('menuitem', { name: 'Connect', exact: true }))
.toHaveAttribute('href', '/server/abc123');
await expect
.element(page.getByRole('menuitem', { name: 'Edit server' }))
.toHaveAttribute('href', '/server/abc123/edit');
});
it.each([true, false])('allows toggling auto-connect', async (autoConnect) => {
const { user, store } = setUp(autoConnect);
await toggleDropdown(user);
await user.click(screen.getByRole('menuitem', { name: autoConnect ? 'Do not auto-connect' : 'Auto-connect' }));
await user.click(page.getByRole('menuitem', { name: autoConnect ? 'Do not auto-connect' : 'Auto-connect' }));
expect(Object.values(store.getState().servers)[0].autoConnect).toEqual(!autoConnect);
});
@@ -55,12 +59,12 @@ describe('<ManageServersRowDropdown />', () => {
it('renders deletion modal', async () => {
const { user } = setUp();
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
expect(page.getByRole('dialog')).not.toBeInTheDocument();
await toggleDropdown(user);
await user.click(screen.getByRole('menuitem', { name: 'Remove server' }));
await user.click(page.getByRole('menuitem', { name: 'Remove server' }));
expect(screen.getByRole('dialog')).toBeInTheDocument();
await expect.element(page.getByRole('dialog')).toBeInTheDocument();
});
it.each([[true], [false]])('renders expected size and icon', (autoConnect) => {

View File

@@ -1,6 +1,6 @@
import { screen } from '@testing-library/react';
import { fromPartial } from '@total-typescript/shoehorn';
import { MemoryRouter } from 'react-router';
import { page } from 'vitest/browser';
import type { ServersMap } from '../../src/servers/data';
import { ServersDropdown } from '../../src/servers/ServersDropdown';
import { checkAccessibility } from '../__helpers__/accessibility';
@@ -27,7 +27,7 @@ describe('<ServersDropdown />', () => {
it('passes a11y checks', async () => {
const { user, ...rest } = setUp();
// Open menu
await user.click(screen.getByText('Servers'));
await user.click(page.getByText('Servers'));
return checkAccessibility(rest);
});
@@ -35,33 +35,35 @@ describe('<ServersDropdown />', () => {
it('contains the list of servers and the "mange servers" button', async () => {
const { user } = setUp();
await user.click(screen.getByText('Servers'));
const items = screen.getAllByRole('menuitem');
await user.click(page.getByText('Servers'));
const items = page.getByRole('menuitem').elements();
// We have to add two for the "Manage servers" and the "Settings" menu items
expect(items).toHaveLength(Object.values(fallbackServers).length + 2);
expect(items[1]).toHaveTextContent('foo');
expect(items[2]).toHaveTextContent('bar');
expect(items[3]).toHaveTextContent('baz');
expect(items[4]).toHaveTextContent('Manage servers');
await expect.element(items[1]).toHaveTextContent('foo');
await expect.element(items[2]).toHaveTextContent('bar');
await expect.element(items[3]).toHaveTextContent('baz');
await expect.element(items[4]).toHaveTextContent('Manage servers');
});
it('contains a toggle with proper text', () => {
it('contains a toggle with proper text', async () => {
setUp();
expect(screen.getByRole('button')).toHaveTextContent('Servers');
await expect.element(page.getByRole('button')).toHaveTextContent('Servers');
});
it('contains a button to manage servers', async () => {
const { user } = setUp();
await user.click(screen.getByText('Servers'));
expect(screen.getByRole('menuitem', { name: 'Manage servers' })).toHaveAttribute('href', '/manage-servers');
await user.click(page.getByText('Servers'));
await expect
.element(page.getByRole('menuitem', { name: 'Manage servers' }))
.toHaveAttribute('href', '/manage-servers');
});
it('shows only create link when no servers exist yet', async () => {
const { user } = setUp({});
await user.click(screen.getByText('Servers'));
expect(screen.getByRole('menuitem', { name: 'Add a server' })).toBeInTheDocument();
await user.click(page.getByText('Servers'));
await expect.element(page.getByRole('menuitem', { name: 'Add a server' })).toBeInTheDocument();
});
});

View File

@@ -26,14 +26,14 @@ describe('<ServersListGroup />', () => {
expect(screen.queryAllByRole('link')).toHaveLength(servers.length);
});
it.each([[true], [false], [undefined]])('renders proper classes for embedded', (borderless) => {
it.each([[true], [false], [undefined]])('renders proper classes for embedded', async (borderless) => {
setUp({ servers, borderless });
const list = screen.getByTestId('list');
if (!borderless) {
expect(list).toHaveClass('border-y');
await expect.element(list).toHaveClass('border-y');
} else {
expect(list).not.toHaveClass('border-y');
await expect.element(list).not.toHaveClass('border-y');
}
});
});

View File

@@ -1,5 +1,5 @@
import { act, screen } from '@testing-library/react';
import { fromPartial } from '@total-typescript/shoehorn';
import { page } from 'vitest/browser';
import type { ServerData } from '../../../src/servers/data';
import { DuplicatedServersModal } from '../../../src/servers/helpers/DuplicatedServersModal';
import { checkAccessibility } from '../../__helpers__/accessibility';
@@ -9,10 +9,8 @@ describe('<DuplicatedServersModal />', () => {
const onClose = vi.fn();
const onConfirm = vi.fn();
const setUp = (duplicatedServers: ServerData[] = []) =>
act(() =>
renderWithEvents(
<DuplicatedServersModal open duplicatedServers={duplicatedServers} onClose={onClose} onConfirm={onConfirm} />,
),
renderWithEvents(
<DuplicatedServersModal open duplicatedServers={duplicatedServers} onClose={onClose} onConfirm={onConfirm} />,
);
const mockServer = (data: Partial<ServerData> = {}) => fromPartial<ServerData>(data);
@@ -24,9 +22,9 @@ describe('<DuplicatedServersModal />', () => {
[[mockServer(), mockServer()], 2],
[[mockServer(), mockServer(), mockServer()], 3],
[[mockServer(), mockServer(), mockServer(), mockServer()], 4],
])('renders expected amount of items', async (duplicatedServers, expectedItems) => {
await setUp(duplicatedServers);
expect(screen.queryAllByRole('listitem')).toHaveLength(expectedItems);
])('renders expected amount of items', (duplicatedServers, expectedItems) => {
setUp(duplicatedServers);
expect(page.getByRole('listitem')).toHaveLength(expectedItems);
});
it.each([
@@ -51,13 +49,13 @@ describe('<DuplicatedServersModal />', () => {
},
],
])('renders expected texts based on amount of servers', async (duplicatedServers, assertions) => {
await setUp(duplicatedServers);
setUp(duplicatedServers);
expect(screen.getByRole('heading')).toHaveTextContent(assertions.header);
expect(screen.getByText(assertions.firstParagraph)).toBeInTheDocument();
expect(screen.getByText(assertions.lastParagraph)).toBeInTheDocument();
expect(screen.getByRole('button', { name: assertions.discardBtn })).toBeInTheDocument();
expect(screen.getByRole('button', { name: assertions.confirmButton })).toBeInTheDocument();
await expect.element(page.getByRole('heading')).toHaveTextContent(assertions.header);
await expect.element(page.getByText(assertions.firstParagraph)).toBeInTheDocument();
await expect.element(page.getByText(assertions.lastParagraph)).toBeInTheDocument();
await expect.element(page.getByRole('button', { name: assertions.discardBtn })).toBeInTheDocument();
await expect.element(page.getByRole('button', { name: assertions.confirmButton })).toBeInTheDocument();
});
it.each([
@@ -65,37 +63,42 @@ describe('<DuplicatedServersModal />', () => {
[[mockServer({ url: 'url', apiKey: 'apiKey' })]],
[[mockServer({ url: 'url_1', apiKey: 'apiKey_1' }), mockServer({ url: 'url_2', apiKey: 'apiKey_2' })]],
])('displays provided server data', async (duplicatedServers) => {
await setUp(duplicatedServers);
setUp(duplicatedServers);
if (duplicatedServers.length === 0) {
expect(screen.queryByRole('listitem')).not.toBeInTheDocument();
await expect.element(page.getByRole('listitem')).not.toBeInTheDocument();
} else if (duplicatedServers.length === 1) {
const [firstItem, secondItem] = screen.getAllByRole('listitem');
const [firstItem, secondItem] = page.getByRole('listitem').elements();
expect(firstItem).toHaveTextContent(`URL: ${duplicatedServers[0].url}`);
expect(secondItem).toHaveTextContent(`API key: ${duplicatedServers[0].apiKey}`);
await expect.element(firstItem).toHaveTextContent(`URL: ${duplicatedServers[0].url}`);
await expect.element(secondItem).toHaveTextContent(`API key: ${duplicatedServers[0].apiKey}`);
} else {
expect.assertions(duplicatedServers.length);
screen.getAllByRole('listitem').forEach((item, index) => {
const server = duplicatedServers[index];
expect(item).toHaveTextContent(`${server.url} - ${server.apiKey}`);
});
await Promise.all(
page
.getByRole('listitem')
.elements()
.map((item, index) => {
const server = duplicatedServers[index];
return expect.element(item).toHaveTextContent(`${server.url} - ${server.apiKey}`);
}),
);
}
});
it('invokes onClose when appropriate button is clicked', async () => {
const { user } = await setUp();
const { user } = setUp();
expect(onClose).not.toHaveBeenCalled();
await user.click(screen.getByRole('button', { name: 'Discard' }));
await user.click(page.getByRole('button', { name: 'Discard' }));
expect(onClose).toHaveBeenCalled();
});
it('invokes onConfirm when appropriate button is clicked', async () => {
const { user } = await setUp();
const { user } = setUp();
expect(onConfirm).not.toHaveBeenCalled();
await user.click(screen.getByRole('button', { name: 'Save duplicate' }));
await user.click(page.getByRole('button', { name: 'Save duplicate' }));
expect(onConfirm).toHaveBeenCalled();
});
});

View File

@@ -1,5 +1,5 @@
import { screen, waitFor } from '@testing-library/react';
import { fromPartial } from '@total-typescript/shoehorn';
import { page } from 'vitest/browser';
import type { ServerData, ServersMap, ServerWithId } from '../../../src/servers/data';
import type { ImportServersBtnProps } from '../../../src/servers/helpers/ImportServersBtn';
import { ImportServersBtn } from '../../../src/servers/helpers/ImportServersBtn';
@@ -22,35 +22,33 @@ describe('<ImportServersBtn />', () => {
it('shows tooltip on button hover', async () => {
const { user } = setUp();
expect(screen.queryByText(/^You can create servers by importing a CSV file/)).not.toBeInTheDocument();
await user.hover(screen.getByRole('button'));
await waitFor(() =>
expect(screen.getByText(/^You can create servers by importing a CSV file/)).toBeInTheDocument(),
);
await expect.element(page.getByText('You can create servers by importing a CSV file')).not.toBeInTheDocument();
await user.hover(page.getByRole('button'));
await expect.element(page.getByText('You can create servers by importing a CSV file')).toBeInTheDocument();
});
it.each([
[undefined, ''],
['foo', 'foo'],
['bar', 'bar'],
])('allows a class name to be provided', (providedClassName, expectedClassName) => {
])('allows a class name to be provided', async (providedClassName, expectedClassName) => {
setUp({ className: providedClassName });
expect(screen.getByRole('button')).toHaveAttribute('class', expect.stringContaining(expectedClassName));
await expect.element(page.getByRole('button')).toHaveAttribute('class', expect.stringContaining(expectedClassName));
});
it.each([
[undefined, 'Import from file'],
['foo', 'foo'],
['bar', 'bar'],
])('has expected text', (children, expectedText) => {
])('has expected text', async (children, expectedText) => {
setUp({ children });
expect(screen.getByRole('button')).toHaveTextContent(expectedText);
await expect.element(page.getByRole('button')).toHaveTextContent(expectedText);
});
it('imports servers when file input changes', async () => {
const { user } = setUp();
await user.upload(screen.getByTestId('csv-file-input'), csvFile);
await user.upload(page.getByTestId('csv-file-input'), csvFile);
expect(importServersFromFile).toHaveBeenCalledTimes(1);
});
@@ -74,15 +72,15 @@ describe('<ImportServersBtn />', () => {
importServersFromFile.mockResolvedValue([existingServerData, newServer]);
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
await user.upload(screen.getByTestId('csv-file-input'), csvFile);
await expect.element(page.getByRole('dialog')).not.toBeInTheDocument();
await user.upload(page.getByTestId('csv-file-input'), csvFile);
// Once the file is uploaded, non-duplicated servers are immediately created
const { servers } = store.getState();
expect(Object.keys(servers)).toHaveLength(2);
expect(screen.getByRole('dialog')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: btnName }));
await expect.element(page.getByRole('dialog')).toBeInTheDocument();
await user.click(page.getByRole('button', { name: btnName }));
// If duplicated servers are saved, there's one extra server creation
if (savesDuplicatedServers) {

View File

@@ -45,10 +45,10 @@ describe('<ServerError />', () => {
notFound: ['Could not find this Shlink server.'],
},
],
])('renders expected information based on provided server type', (selectedServer, { found, notFound }) => {
])('renders expected information based on provided server type', async (selectedServer, { found, notFound }) => {
setUp(selectedServer);
found.forEach((text) => expect(screen.getByText(text)).toBeInTheDocument());
notFound.forEach((text) => expect(screen.queryByText(text)).not.toBeInTheDocument());
await Promise.all(found.map((text) => expect.element(screen.getByText(text)).toBeInTheDocument()));
await Promise.all(notFound.map((text) => expect.element(screen.queryByText(text)).not.toBeInTheDocument()));
});
});

View File

@@ -1,4 +1,5 @@
import { fireEvent, screen } from '@testing-library/react';
import { fireEvent } from '@testing-library/react';
import { page } from 'vitest/browser';
import { ServerForm } from '../../../src/servers/helpers/ServerForm';
import { checkAccessibility } from '../../__helpers__/accessibility';
import { renderWithEvents } from '../../__helpers__/setUpTest';
@@ -9,21 +10,21 @@ describe('<ServerForm />', () => {
it('passes a11y checks', () => checkAccessibility(setUp()));
it('renders inputs', () => {
it('renders inputs', async () => {
setUp();
expect(screen.getByLabelText(/^Name/)).toBeInTheDocument();
expect(screen.getByLabelText(/^URL/)).toBeInTheDocument();
expect(screen.getByLabelText(/^API key/)).toBeInTheDocument();
expect(screen.getByText('Something')).toBeInTheDocument();
expect(screen.getByText('Advanced options')).toBeInTheDocument();
await expect.element(page.getByLabelText(/^Name/)).toBeInTheDocument();
await expect.element(page.getByLabelText(/^URL/)).toBeInTheDocument();
await expect.element(page.getByLabelText(/^API key/)).toBeInTheDocument();
await expect.element(page.getByText('Something')).toBeInTheDocument();
await expect.element(page.getByText('Advanced options')).toBeInTheDocument();
});
it('invokes submit callback when submit event is triggered', async () => {
setUp();
expect(onSubmit).not.toHaveBeenCalled();
fireEvent.submit(screen.getByRole('form'), { preventDefault: vi.fn() });
fireEvent.submit(page.getByTestId('server-form').element(), { preventDefault: vi.fn() });
expect(onSubmit).toHaveBeenCalled();
});
@@ -31,8 +32,8 @@ describe('<ServerForm />', () => {
const { user } = setUp();
const forwardCredentialsLabel = 'Forward credentials to this server on every request.';
expect(screen.queryByLabelText(forwardCredentialsLabel)).not.toBeInTheDocument();
await user.click(screen.getByText('Advanced options'));
expect(screen.getByLabelText(forwardCredentialsLabel)).toBeInTheDocument();
await expect.element(page.getByLabelText(forwardCredentialsLabel)).not.toBeInTheDocument();
await user.click(page.getByText('Advanced options'));
await expect.element(page.getByLabelText(forwardCredentialsLabel)).toBeInTheDocument();
});
});