mirror of
https://github.com/shlinkio/shlink-web-client.git
synced 2024-12-23 01:20:24 +03:00
Remove usages of vi.mock
This commit is contained in:
parent
598540aaac
commit
f50d033551
6 changed files with 84 additions and 67 deletions
23
test/__helpers__/MemoryRouterWithParams.tsx
Normal file
23
test/__helpers__/MemoryRouterWithParams.tsx
Normal file
|
@ -0,0 +1,23 @@
|
||||||
|
import type { FC, PropsWithChildren } from 'react';
|
||||||
|
import { useMemo } from 'react';
|
||||||
|
import { MemoryRouter, Route, Routes } from 'react-router-dom';
|
||||||
|
|
||||||
|
export type MemoryRouterWithParamsProps = PropsWithChildren<{
|
||||||
|
params: Record<string, string>;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wrap any component using useParams() with MemoryRouterWithParams, in order to determine wat the hook should return
|
||||||
|
*/
|
||||||
|
export const MemoryRouterWithParams: FC<MemoryRouterWithParamsProps> = ({ children, params }) => {
|
||||||
|
const pathname = useMemo(() => `/${Object.values(params).join('/')}`, [params]);
|
||||||
|
const pathPattern = useMemo(() => `/:${Object.keys(params).join('/:')}`, [params]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<MemoryRouter>
|
||||||
|
<Routes location={{ pathname }}>
|
||||||
|
<Route path={pathPattern} element={children} />
|
||||||
|
</Routes>
|
||||||
|
</MemoryRouter>
|
||||||
|
);
|
||||||
|
};
|
|
@ -1,14 +1,9 @@
|
||||||
import { render, screen } from '@testing-library/react';
|
import { render, screen } from '@testing-library/react';
|
||||||
import { fromPartial } from '@total-typescript/shoehorn';
|
import { fromPartial } from '@total-typescript/shoehorn';
|
||||||
import { useParams } from 'react-router-dom';
|
|
||||||
import { ShlinkWebComponentContainerFactory } from '../../src/common/ShlinkWebComponentContainer';
|
import { ShlinkWebComponentContainerFactory } from '../../src/common/ShlinkWebComponentContainer';
|
||||||
import type { NonReachableServer, NotFoundServer, SelectedServer } from '../../src/servers/data';
|
import type { NonReachableServer, NotFoundServer, SelectedServer } from '../../src/servers/data';
|
||||||
import { checkAccessibility } from '../__helpers__/accessibility';
|
import { checkAccessibility } from '../__helpers__/accessibility';
|
||||||
|
import { MemoryRouterWithParams } from '../__helpers__/MemoryRouterWithParams';
|
||||||
vi.mock('react-router-dom', async () => ({
|
|
||||||
...(await vi.importActual<any>('react-router-dom')),
|
|
||||||
useParams: vi.fn(),
|
|
||||||
}));
|
|
||||||
|
|
||||||
describe('<ShlinkWebComponentContainer />', () => {
|
describe('<ShlinkWebComponentContainer />', () => {
|
||||||
const ShlinkWebComponentContainer = ShlinkWebComponentContainerFactory(fromPartial({
|
const ShlinkWebComponentContainer = ShlinkWebComponentContainerFactory(fromPartial({
|
||||||
|
@ -18,13 +13,11 @@ describe('<ShlinkWebComponentContainer />', () => {
|
||||||
ServerError: () => <>ServerError</>,
|
ServerError: () => <>ServerError</>,
|
||||||
}));
|
}));
|
||||||
const setUp = (selectedServer: SelectedServer) => render(
|
const setUp = (selectedServer: SelectedServer) => render(
|
||||||
<ShlinkWebComponentContainer selectServer={vi.fn()} selectedServer={selectedServer} settings={{}} />,
|
<MemoryRouterWithParams params={{ serverId: 'abc123' }}>
|
||||||
|
<ShlinkWebComponentContainer selectServer={vi.fn()} selectedServer={selectedServer} settings={{}} />
|
||||||
|
</MemoryRouterWithParams>,
|
||||||
);
|
);
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
(useParams as any).mockReturnValue({ serverId: 'abc123' });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('passes a11y checks', () => checkAccessibility(setUp(fromPartial({ version: '3.0.0' }))));
|
it('passes a11y checks', () => checkAccessibility(setUp(fromPartial({ version: '3.0.0' }))));
|
||||||
|
|
||||||
it('shows loading indicator while loading server', () => {
|
it('shows loading indicator while loading server', () => {
|
||||||
|
|
|
@ -1,16 +1,12 @@
|
||||||
import { fireEvent, screen, waitFor } from '@testing-library/react';
|
import { fireEvent, screen, waitFor } from '@testing-library/react';
|
||||||
import { fromPartial } from '@total-typescript/shoehorn';
|
import { fromPartial } from '@total-typescript/shoehorn';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { createMemoryHistory } from 'history';
|
||||||
|
import { Router } from 'react-router-dom';
|
||||||
import { CreateServerFactory } from '../../src/servers/CreateServer';
|
import { CreateServerFactory } from '../../src/servers/CreateServer';
|
||||||
import type { ServersMap } from '../../src/servers/data';
|
import type { ServersMap } from '../../src/servers/data';
|
||||||
import { checkAccessibility } from '../__helpers__/accessibility';
|
import { checkAccessibility } from '../__helpers__/accessibility';
|
||||||
import { renderWithEvents } from '../__helpers__/setUpTest';
|
import { renderWithEvents } from '../__helpers__/setUpTest';
|
||||||
|
|
||||||
vi.mock('react-router-dom', async () => ({
|
|
||||||
...(await vi.importActual<any>('react-router-dom')),
|
|
||||||
useNavigate: vi.fn(),
|
|
||||||
}));
|
|
||||||
|
|
||||||
type SetUpOptions = {
|
type SetUpOptions = {
|
||||||
serversImported?: boolean;
|
serversImported?: boolean;
|
||||||
importFailed?: boolean;
|
importFailed?: boolean;
|
||||||
|
@ -19,13 +15,10 @@ type SetUpOptions = {
|
||||||
|
|
||||||
describe('<CreateServer />', () => {
|
describe('<CreateServer />', () => {
|
||||||
const createServersMock = vi.fn();
|
const createServersMock = vi.fn();
|
||||||
const navigate = vi.fn();
|
|
||||||
const defaultServers: ServersMap = {
|
const defaultServers: ServersMap = {
|
||||||
foo: fromPartial({ url: 'https://existing_url.com', apiKey: 'existing_api_key' }),
|
foo: fromPartial({ url: 'https://existing_url.com', apiKey: 'existing_api_key' }),
|
||||||
};
|
};
|
||||||
const setUp = ({ serversImported = false, importFailed = false, servers = defaultServers }: SetUpOptions = {}) => {
|
const setUp = ({ serversImported = false, importFailed = false, servers = defaultServers }: SetUpOptions = {}) => {
|
||||||
(useNavigate as any).mockReturnValue(navigate);
|
|
||||||
|
|
||||||
let callCount = 0;
|
let callCount = 0;
|
||||||
const useTimeoutToggle = vi.fn().mockImplementation(() => {
|
const useTimeoutToggle = vi.fn().mockImplementation(() => {
|
||||||
const result = [callCount % 2 === 0 ? serversImported : importFailed, () => null];
|
const result = [callCount % 2 === 0 ? serversImported : importFailed, () => null];
|
||||||
|
@ -36,8 +29,16 @@ describe('<CreateServer />', () => {
|
||||||
ImportServersBtn: () => <>ImportServersBtn</>,
|
ImportServersBtn: () => <>ImportServersBtn</>,
|
||||||
useTimeoutToggle,
|
useTimeoutToggle,
|
||||||
}));
|
}));
|
||||||
|
const history = createMemoryHistory({ initialEntries: ['/foo', '/bar'] });
|
||||||
|
|
||||||
return renderWithEvents(<CreateServer createServers={createServersMock} servers={servers} />);
|
return {
|
||||||
|
history,
|
||||||
|
...renderWithEvents(
|
||||||
|
<Router location={history.location} navigator={history}>
|
||||||
|
<CreateServer createServers={createServersMock} servers={servers} />
|
||||||
|
</Router>,
|
||||||
|
),
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
it('passes a11y checks', () => checkAccessibility(setUp()));
|
it('passes a11y checks', () => checkAccessibility(setUp()));
|
||||||
|
@ -67,7 +68,7 @@ describe('<CreateServer />', () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('creates server data when form is submitted', async () => {
|
it('creates server data when form is submitted', async () => {
|
||||||
const { user } = setUp();
|
const { user, history } = setUp();
|
||||||
|
|
||||||
expect(createServersMock).not.toHaveBeenCalled();
|
expect(createServersMock).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
@ -81,12 +82,12 @@ describe('<CreateServer />', () => {
|
||||||
url: 'https://the_url.com',
|
url: 'https://the_url.com',
|
||||||
apiKey: 'the_api_key',
|
apiKey: 'the_api_key',
|
||||||
})]);
|
})]);
|
||||||
expect(navigate).toHaveBeenCalledWith(expect.stringMatching(/^\/server\//));
|
expect(history.location.pathname).toEqual(expect.stringMatching(/^\/server\//));
|
||||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('displays dialog when trying to create a duplicated server', async () => {
|
it('displays dialog when trying to create a duplicated server', async () => {
|
||||||
const { user } = setUp();
|
const { user, history } = setUp();
|
||||||
|
|
||||||
await user.type(screen.getByLabelText(/^Name/), 'the_name');
|
await user.type(screen.getByLabelText(/^Name/), 'the_name');
|
||||||
await user.type(screen.getByLabelText(/^URL/), 'https://existing_url.com');
|
await user.type(screen.getByLabelText(/^URL/), 'https://existing_url.com');
|
||||||
|
@ -97,6 +98,6 @@ describe('<CreateServer />', () => {
|
||||||
await user.click(screen.getByRole('button', { name: 'Discard' }));
|
await user.click(screen.getByRole('button', { name: 'Discard' }));
|
||||||
|
|
||||||
expect(createServersMock).not.toHaveBeenCalled();
|
expect(createServersMock).not.toHaveBeenCalled();
|
||||||
expect(navigate).toHaveBeenCalledWith(-1);
|
expect(history.location.pathname).toEqual('/foo'); // Goes back to first route from history's initialEntries
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
@ -1,24 +1,21 @@
|
||||||
import { screen, waitFor } from '@testing-library/react';
|
import { screen, waitFor } from '@testing-library/react';
|
||||||
import { fromPartial } from '@total-typescript/shoehorn';
|
import { fromPartial } from '@total-typescript/shoehorn';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { createMemoryHistory } from 'history';
|
||||||
|
import { Router } from 'react-router-dom';
|
||||||
import { DeleteServerModal } from '../../src/servers/DeleteServerModal';
|
import { DeleteServerModal } from '../../src/servers/DeleteServerModal';
|
||||||
import { checkAccessibility } from '../__helpers__/accessibility';
|
import { checkAccessibility } from '../__helpers__/accessibility';
|
||||||
import { renderWithEvents } from '../__helpers__/setUpTest';
|
import { renderWithEvents } from '../__helpers__/setUpTest';
|
||||||
import { TestModalWrapper } from '../__helpers__/TestModalWrapper';
|
import { TestModalWrapper } from '../__helpers__/TestModalWrapper';
|
||||||
|
|
||||||
vi.mock('react-router-dom', async () => ({
|
|
||||||
...(await vi.importActual<any>('react-router-dom')),
|
|
||||||
useNavigate: vi.fn(),
|
|
||||||
}));
|
|
||||||
|
|
||||||
describe('<DeleteServerModal />', () => {
|
describe('<DeleteServerModal />', () => {
|
||||||
const deleteServerMock = vi.fn();
|
const deleteServerMock = vi.fn();
|
||||||
const navigate = vi.fn();
|
|
||||||
const serverName = 'the_server_name';
|
const serverName = 'the_server_name';
|
||||||
const setUp = () => {
|
const setUp = () => {
|
||||||
(useNavigate as any).mockReturnValue(navigate);
|
const history = createMemoryHistory({ initialEntries: ['/foo'] });
|
||||||
|
return {
|
||||||
return renderWithEvents(
|
history,
|
||||||
|
...renderWithEvents(
|
||||||
|
<Router location={history.location} navigator={history}>
|
||||||
<TestModalWrapper
|
<TestModalWrapper
|
||||||
renderModal={(args) => (
|
renderModal={(args) => (
|
||||||
<DeleteServerModal
|
<DeleteServerModal
|
||||||
|
@ -27,8 +24,10 @@ describe('<DeleteServerModal />', () => {
|
||||||
deleteServer={deleteServerMock}
|
deleteServer={deleteServerMock}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
/>,
|
/>
|
||||||
);
|
</Router>,
|
||||||
|
),
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
it('passes a11y checks', () => checkAccessibility(setUp()));
|
it('passes a11y checks', () => checkAccessibility(setUp()));
|
||||||
|
@ -51,22 +50,23 @@ describe('<DeleteServerModal />', () => {
|
||||||
[() => screen.getByRole('button', { name: 'Cancel' })],
|
[() => screen.getByRole('button', { name: 'Cancel' })],
|
||||||
[() => screen.getByLabelText('Close')],
|
[() => screen.getByLabelText('Close')],
|
||||||
])('toggles when clicking cancel button', async (getButton) => {
|
])('toggles when clicking cancel button', async (getButton) => {
|
||||||
const { user } = setUp();
|
const { user, history } = setUp();
|
||||||
|
|
||||||
|
expect(history.location.pathname).toEqual('/foo');
|
||||||
await user.click(getButton());
|
await user.click(getButton());
|
||||||
|
|
||||||
expect(deleteServerMock).not.toHaveBeenCalled();
|
expect(deleteServerMock).not.toHaveBeenCalled();
|
||||||
expect(navigate).not.toHaveBeenCalled();
|
expect(history.location.pathname).toEqual('/foo'); // No navigation happens, keeping initial pathname
|
||||||
});
|
});
|
||||||
|
|
||||||
it('deletes server when clicking accept button', async () => {
|
it('deletes server when clicking accept button', async () => {
|
||||||
const { user } = setUp();
|
const { user, history } = setUp();
|
||||||
|
|
||||||
expect(deleteServerMock).not.toHaveBeenCalled();
|
expect(deleteServerMock).not.toHaveBeenCalled();
|
||||||
expect(navigate).not.toHaveBeenCalled();
|
expect(history.location.pathname).toEqual('/foo');
|
||||||
await user.click(screen.getByRole('button', { name: 'Delete' }));
|
await user.click(screen.getByRole('button', { name: 'Delete' }));
|
||||||
|
|
||||||
await waitFor(() => expect(deleteServerMock).toHaveBeenCalledTimes(1));
|
await waitFor(() => expect(deleteServerMock).toHaveBeenCalledTimes(1));
|
||||||
await waitFor(() => expect(navigate).toHaveBeenCalledTimes(1));
|
await waitFor(() => expect(history.location.pathname).toEqual('/'));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
@ -1,20 +1,15 @@
|
||||||
import { fireEvent, screen } from '@testing-library/react';
|
import { fireEvent, screen } from '@testing-library/react';
|
||||||
import { fromPartial } from '@total-typescript/shoehorn';
|
import { fromPartial } from '@total-typescript/shoehorn';
|
||||||
import { MemoryRouter, useNavigate } from 'react-router-dom';
|
import { createMemoryHistory } from 'history';
|
||||||
|
import { Router } from 'react-router-dom';
|
||||||
import type { ReachableServer, SelectedServer } from '../../src/servers/data';
|
import type { ReachableServer, SelectedServer } from '../../src/servers/data';
|
||||||
import { EditServerFactory } from '../../src/servers/EditServer';
|
import { EditServerFactory } from '../../src/servers/EditServer';
|
||||||
import { checkAccessibility } from '../__helpers__/accessibility';
|
import { checkAccessibility } from '../__helpers__/accessibility';
|
||||||
import { renderWithEvents } from '../__helpers__/setUpTest';
|
import { renderWithEvents } from '../__helpers__/setUpTest';
|
||||||
|
|
||||||
vi.mock('react-router-dom', async () => ({
|
|
||||||
...(await vi.importActual<any>('react-router-dom')),
|
|
||||||
useNavigate: vi.fn(),
|
|
||||||
}));
|
|
||||||
|
|
||||||
describe('<EditServer />', () => {
|
describe('<EditServer />', () => {
|
||||||
const ServerError = vi.fn();
|
const ServerError = vi.fn();
|
||||||
const editServerMock = vi.fn();
|
const editServerMock = vi.fn();
|
||||||
const navigate = vi.fn();
|
|
||||||
const defaultSelectedServer = fromPartial<ReachableServer>({
|
const defaultSelectedServer = fromPartial<ReachableServer>({
|
||||||
id: 'abc123',
|
id: 'abc123',
|
||||||
name: 'the_name',
|
name: 'the_name',
|
||||||
|
@ -22,15 +17,17 @@ describe('<EditServer />', () => {
|
||||||
apiKey: 'the_api_key',
|
apiKey: 'the_api_key',
|
||||||
});
|
});
|
||||||
const EditServer = EditServerFactory(fromPartial({ ServerError }));
|
const EditServer = EditServerFactory(fromPartial({ ServerError }));
|
||||||
const setUp = (selectedServer: SelectedServer = defaultSelectedServer) => renderWithEvents(
|
const setUp = (selectedServer: SelectedServer = defaultSelectedServer) => {
|
||||||
<MemoryRouter>
|
const history = createMemoryHistory({ initialEntries: ['/foo', '/bar'] });
|
||||||
|
return {
|
||||||
|
history,
|
||||||
|
...renderWithEvents(
|
||||||
|
<Router location={history.location} navigator={history}>
|
||||||
<EditServer editServer={editServerMock} selectedServer={selectedServer} selectServer={vi.fn()} />
|
<EditServer editServer={editServerMock} selectedServer={selectedServer} selectServer={vi.fn()} />
|
||||||
</MemoryRouter>,
|
</Router>,
|
||||||
);
|
),
|
||||||
|
};
|
||||||
beforeEach(() => {
|
};
|
||||||
(useNavigate as any).mockReturnValue(navigate);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('passes a11y checks', () => checkAccessibility(setUp()));
|
it('passes a11y checks', () => checkAccessibility(setUp()));
|
||||||
|
|
||||||
|
@ -56,7 +53,7 @@ describe('<EditServer />', () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('edits server and redirects to it when form is submitted', async () => {
|
it('edits server and redirects to it when form is submitted', async () => {
|
||||||
const { user } = setUp();
|
const { user, history } = setUp();
|
||||||
|
|
||||||
await user.type(screen.getByDisplayValue('the_name'), ' edited');
|
await user.type(screen.getByDisplayValue('the_name'), ' edited');
|
||||||
await user.type(screen.getByDisplayValue('the_url'), ' edited');
|
await user.type(screen.getByDisplayValue('the_url'), ' edited');
|
||||||
|
@ -69,6 +66,8 @@ describe('<EditServer />', () => {
|
||||||
url: 'the_url edited',
|
url: 'the_url edited',
|
||||||
apiKey: 'the_api_key',
|
apiKey: 'the_api_key',
|
||||||
});
|
});
|
||||||
expect(navigate).toHaveBeenCalledWith(-1);
|
|
||||||
|
// After saving we go back, to the first route from history's initialEntries
|
||||||
|
expect(history.location.pathname).toEqual('/foo');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
@ -28,6 +28,7 @@ export default defineConfig({
|
||||||
// Vitest config
|
// Vitest config
|
||||||
test: {
|
test: {
|
||||||
globals: true,
|
globals: true,
|
||||||
|
allowOnly: true,
|
||||||
environment: 'jsdom',
|
environment: 'jsdom',
|
||||||
setupFiles: './config/test/setupTests.ts',
|
setupFiles: './config/test/setupTests.ts',
|
||||||
coverage: {
|
coverage: {
|
||||||
|
|
Loading…
Reference in a new issue