Pruebas de extremo a extremo para API: Ahorrando Nervios y Horas

Rate this content
Bookmark

Tener una cobertura de pruebas adecuada significa mucho para una buena API. Pero lo que puede hacer que toda la vida sea patética es el interminable simulacro de datos y funciones para las pruebas de integración. Cada vez que cambias el código, necesitas arreglar la simulación. Después de varias iteraciones, el pensamiento correcto es: ¿qué salió mal?


Un enfoque alternativo son las pruebas de extremo a extremo para la API. Que requieren solo simulaciones mínimas y preparación de datos. El resto es código puro de tu API. Cambia el código, las pruebas de extremo a extremo siguen siendo las mismas.

Esta charla trata sobre mi experiencia de cambiar de las pruebas de integración a las pruebas de extremo a extremo para la API, pros y contras, y cómo empecé a sentirme feliz con las pruebas.

8 min
19 Nov, 2021

Video Summary and Transcription

Esta charla discute el uso de pruebas de extremo a extremo para el desarrollo de API, específicamente utilizando el framework Nest.js. Se explica el proceso de inicialización de la API Nest para las pruebas, junto con opciones de personalización como la anulación de los guardias de autenticación. Se destacan los beneficios de las pruebas de extremo a extremo, incluyendo la facilidad de modificación y su función como documentación adicional para la API. También se mencionan los desafíos de escribir la versión inicial de la prueba y un truco para simular la fecha en las pruebas.

Available in English

1. Introducción a las pruebas de extremo a extremo para API

Short description:

Hola a todos. Mi nombre es Valentin Kononov, y hoy mi charla relámpago trata sobre las pruebas de extremo a extremo para API. Cómo lo hice. Cómo me ahorró nervios y horas y así sucesivamente. Pero primero un poco sobre mí. Soy un desarrollador, que trabaja principalmente con TypeScript y JavaScript en estos días, es decir, con Node.js, y especialmente con el backend. En uno de mis últimos proyectos, teníamos un backend escrito en NestJS, y tuvimos muchos problemas para probarlo, especialmente cuando necesitábamos cambiar alguna funcionalidad. Así que intentamos pasar eventualmente a las pruebas de extremo a extremo, y eso es de lo que trata mi charla.

Mi nombre es Valentin Kononov, y hoy mi charla relámpago trata sobre las pruebas de extremo a extremo para API. Cómo lo hice. Cómo me ahorró nervios y horas y así sucesivamente.

Pero primero un poco sobre mí. Soy un desarrollador, que trabaja principalmente con TypeScript y JavaScript en estos días, es decir, con Node.js, y especialmente con el backend. En uno de mis últimos proyectos, teníamos un backend escrito en NestJS, y tuvimos muchos problemas para probarlo, especialmente cuando necesitábamos cambiar alguna funcionalidad. Así que intentamos pasar eventualmente a las pruebas de extremo a extremo, y eso es de lo que trata mi charla.

En este momento, trabajo en una empresa de Unity, y todo se trata de diversión y juegos y cosas así, pero trabajo en el departamento de publicidad, por lo que tenemos muchos servicios tanto en el frontend como en el backend, y por supuesto, necesitamos probarlos cuidadosamente. Así que vamos al grano, no tenemos mucho tiempo. Cuando hablamos de pruebas de API, ¿a qué nos referimos normalmente? En primer lugar, necesitamos probar el flujo de datos, es decir, cómo fluyen los datos a través de nuestros servicios, cuáles son las consultas a la base de datos, es decir, qué entrada, salida y transformadores de datos tenemos. Y en la mayoría de los casos, solo necesitamos probar si las operaciones CRUD funcionan correctamente y si la sindicación funciona correctamente y si los puntos finales son correctos, y lo que normalmente hacemos para lograr eso. Por supuesto, en la mayoría de los casos, tenemos pruebas de integración.

¿Y cómo funciona eso? Las pruebas de integración suelen probar el módulo completo, como todo el servicio, pero el servicio no es algo que esté presente por sí mismo, es algo que se comunica con otros módulos como una base de datos o un repositorio de datos o algún modelo de sindicación, entre otras cosas. Por eso, para probarlo, necesitamos simular algunas dependencias. Y cuando hicimos eso y la prueba funciona correctamente, ¿qué hacemos a continuación? Actualizamos el código, agregamos nuevas funcionalidades. ¿Y qué necesitamos hacer después? Necesitamos actualizar las dependencias simuladas, para que la prueba siga funcionando. ¿Y qué más? Sí, necesitamos actualizar las dependencias simuladas una y otra vez, y otra vez, y otra vez, y otra vez.

