FigmaMind MCP Server
by joao-loker
Verified
- FigmaMind
- tests
/**
* Teste para verificar a funcionalidade do endpoint REST de transformação do Figma
*/
import axios from 'axios';
import dotenv from 'dotenv';
import fs from 'fs-extra';
import path from 'path';
import { spawn } from 'child_process';
// Carregar variáveis de ambiente
dotenv.config();
// URL do arquivo Figma para testar
const FIGMA_URL = 'https://www.figma.com/design/Mlgjf3cCMzOIwM27GLx81Y/New-Onboarding?node-id=2367-11578&t=RSCjmnJyU6JsPpzQ-4';
// URL da API
const API_URL = 'http://localhost:3000';
// Diretório para salvar a saída do teste
const TEST_OUTPUT_DIR = path.resolve('tests/output');
fs.ensureDirSync(TEST_OUTPUT_DIR);
// Objeto para armazenar a instância do servidor
let serverProcess: any;
/**
* Inicia o servidor para os testes
*/
async function startServer(): Promise<void> {
return new Promise((resolve, reject) => {
console.log('Iniciando o servidor...');
// Inicia o servidor em um processo separado
serverProcess = spawn('node', ['dist/src/index.js'], {
env: { ...process.env, PORT: '3000' },
stdio: 'inherit'
});
// Aguarda um tempo para o servidor iniciar
setTimeout(() => {
console.log('Servidor iniciado');
resolve();
}, 3000);
// Lidar com erros
serverProcess.on('error', (error: Error) => {
console.error('Erro ao iniciar o servidor:', error);
reject(error);
});
});
}
/**
* Encerra o servidor após os testes
*/
function stopServer(): void {
if (serverProcess) {
console.log('Encerrando o servidor...');
serverProcess.kill();
serverProcess = null;
console.log('Servidor encerrado');
}
}
/**
* Testa o endpoint REST de transformação do Figma
*/
async function testFigmaTransformApi(): Promise<any> {
console.log('Iniciando teste do endpoint REST de transformação do Figma...');
console.log(`URL do Figma: ${FIGMA_URL}`);
try {
// Fazer requisição para o endpoint de transformação
console.log('Enviando requisição para o endpoint de transformação...');
const response = await axios.post(
`${API_URL}/api/transform`,
{ figmaUrl: FIGMA_URL },
{ timeout: 60000 } // 60 segundos de timeout, pois pode demorar
);
// Verificar se a resposta é válida
if (response.status !== 200 || !response.data) {
throw new Error(`Requisição falhou com status ${response.status}`);
}
console.log('Resposta recebida do servidor');
// Salvar resposta para inspeção
await fs.writeJson(
path.join(TEST_OUTPUT_DIR, 'api-transform-response.json'),
response.data,
{ spaces: 2 }
);
// Validar a resposta
const validationResults = validateApiResponse(response.data);
// Exibir resultados
console.log('\n==== RESULTADOS DO TESTE DE API ====');
console.log(`Status da resposta: ${response.status}`);
console.log(`Sucesso: ${response.data.success ? 'SIM' : 'NÃO'}`);
console.log(`Mensagem: ${response.data.message}`);
console.log(`Total de componentes: ${response.data.data?.componentsCount || 0}`);
console.log(`Validações bem-sucedidas: ${validationResults.success}`);
console.log(`Validações com falha: ${validationResults.failures.length}`);
if (validationResults.failures.length > 0) {
console.log('\nFalhas de validação:');
validationResults.failures.forEach((failure, index) => {
console.log(`${index + 1}. ${failure}`);
});
}
console.log('\nTeste concluído!');
console.log(`Resposta completa salva em: ${path.join(TEST_OUTPUT_DIR, 'api-transform-response.json')}`);
return {
success: validationResults.failures.length === 0,
responseStatus: response.status,
validationResults
};
} catch (error) {
console.error('Erro durante o teste da API de transformação:', error);
throw error;
}
}
/**
* Valida a resposta da API
*/
function validateApiResponse(response: any) {
const failures: string[] = [];
// 1. Verificar estrutura básica da resposta
if (!response.success) {
failures.push('A resposta indica que a operação não teve sucesso');
}
if (!response.message) {
failures.push('A resposta não contém uma mensagem');
}
if (!response.data) {
failures.push('A resposta não contém dados');
return { success: false, failures };
}
// 2. Verificar estrutura dos dados
const { data } = response;
if (!data.source) {
failures.push('Os dados não contêm a propriedade "source"');
}
if (!data.componentsCount || typeof data.componentsCount !== 'number') {
failures.push('A propriedade "componentsCount" está ausente ou não é um número');
}
if (!data.screen) {
failures.push('Os dados não contêm a propriedade "screen"');
return { success: false, failures };
}
// 3. Verificar estrutura do screen
const { screen } = data;
if (!screen.name) {
failures.push('O screen não tem nome');
}
if (!screen.size || !screen.size.width || !screen.size.height) {
failures.push('O screen não tem dimensões válidas');
}
if (!screen.layout) {
failures.push('O screen não tem layout');
return { success: false, failures };
}
// 4. Verificar componentes
if (!screen.layout.orderedElements || !Array.isArray(screen.layout.orderedElements)) {
failures.push('Não existem elementos ordenados no layout');
} else if (screen.layout.orderedElements.length === 0) {
failures.push('Nenhum componente foi encontrado');
} else {
// Verificar propriedades básicas de alguns componentes
const components = screen.layout.orderedElements;
const sampleSize = Math.min(5, components.length);
for (let i = 0; i < sampleSize; i++) {
const component = components[i];
if (!component.id) {
failures.push(`Componente ${i} não tem ID`);
}
if (!component.name) {
failures.push(`Componente ${i} não tem nome`);
}
if (!component.type) {
failures.push(`Componente ${i} não tem tipo`);
}
}
// Verificar se existem componentes de tipos diferentes
const types = new Set(components.map((c: any) => c.type));
console.log(`Tipos de componentes encontrados: ${Array.from(types).join(', ')}`);
}
return {
success: failures.length === 0,
failures
};
}
/**
* Função principal para executar o teste
*/
async function runTest(): Promise<void> {
try {
// Iniciar o servidor
await startServer();
// Executar o teste
await testFigmaTransformApi();
console.log('\nTeste concluído com sucesso!');
} catch (error) {
console.error('Erro ao executar o teste:', error);
} finally {
// Parar o servidor
stopServer();
}
}
// Executar o teste se este arquivo for executado diretamente
if (require.main === module) {
runTest()
.then(() => {
process.exit(0);
})
.catch(error => {
console.error('Teste falhou:', error);
stopServer();
process.exit(1);
});
}
export { runTest, testFigmaTransformApi };