Prueba de la API SSR de Next.js con Playwright y MSW

Guía para automatizar pruebas de integración de APIs SSR en Next.js con Playwright y MSW, usando un mock bridge en Node para controlar overrides con once y pruebas en CI

8 sept 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Introducción: En este artículo explico cómo automatizar pruebas de integración para APIs SSR de Next.js usando Playwright combinado con Mock Service Worker MSW. La dificultad principal es que SSR ejecuta las llamadas HTTP en el servidor, por lo que las técnicas habituales de mocking en el navegador no funcionan sin un puente que intercepte las peticiones en Node.

Resumen del reto: Playwright está pensado para pruebas en navegador y por defecto facilita CSR. Para SSR hay que interceptar las llamadas que hace el servidor Next.js. MSW puede ejecutar mocks en Node mediante setupServer, pero hay que controlar cómo y cuándo se sobrescriben las respuestas para cubrir diferentes escenarios de prueba.

Solución clave: ejecutar la app Next en su puerto por defecto y levantar un servidor de mocks en otro puerto por ejemplo 3001. Crear un mock bridge que arranque MSW en Node y exponga endpoints de control que las pruebas puedan invocar para cambiar la respuesta mock mediante server.use con la opción once true. De este modo cada override afecta solo a la siguiente petición y vuelve al handler por defecto sin necesidad de llamadas a resetHandlers complicadas. Al ejecutar Playwright conviene desactivar la ejecución paralela configurando fullyParallel false y workers 1 para evitar conflictos por estado global en MSW.

Pasos principales y comandos: npx create-next-app@latest my-app --yes cd my-app npm init playwright@latest npm i msw --save-dev npm install -D tsx Crear archivos mocks handlers server y mock-server para levantar MSW con setupServer y exponer POST /api/switch-pokemon que llame a setMockPokemon. Ejecutar en terminales separados: npx tsx mock-server.ts npm run dev npx playwright test.

Detalles técnicos importantes: usar server.use con http.get para el endpoint interceptado y pasar la opción once true para que el override sea de un solo uso. En el bridge reenvía las peticiones hacia MSW y devuelve la respuesta al cliente; maneja respuestas 500 sin payload JSON. En Playwright, esperar a networkidle después de navegar para asegurarse de que la petición SSR ha terminado y capturar capturas de pantalla para verificación visual.

Buenas prácticas: mantener el mock por defecto sencillo, cambiar solo lo necesario en cada test, evitar cambios globales que persistan entre pruebas y limpiar recursos al finalizar. Si necesitas rendimiento y paralelismo investiga maneras de aislar el estado de MSW entre workers o levantar instancias independientes del bridge por cada worker.

Sobre Q2BSTUDIO: En Q2BSTUDIO somos una empresa de desarrollo de software que crea aplicaciones a medida y software a medida adaptado a necesidades empresariales. Somos especialistas en inteligencia artificial y contamos con soluciones de ia para empresas y agentes IA para automatizar procesos y extraer valor de los datos. También ofrecemos servicios de ciberseguridad y pentesting para proteger tus sistemas, así como servicios cloud aws y azure para infraestructura escalable y segura. Si necesitas avanzar en transformación digital podemos ayudarte con proyectos de automatización y soluciones de inteligencia de negocio y power bi.

Si te interesa desarrollar una solución personalizada consulta nuestra página de desarrollo de aplicaciones y software a medida en desarrollo de aplicaciones y software a medida y para proyectos de inteligencia artificial visita servicios de inteligencia artificial. Palabras clave relevantes incluidas naturalmente en este contenido son 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.

Conclusión: Playwright junto con MSW es una buena combinación para probar APIs SSR en Next.js si se implementa un puente de mocks en Node y se gestionan bien los overrides con once true. En Q2BSTUDIO ayudamos a implementar estas arquitecturas y a integrar pruebas automatizadas en pipelines de CI para obtener despliegues más seguros y fiables.

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