Realmente me enfrenté a eso. Teníamos una prueba realmente grande, importante y súper mega crítica sobre algún proceso de exportación. Y cada vez que cambiábamos algo mínimo en el código de exportación, necesitábamos reescribir completamente toda la prueba. Eso fue malo. Entonces, ¿cómo podría verse normalmente la prueba de integración con todas las simulaciones? En realidad, es una gran cantidad de diferentes tipos de funciones de simulación, como se muestra en las diapositivas. A veces simulamos todo el módulo, a veces simulamos solo una función. Y por supuesto, cuando algo cambia en la función, especialmente en el último ejemplo aquí, la función de actualización cambió, y su salida cambió. Incluso el formato de salida, que era un objeto, se convirtió en un simple número. Así que necesitábamos actualizar la simulación. Y eso realmente fue molesto porque pasamos mucho tiempo solo para mantener las pruebas. Pero debería ser al revés, es decir, las pruebas deberían ahorrar tiempo en el desarrollo. Entonces, ¿hay alguna alternativa de cómo podemos proceder para que todo el proceso sea más fácil para nosotros como desarrolladores? Básicamente, mi receta para eso fueron las pruebas de extremo a extremo.

2. Pruebas de extremo a extremo para API

Short description:

Discutimos el uso del framework Nest.js para pruebas de extremo a extremo en el desarrollo de API. Las pruebas de extremo a extremo implican iniciar toda la API en un entorno de pruebas y probarla punto por punto. La inicialización de la API de Nest implica crear un módulo de pruebas, inicializarlo y crear una aplicación de Nest. Las pruebas se pueden personalizar mediante la anulación de los guardias de autenticación. Las pruebas en sí implican realizar solicitudes POST o GET a puntos finales específicos, enviar datos de solicitud y esperar códigos y propiedades de respuesta específicos. Las pruebas de extremo a extremo tienen ventajas como ser fáciles de corregir, modificar y servir como documentación adicional para la API. Sin embargo, escribir la versión inicial de la prueba puede llevar tiempo, especialmente cuando se requiere preparación de datos. También se comparte un truco para simular la fecha en las pruebas.

Discutimos con el equipo, vale, tenemos el framework Nest.js. Tiene muchas capacidades de pruebas. ¿Por qué no lo usamos para pruebas de extremo a extremo? ¿Y qué es la prueba de extremo a extremo cuando hablamos de la API? Es cuando inicias toda la API, como todo el servicio de nodo en tu entorno de pruebas, y lo pruebas punto por punto.

En esta diapositiva, puedes ver cómo podría ser la inicialización de la API de Nest. Creas un módulo de pruebas, lo inicializas, creas la aplicación de Nest. Al final, debes cerrarlo y, por supuesto, puedes sobrescribir lo que quieras. Por ejemplo, en Nest, usamos los llamados guardias para la autenticación. Aquí, podemos anularlo, inicializarlo y cerrarlo al final cuando todas las pruebas hayan pasado. La simulación del guardia de autenticación es algo bastante simple, que solo escribes una vez y usas en todas partes. Es realmente algo tan simple.

Y así es como se vería toda la prueba. Literalmente, haces una solicitud, haces una solicitud POST o GET a algún punto final específico, para alguna URL específica. Y en este ejemplo, como es POST, puedes enviar detalles de alguien, como qué tipo de proyecto debemos agregar. Y puedes esperar, como aquí en la última línea, puedes esperar algún tipo de código, como que debería devolver 201. Lo que significa creado exitosamente. Y también puedes hacer una solicitud GET y también formar alguna URL, enviar solicitudes, esperar algún código. Y también esperar alguna respuesta. Y verificar que las propiedades de la respuesta sean correctas.

¿Qué quiero decir? Así que los pros y los contras. Los pros, fáciles de corregir, fáciles de modificar y pruebas de todo el flujo de trabajo. Y como puedes ver aquí mismo, toda la prueba es muy legible y también es una fuente adicional de documentación para tu API. Pero, por supuesto, también hay algunos contras y aspectos negativos. Puede llevar tiempo escribir la versión inicial de esta prueba porque en algunos casos necesitas preparar los datos. Por supuesto, cuando solo tienes una API rudimentaria, puedes usar solo solicitudes GET o POST para crear datos y asegurarte de que se creen. Pero en algunos casos, necesitas preparar los datos en una base de datos y esta base de datos mínima debe ejecutarse en algún lugar en un servicio de integración continua. Y solo para ti tenemos un truco realmente especial, muy pequeño. A veces, en mi experiencia, solo una vez. Pero necesitábamos falsificar la fecha. Preparé algunos datos y debo asegurarme de que estos datos se creen con esta fecha actual. Y generalmente lo hacíamos así. Pero en algún código realmente usamos no solo la función now, sino también construct. Y hay una solución un poco más completa de cómo simular la fecha tanto para now como para el constructor. Así que toma una captura de pantalla, es un truco muy útil, nos vemos más tarde.

