Introduce shoehorn as a possible replacement for ts-mockery

This commit is contained in:
Alejandro Celaya
2023-04-13 21:48:29 +02:00
parent f6334c3618
commit 340f4b8fb5
65 changed files with 357 additions and 375 deletions

View File

@@ -1,6 +1,6 @@
import { fireEvent, screen, waitFor } from '@testing-library/react';
import { fromPartial } from '@total-typescript/shoehorn';
import { useNavigate } from 'react-router-dom';
import { Mock } from 'ts-mockery';
import { CreateServer as createCreateServer } from '../../src/servers/CreateServer';
import type { ServerWithId } from '../../src/servers/data';
import { renderWithEvents } from '../__helpers__/setUpTest';
@@ -10,7 +10,7 @@ jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom')
describe('<CreateServer />', () => {
const createServersMock = jest.fn();
const navigate = jest.fn();
const servers = { foo: Mock.of<ServerWithId>({ url: 'https://existing_url.com', apiKey: 'existing_api_key' }) };
const servers = { foo: fromPartial<ServerWithId>({ url: 'https://existing_url.com', apiKey: 'existing_api_key' }) };
const setUp = (serversImported = false, importFailed = false) => {
(useNavigate as any).mockReturnValue(navigate);

View File

@@ -1,7 +1,6 @@
import { screen, waitFor } from '@testing-library/react';
import { fromPartial } from '@total-typescript/shoehorn';
import type { ReactNode } from 'react';
import { Mock } from 'ts-mockery';
import type { ServerWithId } from '../../src/servers/data';
import { DeleteServerButton as createDeleteServerButton } from '../../src/servers/DeleteServerButton';
import { renderWithEvents } from '../__helpers__/setUpTest';
@@ -10,7 +9,7 @@ describe('<DeleteServerButton />', () => {
({ isOpen }) => <>DeleteServerModal {isOpen ? '[Open]' : '[Closed]'}</>,
);
const setUp = (children?: ReactNode) => renderWithEvents(
<DeleteServerButton server={Mock.all<ServerWithId>()} textClassName="button">{children}</DeleteServerButton>,
<DeleteServerButton server={fromPartial({})} textClassName="button">{children}</DeleteServerButton>,
);
it.each([

View File

@@ -1,7 +1,6 @@
import { screen, waitFor } from '@testing-library/react';
import { fromPartial } from '@total-typescript/shoehorn';
import { useNavigate } from 'react-router-dom';
import { Mock } from 'ts-mockery';
import type { ServerWithId } from '../../src/servers/data';
import { DeleteServerModal } from '../../src/servers/DeleteServerModal';
import { renderWithEvents } from '../__helpers__/setUpTest';
import { TestModalWrapper } from '../__helpers__/TestModalWrapper';
@@ -20,7 +19,7 @@ describe('<DeleteServerModal />', () => {
renderModal={(args) => (
<DeleteServerModal
{...args}
server={Mock.of<ServerWithId>({ name: serverName })}
server={fromPartial({ name: serverName })}
deleteServer={deleteServerMock}
/>
)}

View File

@@ -1,6 +1,6 @@
import { fireEvent, screen } from '@testing-library/react';
import { fromPartial } from '@total-typescript/shoehorn';
import { MemoryRouter, useNavigate } from 'react-router-dom';
import { Mock } from 'ts-mockery';
import type { ReachableServer, SelectedServer } from '../../src/servers/data';
import { EditServer as editServerConstruct } from '../../src/servers/EditServer';
import { renderWithEvents } from '../__helpers__/setUpTest';
@@ -11,7 +11,7 @@ describe('<EditServer />', () => {
const ServerError = jest.fn();
const editServerMock = jest.fn();
const navigate = jest.fn();
const defaultSelectedServer = Mock.of<ReachableServer>({
const defaultSelectedServer = fromPartial<ReachableServer>({
id: 'abc123',
name: 'the_name',
url: 'the_url',
@@ -31,7 +31,7 @@ describe('<EditServer />', () => {
afterEach(jest.clearAllMocks);
it('renders nothing if selected server is not reachable', () => {
setUp(Mock.all<SelectedServer>());
setUp(fromPartial<SelectedServer>({}));
expect(screen.queryByText('Edit')).not.toBeInTheDocument();
expect(screen.queryByText('Cancel')).not.toBeInTheDocument();

View File

@@ -1,6 +1,6 @@
import { screen, waitFor } from '@testing-library/react';
import { fromPartial } from '@total-typescript/shoehorn';
import { MemoryRouter } from 'react-router-dom';
import { Mock } from 'ts-mockery';
import type { ServersMap, ServerWithId } from '../../src/servers/data';
import { ManageServers as createManageServers } from '../../src/servers/ManageServers';
import type { ServersExporter } from '../../src/servers/services/ServersExporter';
@@ -8,7 +8,7 @@ import { renderWithEvents } from '../__helpers__/setUpTest';
describe('<ManageServers />', () => {
const exportServers = jest.fn();
const serversExporter = Mock.of<ServersExporter>({ exportServers });
const serversExporter = fromPartial<ServersExporter>({ exportServers });
const useTimeoutToggle = jest.fn().mockReturnValue([false, jest.fn()]);
const ManageServers = createManageServers(
serversExporter,
@@ -16,7 +16,7 @@ describe('<ManageServers />', () => {
useTimeoutToggle,
({ hasAutoConnect }) => <tr><td>ManageServersRow {hasAutoConnect ? '[YES]' : '[NO]'}</td></tr>,
);
const createServerMock = (value: string, autoConnect = false) => Mock.of<ServerWithId>(
const createServerMock = (value: string, autoConnect = false) => fromPartial<ServerWithId>(
{ id: value, name: value, url: value, autoConnect },
);
const setUp = (servers: ServersMap = {}) => renderWithEvents(

View File

@@ -1,6 +1,6 @@
import { screen } from '@testing-library/react';
import { fromPartial } from '@total-typescript/shoehorn';
import { MemoryRouter } from 'react-router-dom';
import { Mock } from 'ts-mockery';
import type { ServerWithId } from '../../src/servers/data';
import { ManageServersRowDropdown as createManageServersRowDropdown } from '../../src/servers/ManageServersRowDropdown';
import { renderWithEvents } from '../__helpers__/setUpTest';
@@ -11,7 +11,7 @@ describe('<ManageServersRowDropdown />', () => {
);
const setAutoConnect = jest.fn();
const setUp = (autoConnect = false) => {
const server = Mock.of<ServerWithId>({ id: 'abc123', autoConnect });
const server = fromPartial<ServerWithId>({ id: 'abc123', autoConnect });
return renderWithEvents(
<MemoryRouter>
<ManageServersRowDropdown setAutoConnect={setAutoConnect} server={server} />

View File

@@ -1,14 +1,9 @@
import { screen, waitFor } from '@testing-library/react';
import { fromPartial } from '@total-typescript/shoehorn';
import { MemoryRouter } from 'react-router-dom';
import { Mock } from 'ts-mockery';
import type { MercureInfo } from '../../src/mercure/reducers/mercureInfo';
import type { ReachableServer } from '../../src/servers/data';
import { Overview as overviewCreator } from '../../src/servers/Overview';
import type { Settings } from '../../src/settings/reducers/settings';
import type { ShortUrlsList as ShortUrlsListState } from '../../src/short-urls/reducers/shortUrlsList';
import type { TagsList } from '../../src/tags/reducers/tagsList';
import { prettify } from '../../src/utils/helpers/numbers';
import type { VisitsOverview } from '../../src/visits/reducers/visitsOverview';
import { renderWithEvents } from '../__helpers__/setUpTest';
describe('<Overview />', () => {
@@ -28,18 +23,18 @@ describe('<Overview />', () => {
listShortUrls={listShortUrls}
listTags={listTags}
loadVisitsOverview={loadVisitsOverview}
shortUrlsList={Mock.of<ShortUrlsListState>({ loading, shortUrls })}
tagsList={Mock.of<TagsList>({ loading, tags: ['foo', 'bar', 'baz'] })}
visitsOverview={Mock.of<VisitsOverview>({
shortUrlsList={fromPartial({ loading, shortUrls })}
tagsList={fromPartial({ loading, tags: ['foo', 'bar', 'baz'] })}
visitsOverview={fromPartial({
loading,
nonOrphanVisits: { total: 3456, bots: 1000, nonBots: 2456 },
orphanVisits: { total: 28, bots: 15, nonBots: 13 },
})}
selectedServer={Mock.of<ReachableServer>({ id: serverId })}
selectedServer={fromPartial({ id: serverId })}
createNewVisits={jest.fn()}
loadMercureInfo={jest.fn()}
mercureInfo={Mock.all<MercureInfo>()}
settings={Mock.of<Settings>({ visits: { excludeBots } })}
mercureInfo={fromPartial<MercureInfo>({})}
settings={fromPartial({ visits: { excludeBots } })}
/>
</MemoryRouter>,
);

View File

@@ -1,16 +1,16 @@
import { screen } from '@testing-library/react';
import { fromPartial } from '@total-typescript/shoehorn';
import { values } from 'ramda';
import { MemoryRouter } from 'react-router-dom';
import { Mock } from 'ts-mockery';
import type { ServersMap, ServerWithId } from '../../src/servers/data';
import type { ServersMap } from '../../src/servers/data';
import { ServersDropdown } from '../../src/servers/ServersDropdown';
import { renderWithEvents } from '../__helpers__/setUpTest';
describe('<ServersDropdown />', () => {
const fallbackServers: ServersMap = {
'1a': Mock.of<ServerWithId>({ name: 'foo', id: '1a' }),
'2b': Mock.of<ServerWithId>({ name: 'bar', id: '2b' }),
'3c': Mock.of<ServerWithId>({ name: 'baz', id: '3c' }),
'1a': fromPartial({ name: 'foo', id: '1a' }),
'2b': fromPartial({ name: 'bar', id: '2b' }),
'3c': fromPartial({ name: 'baz', id: '3c' }),
};
const setUp = (servers: ServersMap = fallbackServers) => renderWithEvents(
<MemoryRouter><ServersDropdown servers={servers} selectedServer={null} /></MemoryRouter>,

View File

@@ -1,13 +1,13 @@
import { render, screen } from '@testing-library/react';
import { fromPartial } from '@total-typescript/shoehorn';
import { MemoryRouter } from 'react-router-dom';
import { Mock } from 'ts-mockery';
import type { ServerWithId } from '../../src/servers/data';
import { ServersListGroup } from '../../src/servers/ServersListGroup';
describe('<ServersListGroup />', () => {
const servers = [
Mock.of<ServerWithId>({ name: 'foo', id: '123' }),
Mock.of<ServerWithId>({ name: 'bar', id: '456' }),
const servers: ServerWithId[] = [
fromPartial({ name: 'foo', id: '123' }),
fromPartial({ name: 'bar', id: '456' }),
];
const setUp = (params: { servers?: ServerWithId[]; withChildren?: boolean; embedded?: boolean }) => {
const { servers = [], withChildren = true, embedded } = params;

View File

@@ -1,5 +1,5 @@
import { screen } from '@testing-library/react';
import { Mock } from 'ts-mockery';
import { fromPartial } from '@total-typescript/shoehorn';
import type { ServerData } from '../../../src/servers/data';
import { DuplicatedServersModal } from '../../../src/servers/helpers/DuplicatedServersModal';
import { renderWithEvents } from '../../__helpers__/setUpTest';
@@ -10,15 +10,16 @@ describe('<DuplicatedServersModal />', () => {
const setUp = (duplicatedServers: ServerData[] = []) => renderWithEvents(
<DuplicatedServersModal isOpen duplicatedServers={duplicatedServers} onDiscard={onDiscard} onSave={onSave} />,
);
const mockServer = (data: Partial<ServerData> = {}) => fromPartial<ServerData>(data);
beforeEach(jest.clearAllMocks);
it.each([
[[], 0],
[[Mock.all<ServerData>()], 2],
[[Mock.all<ServerData>(), Mock.all<ServerData>()], 2],
[[Mock.all<ServerData>(), Mock.all<ServerData>(), Mock.all<ServerData>()], 3],
[[Mock.all<ServerData>(), Mock.all<ServerData>(), Mock.all<ServerData>(), Mock.all<ServerData>()], 4],
[[mockServer()], 2],
[[mockServer(), mockServer()], 2],
[[mockServer(), mockServer(), mockServer()], 3],
[[mockServer(), mockServer(), mockServer(), mockServer()], 4],
])('renders expected amount of items', (duplicatedServers, expectedItems) => {
setUp(duplicatedServers);
expect(screen.queryAllByRole('listitem')).toHaveLength(expectedItems);
@@ -26,7 +27,7 @@ describe('<DuplicatedServersModal />', () => {
it.each([
[
[Mock.all<ServerData>()],
[mockServer()],
{
header: 'Duplicated server',
firstParagraph: 'There is already a server with:',
@@ -35,7 +36,7 @@ describe('<DuplicatedServersModal />', () => {
},
],
[
[Mock.all<ServerData>(), Mock.all<ServerData>()],
[mockServer(), mockServer()],
{
header: 'Duplicated servers',
firstParagraph: 'The next servers already exist:',
@@ -54,10 +55,10 @@ describe('<DuplicatedServersModal />', () => {
it.each([
[[]],
[[Mock.of<ServerData>({ url: 'url', apiKey: 'apiKey' })]],
[[mockServer({ url: 'url', apiKey: 'apiKey' })]],
[[
Mock.of<ServerData>({ url: 'url_1', apiKey: 'apiKey_1' }),
Mock.of<ServerData>({ url: 'url_2', apiKey: 'apiKey_2' }),
mockServer({ url: 'url_1', apiKey: 'apiKey_1' }),
mockServer({ url: 'url_2', apiKey: 'apiKey_2' }),
]],
])('displays provided server data', (duplicatedServers) => {
setUp(duplicatedServers);

View File

@@ -1,5 +1,5 @@
import { fireEvent, screen, waitFor } from '@testing-library/react';
import { Mock } from 'ts-mockery';
import { fromPartial } from '@total-typescript/shoehorn';
import type { ServersMap, ServerWithId } from '../../../src/servers/data';
import type {
ImportServersBtnProps } from '../../../src/servers/helpers/ImportServersBtn';
@@ -13,7 +13,7 @@ describe('<ImportServersBtn />', () => {
const onImportMock = jest.fn();
const createServersMock = jest.fn();
const importServersFromFile = jest.fn().mockResolvedValue([]);
const serversImporterMock = Mock.of<ServersImporter>({ importServersFromFile });
const serversImporterMock = fromPartial<ServersImporter>({ importServersFromFile });
const ImportServersBtn = createImportServersBtn(serversImporterMock);
const setUp = (props: Partial<ImportServersBtnProps> = {}, servers: ServersMap = {}) => renderWithEvents(
<ImportServersBtn
@@ -67,8 +67,8 @@ describe('<ImportServersBtn />', () => {
['Save anyway', true],
['Discard', false],
])('creates expected servers depending on selected option in modal', async (btnName, savesDuplicatedServers) => {
const existingServer = Mock.of<ServerWithId>({ id: 'abc', url: 'existingUrl', apiKey: 'existingApiKey' });
const newServer = Mock.of<ServerWithId>({ url: 'newUrl', apiKey: 'newApiKey' });
const existingServer = fromPartial<ServerWithId>({ id: 'abc', url: 'existingUrl', apiKey: 'existingApiKey' });
const newServer = fromPartial<ServerWithId>({ url: 'newUrl', apiKey: 'newApiKey' });
const { container, user } = setUp({}, { abc: existingServer });
const input = container.querySelector('[type=file]');
importServersFromFile.mockResolvedValue([existingServer, newServer]);

View File

@@ -1,6 +1,6 @@
import { render, screen } from '@testing-library/react';
import { fromPartial } from '@total-typescript/shoehorn';
import { MemoryRouter } from 'react-router-dom';
import { Mock } from 'ts-mockery';
import type { NonReachableServer, NotFoundServer } from '../../../src/servers/data';
import { ServerError as createServerError } from '../../../src/servers/helpers/ServerError';
@@ -9,7 +9,7 @@ describe('<ServerError />', () => {
it.each([
[
Mock.all<NotFoundServer>(),
fromPartial<NotFoundServer>({}),
{
found: ['Could not find this Shlink server.'],
notFound: [
@@ -20,7 +20,7 @@ describe('<ServerError />', () => {
},
],
[
Mock.of<NonReachableServer>({ id: 'abc123' }),
fromPartial<NonReachableServer>({ id: 'abc123' }),
{
found: [
'Oops! Could not connect to this Shlink server.',

View File

@@ -1,4 +1,4 @@
import { Mock } from 'ts-mockery';
import { fromPartial } from '@total-typescript/shoehorn';
import type { HttpClient } from '../../../src/common/services/HttpClient';
import { fetchServers } from '../../../src/servers/reducers/remoteServers';
@@ -8,7 +8,7 @@ describe('remoteServersReducer', () => {
describe('fetchServers', () => {
const dispatch = jest.fn();
const fetchJson = jest.fn();
const httpClient = Mock.of<HttpClient>({ fetchJson });
const httpClient = fromPartial<HttpClient>({ fetchJson });
it.each([
[

View File

@@ -1,4 +1,4 @@
import { Mock } from 'ts-mockery';
import { fromPartial } from '@total-typescript/shoehorn';
import { v4 as uuid } from 'uuid';
import type { ShlinkApiClient } from '../../../src/api/services/ShlinkApiClient';
import type { ShlinkState } from '../../../src/container/types';
@@ -15,7 +15,7 @@ import {
describe('selectedServerReducer', () => {
const dispatch = jest.fn();
const health = jest.fn();
const buildApiClient = jest.fn().mockReturnValue(Mock.of<ShlinkApiClient>({ health }));
const buildApiClient = jest.fn().mockReturnValue(fromPartial<ShlinkApiClient>({ health }));
const selectServer = selectServerCreator(buildApiClient);
const { reducer } = selectedServerReducerCreator(selectServer);
@@ -26,8 +26,7 @@ describe('selectedServerReducer', () => {
expect(reducer(null, resetSelectedServer())).toBeNull());
it('returns selected server when action is SELECT_SERVER', () => {
const payload = Mock.of<RegularServer>({ id: 'abc123' });
const payload = fromPartial<RegularServer>({ id: 'abc123' });
expect(reducer(null, selectServer.fulfilled(payload, '', ''))).toEqual(payload);
});
});
@@ -66,7 +65,7 @@ describe('selectedServerReducer', () => {
it('dispatches error when health endpoint fails', async () => {
const id = uuid();
const getState = createGetStateMock(id);
const expectedSelectedServer = Mock.of<NonReachableServer>({ id, serverNotReachable: true });
const expectedSelectedServer = fromPartial<NonReachableServer>({ id, serverNotReachable: true });
health.mockRejectedValue({});
@@ -78,7 +77,7 @@ describe('selectedServerReducer', () => {
it('dispatches error when server is not found', async () => {
const id = uuid();
const getState = jest.fn(() => Mock.of<ShlinkState>({ servers: {} }));
const getState = jest.fn(() => fromPartial<ShlinkState>({ servers: {} }));
const expectedSelectedServer: NotFoundServer = { serverNotFound: true };
await selectServer(id)(dispatch, getState, {});
@@ -95,9 +94,9 @@ describe('selectedServerReducer', () => {
const { middleware } = selectServerListener(selectServer, loadMercureInfo);
it.each([
[Mock.of<ReachableServer>({ version: '1.2.3' }), 1],
[Mock.of<NotFoundServer>({ serverNotFound: true }), 0],
[Mock.of<NonReachableServer>({ serverNotReachable: true }), 0],
[fromPartial<ReachableServer>({ version: '1.2.3' }), 1],
[fromPartial<NotFoundServer>({ serverNotFound: true }), 0],
[fromPartial<NonReachableServer>({ serverNotReachable: true }), 0],
])('dispatches loadMercureInfo when provided server is reachable', (payload, expectedCalls) => {
middleware({ dispatch, getState })(jest.fn())({
payload,
@@ -110,7 +109,7 @@ describe('selectedServerReducer', () => {
it('does not dispatch loadMercureInfo when action is not of the proper type', () => {
middleware({ dispatch, getState })(jest.fn())({
payload: Mock.of<ReachableServer>({ version: '1.2.3' }),
payload: fromPartial<ReachableServer>({ version: '1.2.3' }),
type: 'something_else',
});

View File

@@ -1,6 +1,6 @@
import { fromPartial } from '@total-typescript/shoehorn';
import { dissoc, values } from 'ramda';
import { Mock } from 'ts-mockery';
import type { RegularServer, ServerWithId } from '../../../src/servers/data';
import type { RegularServer, ServersMap, ServerWithId } from '../../../src/servers/data';
import {
createServers,
deleteServer,
@@ -10,9 +10,9 @@ import {
} from '../../../src/servers/reducers/servers';
describe('serversReducer', () => {
const list = {
abc123: Mock.of<RegularServer>({ id: 'abc123' }),
def456: Mock.of<RegularServer>({ id: 'def456' }),
const list: ServersMap = {
abc123: fromPartial({ id: 'abc123' }),
def456: fromPartial({ id: 'def456' }),
};
afterEach(jest.clearAllMocks);
@@ -31,12 +31,12 @@ describe('serversReducer', () => {
}));
it('removes server when action is DELETE_SERVER', () =>
expect(serversReducer(list, deleteServer(Mock.of<ServerWithId>({ id: 'abc123' })))).toEqual({
expect(serversReducer(list, deleteServer(fromPartial<ServerWithId>({ id: 'abc123' })))).toEqual({
def456: { id: 'def456' },
}));
it('appends server when action is CREATE_SERVERS', () =>
expect(serversReducer(list, createServers([Mock.of<ServerWithId>({ id: 'ghi789' })]))).toEqual({
expect(serversReducer(list, createServers([fromPartial<ServerWithId>({ id: 'ghi789' })]))).toEqual({
abc123: { id: 'abc123' },
def456: { id: 'def456' },
ghi789: { id: 'ghi789' },
@@ -46,7 +46,7 @@ describe('serversReducer', () => {
[true],
[false],
])('returns state as it is when trying to set auto-connect on invalid server', (autoConnect) =>
expect(serversReducer(list, setAutoConnect(Mock.of<ServerWithId>({ id: 'invalid' }), autoConnect))).toEqual({
expect(serversReducer(list, setAutoConnect(fromPartial<ServerWithId>({ id: 'invalid' }), autoConnect))).toEqual({
abc123: { id: 'abc123' },
def456: { id: 'def456' },
}));
@@ -59,7 +59,7 @@ describe('serversReducer', () => {
expect(serversReducer(
listWithDisabledAutoConnect,
setAutoConnect(Mock.of<ServerWithId>({ id: 'abc123' }), false),
setAutoConnect(fromPartial<ServerWithId>({ id: 'abc123' }), false),
)).toEqual({
abc123: { id: 'abc123', autoConnect: false },
def456: { id: 'def456' },
@@ -74,7 +74,7 @@ describe('serversReducer', () => {
expect(serversReducer(
listWithEnabledAutoConnect,
setAutoConnect(Mock.of<ServerWithId>({ id: 'def456' }), true),
setAutoConnect(fromPartial<ServerWithId>({ id: 'def456' }), true),
)).toEqual({
abc123: { id: 'abc123', autoConnect: false },
def456: { id: 'def456', autoConnect: true },
@@ -94,7 +94,7 @@ describe('serversReducer', () => {
describe('deleteServer', () => {
it('returns expected action', () => {
const serverToDelete = Mock.of<RegularServer>({ id: 'abc123' });
const serverToDelete = fromPartial<RegularServer>({ id: 'abc123' });
const { payload } = deleteServer(serverToDelete);
expect(payload).toEqual({ id: 'abc123' });
@@ -122,7 +122,7 @@ describe('serversReducer', () => {
[true],
[false],
])('returns expected action', (autoConnect) => {
const serverToEdit = Mock.of<RegularServer>({ id: 'abc123' });
const serverToEdit = fromPartial<RegularServer>({ id: 'abc123' });
const { payload } = setAutoConnect(serverToEdit, autoConnect);
expect(payload).toEqual({ serverId: 'abc123', autoConnect });

View File

@@ -1,10 +1,10 @@
import { Mock } from 'ts-mockery';
import { fromPartial } from '@total-typescript/shoehorn';
import { ServersExporter } from '../../../src/servers/services/ServersExporter';
import type { LocalStorage } from '../../../src/utils/services/LocalStorage';
import { appendChild, removeChild, windowMock } from '../../__mocks__/Window.mock';
describe('ServersExporter', () => {
const storageMock = Mock.of<LocalStorage>({
const storageMock = fromPartial<LocalStorage>({
get: jest.fn(() => ({
abc123: {
id: 'abc123',
@@ -16,7 +16,7 @@ describe('ServersExporter', () => {
name: 'bar',
autoConnect: false,
},
})),
} as any)),
});
const erroneousToCsv = jest.fn(() => {
throw new Error('');
@@ -31,7 +31,7 @@ describe('ServersExporter', () => {
beforeEach(() => {
originalConsole = global.console;
global.console = Mock.of<Console>({ error });
global.console = fromPartial<Console>({ error });
(global as any).Blob = class Blob {};
(global as any).URL = { createObjectURL: () => '' };
});

View File

@@ -1,16 +1,16 @@
import { Mock } from 'ts-mockery';
import { fromPartial } from '@total-typescript/shoehorn';
import type { RegularServer } from '../../../src/servers/data';
import { ServersImporter } from '../../../src/servers/services/ServersImporter';
describe('ServersImporter', () => {
const servers: RegularServer[] = [Mock.all<RegularServer>(), Mock.all<RegularServer>()];
const servers: RegularServer[] = [fromPartial<RegularServer>({}), fromPartial<RegularServer>({})];
const csvjsonMock = jest.fn().mockResolvedValue(servers);
const readAsText = jest.fn();
const fileReaderMock = Mock.of<FileReader>({
const fileReaderMock = fromPartial<FileReader>({
readAsText,
addEventListener: (_eventName: string, listener: (e: ProgressEvent<FileReader>) => void) => listener(
Mock.of<ProgressEvent<FileReader>>({ target: { result: '' } }),
),
addEventListener: ((_eventName: string, listener: (e: ProgressEvent<FileReader>) => void) => listener(
fromPartial({ target: { result: '' } }),
)) as any,
});
const importer = new ServersImporter(csvjsonMock, () => fileReaderMock);
@@ -28,7 +28,7 @@ describe('ServersImporter', () => {
csvjsonMock.mockRejectedValue(expectedError);
await expect(importer.importServersFromFile(Mock.of<File>({ type: 'text/html' }))).rejects.toEqual(expectedError);
await expect(importer.importServersFromFile(fromPartial({ type: 'text/html' }))).rejects.toEqual(expectedError);
});
it.each([
@@ -57,7 +57,7 @@ describe('ServersImporter', () => {
])('rejects with error if provided file does not parse to valid list of servers', async (parsedObject) => {
csvjsonMock.mockResolvedValue(parsedObject);
await expect(importer.importServersFromFile(Mock.of<File>({ type: 'text/html' }))).rejects.toEqual(
await expect(importer.importServersFromFile(fromPartial({ type: 'text/html' }))).rejects.toEqual(
new Error('Provided file does not have the right format.'),
);
});
@@ -78,7 +78,7 @@ describe('ServersImporter', () => {
csvjsonMock.mockResolvedValue(expectedServers);
const result = await importer.importServersFromFile(Mock.all<File>());
const result = await importer.importServersFromFile(fromPartial({}));
expect(result).toEqual(expectedServers);
expect(readAsText).toHaveBeenCalledTimes(1);