83 lines
3.8 KiB
TypeScript
83 lines
3.8 KiB
TypeScript
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
|
import { McpConfigPanel } from './mcp-config-panel';
|
|
|
|
// Comandos Tauri dos servidores MCP e o toast viram fakes; nenhum servidor MCP é iniciado.
|
|
const { invokeMock, toast } = vi.hoisted(() => ({ invokeMock: vi.fn(), toast: vi.fn() }));
|
|
vi.mock('@tauri-apps/api/core', () => ({ invoke: invokeMock }));
|
|
vi.mock('@/hooks/use-toast', () => ({ useToast: () => ({ toast }) }));
|
|
|
|
let saveResult: () => Promise<void> = async () => {};
|
|
|
|
beforeEach(() => {
|
|
saveResult = async () => {};
|
|
toast.mockReset();
|
|
invokeMock.mockReset();
|
|
invokeMock.mockImplementation(async (cmd: string) => {
|
|
if (cmd === 'load_mcp_config') return { mcpServers: {} };
|
|
if (cmd === 'list_mcp_server_status') return [];
|
|
if (cmd === 'get_mcp_config_path_command') return '/cfg/mcp.json';
|
|
if (cmd === 'save_mcp_config') return saveResult();
|
|
throw new Error(`comando inesperado: ${cmd}`);
|
|
});
|
|
vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
});
|
|
|
|
async function saveWith(json: string) {
|
|
render(<McpConfigPanel />);
|
|
const editor = await screen.findByRole('textbox'); // durante o carregamento só há o spinner
|
|
await waitFor(() => expect((editor as HTMLTextAreaElement).value).toContain('mcpServers'));
|
|
fireEvent.change(editor, { target: { value: json } });
|
|
await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Salvar' })));
|
|
}
|
|
|
|
const saved = () => invokeMock.mock.calls.filter(([cmd]) => cmd === 'save_mcp_config').map(([, args]) => args);
|
|
const lastToast = () => toast.mock.calls[toast.mock.calls.length - 1][0];
|
|
|
|
describe('McpConfigPanel.saveConfig', () => {
|
|
it('JSON em branco: avisa e não salva', async () => {
|
|
await saveWith(' ');
|
|
expect(lastToast()).toMatchObject({ title: 'Erro', description: expect.stringContaining('JSON vazio') });
|
|
expect(saved()).toEqual([]);
|
|
});
|
|
|
|
it('JSON inválido: erro de JSON e não salva', async () => {
|
|
await saveWith('{ "mcpServers": ');
|
|
expect(lastToast()).toMatchObject({ title: 'Erro de JSON', description: expect.stringContaining('JSON inválido:') });
|
|
expect(saved()).toEqual([]);
|
|
});
|
|
|
|
it.each(['null', '"texto"'])('JSON %s (não objeto): avisa e não salva', async (json) => {
|
|
await saveWith(json);
|
|
expect(lastToast()).toMatchObject({ description: 'Configuração inválida: deve ser um objeto JSON.' });
|
|
expect(saved()).toEqual([]);
|
|
});
|
|
|
|
it.each([
|
|
['sem mcpServers', '{"outro": 1}'],
|
|
['mcpServers não objeto', '{"mcpServers": "x"}'],
|
|
])('%s: salva a estrutura mínima', async (_n, json) => {
|
|
await saveWith(json);
|
|
expect(saved()).toEqual([{ config: { mcpServers: {} } }]);
|
|
});
|
|
|
|
it('config válida: salva só mcpServers, avisa sucesso e recarrega o status', async () => {
|
|
const servers = { fs: { command: 'npx', args: ['-y', 'server-fs'] } };
|
|
await saveWith(JSON.stringify({ mcpServers: servers, extra: true }));
|
|
expect(saved()).toEqual([{ config: { mcpServers: servers } }]);
|
|
expect(lastToast()).toMatchObject({ title: 'Sucesso' });
|
|
expect(invokeMock.mock.calls.filter(([cmd]) => cmd === 'list_mcp_server_status')).toHaveLength(2);
|
|
expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).toBe(JSON.stringify({ mcpServers: servers }, null, 2));
|
|
});
|
|
|
|
it.each([
|
|
['Error', new Error('permissão negada'), 'Falha ao salvar configuração MCP: permissão negada'],
|
|
['string do Rust', 'disco cheio', 'Falha ao salvar configuração MCP: Erro desconhecido'],
|
|
])('backend falha com %s: toast de erro', async (_n, error, description) => {
|
|
saveResult = async () => { throw error; };
|
|
await saveWith('{"mcpServers": {}}');
|
|
expect(lastToast()).toMatchObject({ title: 'Erro', description });
|
|
expect(screen.getByRole('button', { name: 'Salvar' })).toHaveProperty('disabled', false);
|
|
});
|
|
});
|