Y aquí está el enlace a mis diapositivas, mi sitio web y mi documentación, que me inspiraron para todo eso. Entonces, como resumen, haz pruebas. Realmente es algo genial cuando haces pruebas. Y las pruebas de extremo a extremo hacen que los cambios sean más rápidos y puedes cubrir todo el flujo de trabajo con las últimas simulaciones y ser mucho más feliz. ¡Nos vemos, chicos!

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

React Summit 2022React Summit 2022
20 min
Routing in React 18 and Beyond
Top Content
Concurrent React and Server Components are changing the way we think about routing, rendering, and fetching in web applications. Next.js recently shared part of its vision to help developers adopt these new React features and take advantage of the benefits they unlock.In this talk, we’ll explore the past, present and future of routing in front-end applications and discuss how new features in React and Next.js can help us architect more performant and feature-rich applications.
TestJS Summit 2021TestJS Summit 2021
33 min
Network Requests with Cypress
Top Content
Whether you're testing your UI or API, Cypress gives you all the tools needed to work with and manage network requests. This intermediate-level task demonstrates how to use the cy.request and cy.intercept commands to execute, spy on, and stub network requests while testing your application in the browser. Learn how the commands work as well as use cases for each, including best practices for testing and mocking your network requests.
TestJS Summit 2021TestJS Summit 2021
38 min
Testing Pyramid Makes Little Sense, What We Can Use Instead
Top Content
Featured Video
The testing pyramid - the canonical shape of tests that defined what types of tests we need to write to make sure the app works - is ... obsolete. In this presentation, Roman Sandler and Gleb Bahmutov argue what the testing shape works better for today's web applications.
TestJS Summit 2022TestJS Summit 2022
27 min
Full-Circle Testing With Cypress
Top Content
Cypress has taken the world by storm by brining an easy to use tool for end to end testing. It’s capabilities have proven to be be useful for creating stable tests for frontend applications. But end to end testing is just a small part of testing efforts. What about your API? What about your components? Well, in my talk I would like to show you how we can start with end-to-end tests, go deeper with component testing and then move up to testing our API, circ
TestJS Summit 2022TestJS Summit 2022
20 min
Testing Web Applications with Playwright
Top Content
Testing is hard, testing takes time to learn and to write, and time is money. As developers we want to test. We know we should but we don't have time. So how can we get more developers to do testing? We can create better tools.Let me introduce you to Playwright - Reliable end-to-end cross browser testing for modern web apps, by Microsoft and fully open source. Playwright's codegen generates tests for you in JavaScript, TypeScript, Dot Net, Java or Python. Now you really have no excuses. It's time to play your tests wright.
TestJS Summit 2021TestJS Summit 2021
31 min
Test Effective Development
Top Content
Developers want to sleep tight knowing they didn't break production. Companies want to be efficient in order to meet their customer needs faster and to gain competitive advantage sooner. We ALL want to be cost effective... or shall I say... TEST EFFECTIVE!But how do we do that?Are the "unit" and "integration" terminology serves us right?Or is it time for a change? When should we use either strategy to maximize our "test effectiveness"?In this talk I'll show you a brand new way to think about cost effective testing with new strategies and new testing terms!It’s time to go DEEPER!

Workshops on related topic

React Summit 2023React Summit 2023
151 min
Designing Effective Tests With React Testing Library
Top Content
Featured Workshop
React Testing Library is a great framework for React component tests because there are a lot of questions it answers for you, so you don’t need to worry about those questions. But that doesn’t mean testing is easy. There are still a lot of questions you have to figure out for yourself: How many component tests should you write vs end-to-end tests or lower-level unit tests? How can you test a certain line of code that is tricky to test? And what in the world are you supposed to do about that persistent act() warning?
In this three-hour workshop we’ll introduce React Testing Library along with a mental model for how to think about designing your component tests. This mental model will help you see how to test each bit of logic, whether or not to mock dependencies, and will help improve the design of your components. You’ll walk away with the tools, techniques, and principles you need to implement low-cost, high-value component tests.
Table of contents- The different kinds of React application tests, and where component tests fit in- A mental model for thinking about the inputs and outputs of the components you test- Options for selecting DOM elements to verify and interact with them- The value of mocks and why they shouldn’t be avoided- The challenges with asynchrony in RTL tests and how to handle them
Prerequisites- Familiarity with building applications with React- Basic experience writing automated tests with Jest or another unit testing framework- You do not need any experience with React Testing Library- Machine setup: Node LTS, Yarn
TestJS Summit 2022TestJS Summit 2022
146 min
How to Start With Cypress
Featured WorkshopFree
The web has evolved. Finally, testing has also. Cypress is a modern testing tool that answers the testing needs of modern web applications. It has been gaining a lot of traction in the last couple of years, gaining worldwide popularity. If you have been waiting to learn Cypress, wait no more! Filip Hric will guide you through the first steps on how to start using Cypress and set up a project on your own. The good news is, learning Cypress is incredibly easy. You'll write your first test in no time, and then you'll discover how to write a full end-to-end test for a modern web application. You'll learn the core concepts like retry-ability. Discover how to work and interact with your application and learn how to combine API and UI tests. Throughout this whole workshop, we will write code and do practical exercises. You will leave with a hands-on experience that you can translate to your own project.
React Summit 2022React Summit 2022
173 min
Build a Headless WordPress App with Next.js and WPGraphQL
Top Content
WorkshopFree
In this workshop, you’ll learn how to build a Next.js app that uses Apollo Client to fetch data from a headless WordPress backend and use it to render the pages of your app. You’ll learn when you should consider a headless WordPress architecture, how to turn a WordPress backend into a GraphQL server, how to compose queries using the GraphiQL IDE, how to colocate GraphQL fragments with your components, and more.
React Day Berlin 2022React Day Berlin 2022
53 min
Next.js 13: Data Fetching Strategies
Top Content
WorkshopFree
- Introduction- Prerequisites for the workshop- Fetching strategies: fundamentals- Fetching strategies – hands-on: fetch API, cache (static VS dynamic), revalidate, suspense (parallel data fetching)- Test your build and serve it on Vercel- Future: Server components VS Client components- Workshop easter egg (unrelated to the topic, calling out accessibility)- Wrapping up
React Summit 2022React Summit 2022
117 min
Detox 101: How to write stable end-to-end tests for your React Native application
Top Content
WorkshopFree
Compared to unit testing, end-to-end testing aims to interact with your application just like a real user. And as we all know it can be pretty challenging. Especially when we talk about Mobile applications.
Tests rely on many conditions and are considered to be slow and flaky. On the other hand - end-to-end tests can give the greatest confidence that your app is working. And if done right - can become an amazing tool for boosting developer velocity.
Detox is a gray-box end-to-end testing framework for mobile apps. Developed by Wix to solve the problem of slowness and flakiness and used by React Native itself as its E2E testing tool.
Join me on this workshop to learn how to make your mobile end-to-end tests with Detox rock.
Prerequisites- iOS/Android: MacOS Catalina or newer- Android only: Linux- Install before the workshop
TestJS Summit 2023TestJS Summit 2023
48 min
API Testing with Postman Workshop
Top Content
WorkshopFree
In the ever-evolving landscape of software development, ensuring the reliability and functionality of APIs has become paramount. "API Testing with Postman" is a comprehensive workshop designed to equip participants with the knowledge and skills needed to excel in API testing using Postman, a powerful tool widely adopted by professionals in the field. This workshop delves into the fundamentals of API testing, progresses to advanced testing techniques, and explores automation, performance testing, and multi-protocol support, providing attendees with a holistic understanding of API testing with Postman.
1. Welcome to Postman- Explaining the Postman User Interface (UI)2. Workspace and Collections Collaboration- Understanding Workspaces and their role in collaboration- Exploring the concept of Collections for organizing and executing API requests3. Introduction to API Testing- Covering the basics of API testing and its significance4. Variable Management- Managing environment, global, and collection variables- Utilizing scripting snippets for dynamic data5. Building Testing Workflows- Creating effective testing workflows for comprehensive testing- Utilizing the Collection Runner for test execution- Introduction to Postbot for automated testing6. Advanced Testing- Contract Testing for ensuring API contracts- Using Mock Servers for effective testing- Maximizing productivity with Collection/Workspace templates- Integration Testing and Regression Testing strategies7. Automation with Postman- Leveraging the Postman CLI for automation- Scheduled Runs for regular testing- Integrating Postman into CI/CD pipelines8. Performance Testing- Demonstrating performance testing capabilities (showing the desktop client)- Synchronizing tests with VS Code for streamlined development9. Exploring Advanced Features - Working with Multiple Protocols: GraphQL, gRPC, and more
Join us for this workshop to unlock the full potential of Postman for API testing, streamline your testing processes, and enhance the quality and reliability of your software. Whether you're a beginner or an experienced tester, this workshop will equip you with the skills needed to excel in API testing with Postman.