Visual Regression Bajo el Capó

Rate this content
Bookmark

La regresión visual es una de las partes más difíciles en las pruebas de interfaz de usuario. Y seguramente estarás de acuerdo en que es extremadamente poderosa. Pero, ¿cómo funciona? ¿Cuál es el problema que resuelve bajo el capó? ¿Por qué la gente elige servicios de regresión visual y cómo construimos la herramienta de regresión visual más rápida del mundo :)

9 min
15 Jun, 2021

Video Summary and Transcription

La charla de hoy discute el valor y los desafíos de la regresión visual en las pruebas de interfaz de usuario. Destaca la importancia de la previsibilidad en la carga de páginas y la elección de la resolución correcta de capturas de pantalla. También menciona el uso de servicios de regresión visual, Docker y la biblioteca Odiff como soluciones para mejorar la estabilidad y eficiencia en las pruebas de regresión visual.

Available in English

1. Introducción a la Regresión Visual

Short description:

Hola a todos. Hoy hablaré sobre la regresión visual y su valor en las pruebas de interfaz de usuario. Vamos a ver un ejemplo sencillo y ver cómo la regresión visual puede detectar automáticamente cambios en las capturas de pantalla de la interfaz de usuario, ayudándonos a construir un sistema estable y confiable.

Hola a todos. Estoy emocionado de estar aquí hoy y hablar sobre la regresión visual. Mi nombre es Dmitry. Soy de Ucrania. Trabajo a tiempo completo en Cypress.io y también colaboro en la comunidad de código abierto. Comencemos. Hoy hemos estado hablando mucho sobre las pruebas de interfaz de usuario, pero probablemente estarán de acuerdo en que la parte más difícil de las pruebas de interfaz de usuario es probar cómo se ve la interfaz de usuario para los usuarios, ¿verdad? Porque las computadoras no saben nada sobre la interfaz de usuario. Y ahí es donde la regresión visual nos brinda mucho valor. Veamos un ejemplo sencillo de regresión visual y luego profundicemos en el proceso. Aquí hay un ejemplo. Una captura de pantalla sencilla de la página de inicio de Cypress.io. Y aquí está la siguiente captura de pantalla. Probablemente noten la diferencia, ¿verdad? Porque están cambiando muy rápido. Pero la regresión visual puede hacer esto automáticamente. Pueden ver que hay dos cambios entre estas capturas de pantalla. Y esto es extremadamente útil cuando queremos construir un sistema estable y confiable. Sí, lo hace

2. Desafíos y Soluciones en la Regresión Visual

Short description:

Pero en mi experiencia, la regresión visual también es una categoría de prueba extremadamente inestable. Hoy, me gustaría adentrarme en la regresión visual y discutir los problemas ocultos en cada paso. Cargar la página no es suficiente; debe ser predecible. Diferentes interfaces de usuario pueden aparecer en diferentes sistemas operativos o navegadores. Los servicios de regresión visual y Docker pueden ayudar a lograr la predecibilidad. Elegir la resolución correcta de captura de pantalla es crucial, ya que debe coincidir con las resoluciones utilizadas por los usuarios. La comparación de capturas de pantalla puede ser lenta, pero la biblioteca Odiff ofrece una solución más rápida. En conclusión, asegúrese de tener entornos consistentes, evite contenido inestable y pruebe la interfaz de usuario en las resoluciones utilizadas por los usuarios.

nos da confianza sobre cómo cambia nuestra interfaz de usuario para los usuarios reales. Pero en mi experiencia, la regresión visual también es una categoría de prueba extremadamente inestable. Probablemente conozcan esta razón cuando cada literalmente cada segundo captura de pantalla, cada segundo commit, tiene algún ruido de regresión visual y como todos somos humanos y nos estamos acostumbrando a esto, comenzamos a ignorarlo, aprobarlo automáticamente y así sucesivamente. Y esto es un problema porque una vez que se vuelve inestable, pierde el valor. Así que hoy, me gustaría abordar este problema adentrándome en la regresión visual, los problemas ocultos y tratar de obtener este conocimiento y utilizarlo para construir una regresión visual más confiable. Así que bajo la superficie de la regresión visual siempre hay cuatro pasos simples. En primer lugar, debes cargar una página, luego debes tomar una captura de pantalla, compararla con la versión aprobada anterior y ver la diferencia. Parece bastante fácil, pero cada uno de estos pasos tiene sus propios problemas ocultos y me gustaría discutirlos. Así que primero, debes cargar la página, pero no es suficiente cargar la página usando tu ejecutor de pruebas basado en navegador favorito como Cypress, ¿verdad? Necesitas hacer que esta página sea predecible, y esto es un problema especialmente cuando no estás utilizando servicios de regresión visual, porque cuando tu página no está en un estado estable puedes obtener fácilmente mucho ruido, como por ejemplo, aquí. La mayoría de las capturas de pantalla tienen secciones que cambian de vez en cuando, como los videos incrustados o el carrusel que cambia por tiempo, y todo esto puede romper fácilmente el proceso de regresión visual. Además, las animaciones, los tiempos, los valores aleatorios pueden romper esto fácilmente, así que debemos tener cuidado con esto, pero eso no es todo de lo que debemos preocuparnos. También es posible que haya diferentes interfaces de usuario incluso cuando estás ejecutando el mismo código, pero en diferentes sistemas operativos o navegadores. Simplemente porque los diferentes sistemas de diseño o el propio sistema operativo pueden producir cambios en el diseño o una vista predeterminada diferente, por lo que esto romperá nuestro código. Y este es un problema real, que se resuelve perfectamente con los servicios de regresión visual, pero presenta muchos problemas para las personas que intentan hacer la regresión visual por sí mismas. Los servicios de regresión visual resuelven esto cargando tu HTML, y no la captura de pantalla, sino el HTML, ejecutando este HTML con todos los estilos en el navegador especificado, y solo allí tomando una captura de pantalla y comparándola. Pero puedes obtener el mismo nivel de predecibilidad ejecutando todas tus tareas y solo ejecutando tus tareas de regresión visual en Docker. Incluso puede ser razonable hacer una cantidad específica de tareas separadas solo para la regresión visual y ejecutarlas solo en Docker, incluso aprobarlas en Docker. Y esto te dará confianza de que tus tareas se están ejecutando en el mismo entorno y no generan mucho ruido y cambios en el diseño entre las máquinas locales de los desarrolladores. Pero también hay un enfoque interesante entre estas dos opciones. Existe un proyecto llamado Visual Regression Tracker que te permite ejecutar estas tareas dentro de Docker en un servicio autohospedado, te brinda una interfaz que te permite aprobar la captura de pantalla y te brinda el mismo nivel de predecibilidad que los servicios de regresión visual, pero autohospedado. Estoy seguro de que este proyecto será el futuro de la regresión visual. Pero luego necesitas tomar una captura de pantalla, ¿verdad? Pero ¿cuál? Y aquí está el problema, porque constantemente veo, especialmente en la comunidad de Cypress, que la gente está usando la resolución predeterminada de Cypress, o alguna resolución pequeña que honestamente no usa nadie en el mundo, ¿verdad? Necesitamos asegurarnos de que estamos probando nuestra interfaz de usuario en las resoluciones que utilizan nuestros usuarios. Puedes obtener fácilmente esta información de cualquier herramienta de análisis. Por ejemplo, aquí están las estadísticas de mi sitio web personal, y puedes ver que la mayoría de mis usuarios están utilizando esta extraña resolución de algunas tabletas, y honestamente, no estoy probando mi sitio web en esta resolución, y probablemente sabes lo fácil que es perder algunos efectos visuales cuando esta resolución no es ampliamente popular o es demasiado grande, por ejemplo, y necesitas asegurarte de que estás probando en esta resolución que utilizan tus usuarios, y en realidad es extraño que por defecto, las herramientas y servicios de aplicaciones visuales no utilicen las resoluciones más populares, como por ejemplo, Full HD. Y la razón de esto es que la comparación de capturas de pantalla es realmente lenta. Para comparar dos imágenes con una resolución Full HD, necesitas iterar sobre 2 millones de píxeles, calcular la diferencia entre cada uno utilizando una fórmula especializada y luego guardar la diferencia. Es una tarea bastante difícil y que no es amigable con el rendimiento para las computadoras, especialmente cuando intentas hacer esto en JavaScript. Y por eso creé y actualmente estoy trabajando en la biblioteca llamada Odiff que te permite hacer la comparación de imágenes no en JavaScript, sino en un lenguaje nativo más eficiente en términos de rendimiento y te ahorra mucho tiempo y te permite probar las capturas de pantalla que deseas y hacerlo rápidamente. Así que probablemente se nos acabe el tiempo. Así que discutamos una conclusión y la clave para una regresión visual sin problemas. Necesitas asegurarte de que tus tareas se ejecuten en el mismo entorno y debes asegurarte de que no haya contenido inestable en tu página, incluso si estás utilizando servicios de regresión visual. Y también debes probar tu interfaz de usuario en la resolución que utilizan tus usuarios y no solo en una resolución rápida o amigable para algún servicio. Y eso es todo. Estoy feliz de estar aquí. ¡Gracias y adiós!

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

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 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!
TestJS Summit 2023TestJS Summit 2023
21 min
Everyone Can Easily Write Tests
Let’s take a look at how Playwright can help you get your end to end tests written with tools like Codegen that generate tests on user interaction. Let’s explore UI mode for a better developer experience and then go over some tips to make sure you don’t have flakey tests. Then let’s talk about how to get your tests up and running on CI, debugging on CI and scaling using shards.

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.
Remix Conf Europe 2022Remix Conf Europe 2022
195 min
How to Solve Real-World Problems with Remix
Featured Workshop
- Errors? How to render and log your server and client errorsa - When to return errors vs throwb - Setup logging service like Sentry, LogRocket, and Bugsnag- Forms? How to validate and handle multi-page formsa - Use zod to validate form data in your actionb - Step through multi-page forms without losing data- Stuck? How to patch bugs or missing features in Remix so you can move ona - Use patch-package to quickly fix your Remix installb - Show tool for managing multiple patches and cherry-pick open PRs- Users? How to handle multi-tenant apps with Prismaa - Determine tenant by host or by userb - Multiple database or single database/multiple schemasc - Ensures tenant data always separate from others
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.
TestJS Summit - January, 2021TestJS Summit - January, 2021
173 min
Testing Web Applications Using Cypress
WorkshopFree
This workshop will teach you the basics of writing useful end-to-end tests using Cypress Test Runner.
We will cover writing tests, covering every application feature, structuring tests, intercepting network requests, and setting up the backend data.
Anyone who knows JavaScript programming language and has NPM installed would be able to follow along.