Errores de Jest y cómo solucionarlos

Guía práctica de Jest para pruebas en una app con React, TypeScript, Chakra UI y Supabase: errores comunes, mocks y buenas prácticas de testing para proyectos a medida

15 sept 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Introducción: este artículo resume los errores más comunes y sus soluciones que encontré al usar Jest para probar una aplicacion de learning log desarrollada con React, TypeScript, Chakra UI y Supabase. También incluye recomendaciones prácticas y cómo evitarlos en futuros proyectos de desarrollo de software a medida.

1. Error supabaseUrl is required: Situación: durante las pruebas llamé por error al cliente real de un servicio externo (Supabase, Firebase, etc.) y faltaba el archivo .env, provocando un error. Causa: se estaba usando el cliente real cuando se ejecutó Jest, el mock no se aplicó. Solución: crear un mock en src/mocks/supabase.ts para simular las respuestas de la API. Por ejemplo export const supabase = { from: () => ({ select: async () => ({ data: [], error: null }), insert: async () => ({ error: null }), delete: async () => ({ error: null }), update: async () => ({ error: null }) }) } y además configurar moduleNameMapper en jest.config.js para apuntar al mock. Esto evita llamadas externas y hace las pruebas deterministas.

2. Advertencia Received NaN for the value attribute: Situación: apareció una advertencia al pasar NaN a NumberInput de Chakra UI. Causa: la conexión entre Controller de React Hook Form y el input numerico estaba incompleta, rompiendo la conversión de string a numero. Solución: en el Controller usar valueAsNumber: true para forzar el valor a numero y siempre establecer defaultValue a 0 o 1 para definir un valor inicial válido. Con esto desaparecen los warnings y las pruebas son más estables.

3. Unable to find element by text: Situación: las pruebas fallaban porque no encontraban texto. Causa: el texto esperado en el test no coincidía exactamente con el de la interfaz (por ejemplo la implementacion mostraba Study Record y el test buscaba Study Record App) o los mensajes de validacion eran distintos. Solución: ajustar los tests para que coincidan con la UI real, por ejemplo usar expect(await screen.findByText(/Study Record/i)).toBeInTheDocument() y comprobar los mensajes de error exactos que muestra la aplicacion. Mantener sincronizados tests y textos evita falsos negativos.

4. Test Suites 0 of 1 total stuck on RUNS: Situación: la ejecucion de tests se quedaba en RUNS indefinidamente. Causa: el cliente real de Supabase era invocado repetidamente, generando un bucle infinito porque el mock no se aplicó. Solución: asegurarse de incluir jest.mock(../utils/supabase) al inicio del archivo de pruebas y preparar src/mocks/supabase.ts con las respuestas simuladas. Siempre utilizar mocks para servicios externos en los tests unitarios y de integración.

Resumen: la mayor parte de estos problemas se solucionan aplicando mocks correctos, sincronizando los textos de la UI con los tests y manejando correctamente la conversion de tipos en formularios. Implementar buenas practicas de testing reduce tiempo de depuracion y mejora la calidad del software.

Sobre Q2BSTUDIO: en Q2BSTUDIO somos una empresa de desarrollo de software especializada en aplicaciones a medida y software a medida para empresas de todos los tamaños. Ofrecemos servicios que van desde desarrollo de aplicaciones multiplataforma hasta soluciones avanzadas de inteligencia artificial, ciberseguridad y servicios cloud AWS y Azure. Si buscas crear una aplicacion a medida robusta y escalable podemos ayudarte, conoce mas sobre nuestro enfoque en desarrollo buscando soluciones de software a medida y aplicaciones a medida. Tambien trabajamos proyectos de inteligencia artificial para empresas, agentes IA y automatizacion con enfoque en negocio, descubre nuestras capacidades en inteligencia artificial y ia para empresas.

Palabras clave: aplicaciones a medida, software a medida, inteligencia artificial, ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio, ia para empresas, agentes IA, power bi. Si necesitas apoyo en testing, integracion continua, o en asegurar que tus pruebas no dependan de servicios externos, contacta con el equipo de Q2BSTUDIO y optimiza tus procesos de desarrollo y despliegue.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat