Prueba del Servicio de Correo con Playwright

Rate this content
Bookmark

Enviamos correos electrónicos a nuestros usuarios - verificación de cuenta y boletines informativos. Permitimos que el usuario nos contacte enviando un correo electrónico a través de un formulario incorporado. ¿Lo hacemos? ¿Recibe el usuario un correo electrónico de verificación de cuenta o exactamente la notificación para la que se inscribió? Podemos cubrir esta funcionalidad como parte de las pruebas E2E: obtener un correo electrónico y abrirlo para verificar qué contiene. Necesitaremos Playwright y un servidor SMTP falso para capturar los correos electrónicos enviados por la aplicación.

Kat Kmiotek
Kat Kmiotek
17 min
03 Nov, 2022

Comments

Sign in or register to post your comment.

Video Summary and Transcription

Esta charla discute cómo probar el servicio de correo con Playwright, cubriendo la verificación de correo electrónico, el viaje del usuario para restablecer la contraseña y más. Explora el uso de proveedores de terceros para la entrega confiable de correos electrónicos y demuestra cómo Playwright puede ayudar a realizar comprobaciones en el contenido del correo electrónico. La charla también introduce el concepto de un servidor SMTP falso y muestra cómo se pueden usar los accesorios para acceder al servidor SMTP y realizar afirmaciones en el cuerpo HTML de los correos electrónicos. La función de renderizado HTML de Playwright permite interactuar con el contenido del correo electrónico como si fuera una página web regular. Destaca la capacidad de renderizar HTML a partir de llamadas API, realizar afirmaciones en la página renderizada y excluir datos generados dinámicamente de las pruebas de regresión visual.

Available in English

1. Prueba del servicio de correo con Playwright

Short description:

En esta charla, les mostraré cómo probar el servicio de correo con Playwright. Cubriremos la verificación de correo electrónico, el recorrido del usuario para restablecer la contraseña y más. Al usar proveedores de terceros como Amazon SES, MailChimp, Postmark o SendGrid, podemos garantizar una entrega de correo electrónico confiable. Sin embargo, el problema radica en lo que se entrega al usuario. Hoy, demostraré cómo Playwright puede ayudar a realizar controles en el contenido del correo electrónico y garantizar una experiencia de usuario fluida. Además, presentaré el concepto de un servidor SMTP falso, que captura y almacena correos electrónicos en un entorno de prueba. Herramientas como Mailhug proporcionan una interfaz fácil de usar para la verificación manual y una documentación de API completa.

Hola a todos, mi nombre es Kat Kniotek, trabajo como ingeniera de calidad en Zoopla, y gracias por unirse a mi charla hoy. Estaré hablando sobre testing el servicio de correo con Playwright. Les mostraré lo fácil que es agregar la verificación de correo electrónico o el recorrido del usuario para restablecer la contraseña a sus pruebas de extremo a extremo. Y sinceramente, me gusta mucho lo ingenioso que puedes ser aquí con Playwright. Así que comencemos.

Dependiendo de la aplicación en la que estés trabajando, puedes o no puedes comunicarte con el usuario por correo electrónico. Pero si lo haces, les enviarías boletines informativos, confirmaciones de pedidos. Si trabajas en el sitio web de e-commerce, enlace para restablecer la contraseña si la acción es solicitada por el usuario, solicitud de verificación de correo electrónico y cualquier tipo de recibos o notificaciones que puedan solicitar. Y generalmente usas proveedores de terceros para manejar esto, pueden transportarlo por ti. Y esos serían Amazon SES, MailChimp, Postmark y SendGrid, solo por nombrar algunos. Y es una muy buena idea porque podemos confiar en ellos para asegurarnos de que el correo electrónico se entregue realmente. Pero la declaración del problema de esta charla es lo que se entrega al usuario. ¿Pueden hacer clic en el enlace y restablecer su contraseña? ¿El correo electrónico de verificación realmente los lleva al dominio correcto? Si el contenido del cuerpo del correo electrónico realmente coincide con nuestro sistema de design, y por supuesto, si por error, no enviamos ningún data sensible o cualquier data aleatorio como esta prueba como asunto del correo electrónico. Así que hoy, les mostraré cómo se pueden realizar todas esas verificaciones con la ayuda de Playwright. Así que comencemos. Entonces, para describir la comunicación por correo electrónico en una aplicación de producción, tendrás la aplicación comunicándose con el servicio de terceros, y el servicio de terceros será responsable de entregar los correos electrónicos al usuario o a los grupos de usuarios. En un entorno de prueba para esta demostración, en lugar de enviar solicitudes al servicio de terceros, estaremos enviando correos electrónicos a un servicio SMTP falso y desde allí, podremos acceder a data desde las pruebas de Playwright. OK, acabo de introducir algo nuevo, un servidor SMTP falso, ¿qué es eso? Puedes pensar en ello como un contenedor que estará capturando y almacenando todos los correos electrónicos enviados por la aplicación en un entorno de prueba. Y para este propósito, puedes elegir una de las muchas herramientas disponibles. Aquí solo he enumerado algunas. Algunas de ellas son de pago y algunas de ellas son de código abierto. Depende de ti cuál usarás. Para esta demostración, estoy usando Mailhug. Todos ellos suelen venir con una interfaz de usuario gráfica muy agradable que puedes acceder en tu navegador que se ve exactamente como el buzón. Puedes navegar por los correos electrónicos, puedes eliminar correos electrónicos, almacenar archivos adjuntos o reenviar correos electrónicos. Es genial para la verificación manual de lo que se envía al usuario. Ese tipo de servidor SMTP falso también vendrá con una gran documentation sobre su API. Así que con Swagger. Swagger enumeraría todos los puntos finales disponibles en el servicio con los métodos que están disponibles y cómo debería verse la carga útil

2. Integrando la API de Mailhook con las pruebas de Playwright

Short description:

Aquí está el ejemplo de llamada a la API de Mailhook, consultando los correos electrónicos enviados al usuario de prueba. La respuesta incluye el estado, el número de correos electrónicos enviados y los objetos de correo electrónico con ID, de, para, contenido y cuerpo. Podemos realizar afirmaciones sobre el contenido del correo electrónico, incluyendo la comprobación de cadenas específicas, elementos y estilos. Para traducir esta prueba de API a las pruebas de Playwright, necesitamos acceder al servidor SMTP, recuperar el correo electrónico más reciente y realizar afirmaciones sobre el cuerpo HTML. La función de renderizado HTML de Playwright nos permite interactuar con el contenido del correo electrónico como si fuera una página web regular. Podemos hacer clic en enlaces, comprobar elementos y verificar URLs. Para empezar, accederemos al servidor SMTP desde nuestras pruebas de extremo a extremo utilizando fixtures, que proporcionan contextos aislados con configuraciones separadas.

como y qué esperas ver como respuesta de la llamada API al servidor. Aquí está la captura de pantalla del ejemplo de llamada a la API de Mailhook. Así que como punto de búsqueda estoy consultando aquí. Basado en su documentation, proporcioné parámetros de consulta para obtener todos los correos electrónicos que han sido enviados al usuario de prueba en example.com y en el lado derecho, puedes ver cómo se ve la respuesta. Tan bueno, porque el estado es 200. Y luego puedes ver cuántos correos electrónicos han sido enviados a este usuario, así que el punto final del servicio devuelve tres. Brillante, porque estaba solo testing un poco. Y todos ellos están listados como objetos de correo electrónico en el array de items, así en la línea cinco, y cada objeto de correo electrónico individual tendría ID, de, para, contenido y cuerpo. Y si miras más de cerca, debajo de la línea 34, bueno, desde la línea 34, puedes ver que el cuerpo es en realidad cuerpo HTML, código HTML. Así que de nuevo, aquí también podemos hacer algunas afirmaciones. Podemos comprobar si ciertas cadenas están presentes, si ciertos elementos están presentes, digamos un botón o un enlace, pero también verificar si se ha aplicado el estilo, ¿verdad? Sólo para mencionar, estoy usando Thunder Client aquí. Así que, herramientas similares a Postman o Insomnia, si estás familiarizado con ellas. Bueno, así que, un servidor SMTP falso viene con algunas características agradables que permiten la testing manual, pero usaremos el mismo servidor SMTP en nuestras pruebas de Playwright, así que veamos cómo traducir lo que acabo de mostrar con, digamos, la testing de API a las pruebas de Playwright. Empecemos con la codificación pseudo, ¿qué queremos hacer? Así que, primero, nuestra prueba necesitará tener una precondición y eso depende de tu aplicación. Eso podría ser la acción que desencadena el envío de la verificación por correo electrónico. Digamos, el usuario crea la cuenta o el usuario completa el pedido y se envía la confirmación del pedido y así sucesivamente. Como no estoy conectando a ninguna aplicación real aquí, era sólo un script que desencadena el envío de correo electrónico. Bueno, así que ¿en qué queremos centrarnos en la prueba? Queremos hacer exactamente lo que hice manualmente con la conexión al servidor SMTP. Así que, quiero acceder al servidor SMTP, quiero obtener el correo electrónico más reciente que ha sido enviado al usuario. Así que, en una respuesta había un array de items, así que quiero obtener el primer elemento de él, así con el índice cero. Y quiero obtener una parte del cuerpo HTML, porque ahí es donde quiero hacer afirmaciones. Y la gran característica mágica de Playwright, puedes usar este cuerpo HTML para renderizar una nueva página y hacer las mismas afirmaciones que harías en una página regular en un navegador. Así que, puedes hacer clic en el botón de verificación, puedes comprobar si ciertos elementos están presentes y también puedes verificar si al hacer clic en el botón de verificación, se abrirá una nueva pestaña y puedes hacer una afirmación si la nueva pestaña que es también página, tendrá la URL esperada. Bueno, así que, eso es mucho que hacer. Así que, ¿por dónde empezar? Empezaré accediendo al servidor SMTP desde mis pruebas de extremo a extremo. Y para este propósito, estaré usando fixtures. ¿Qué son los fixtures? Así que, probablemente en tu aplicación, tienes Configuración de Playwright. Bueno, en tus pruebas de extremo a extremo, tienes Configuración de Playwright y especificas el valor de la URL base allí. Y eso sería el frente de tu aplicación cliente code, la URL base de tus viejas pruebas. Pero también puedes especificar fixtures, así como contextos aislados que se utilizarán en una cierta prueba. Así que, aquí estoy creando el fixture llamado email API

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

Scaling Up with Remix and Micro Frontends
Remix Conf Europe 2022Remix Conf Europe 2022
23 min
Scaling Up with Remix and Micro Frontends
Top Content
Do you have a large product built by many teams? Are you struggling to release often? Did your frontend turn into a massive unmaintainable monolith? If, like me, you’ve answered yes to any of those questions, this talk is for you! I’ll show you exactly how you can build a micro frontend architecture with Remix to solve those challenges.
Full Stack Components
Remix Conf Europe 2022Remix Conf Europe 2022
37 min
Full Stack Components
Top Content
Remix is a web framework that gives you the simple mental model of a Multi-Page App (MPA) but the power and capabilities of a Single-Page App (SPA). One of the big challenges of SPAs is network management resulting in a great deal of indirection and buggy code. This is especially noticeable in application state which Remix completely eliminates, but it's also an issue in individual components that communicate with a single-purpose backend endpoint (like a combobox search for example).
In this talk, Kent will demonstrate how Remix enables you to build complex UI components that are connected to a backend in the simplest and most powerful way you've ever seen. Leaving you time to chill with your family or whatever else you do for fun.
Making JavaScript on WebAssembly Fast
JSNation Live 2021JSNation Live 2021
29 min
Making JavaScript on WebAssembly Fast
Top Content
JavaScript in the browser runs many times faster than it did two decades ago. And that happened because the browser vendors spent that time working on intensive performance optimizations in their JavaScript engines.Because of this optimization work, JavaScript is now running in many places besides the browser. But there are still some environments where the JS engines can’t apply those optimizations in the right way to make things fast.We’re working to solve this, beginning a whole new wave of JavaScript optimization work. We’re improving JavaScript performance for entirely different environments, where different rules apply. And this is possible because of WebAssembly. In this talk, I'll explain how this all works and what's coming next.
Debugging JS
React Summit 2023React Summit 2023
24 min
Debugging JS
Top Content
As developers, we spend much of our time debugging apps - often code we didn't even write. Sadly, few developers have ever been taught how to approach debugging - it's something most of us learn through painful experience.  The good news is you _can_ learn how to debug effectively, and there's several key techniques and tools you can use for debugging JS and React apps.
Testing Web Applications with Playwright
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.
Full-Circle Testing With Cypress
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

Workshops on related topic

Detox 101: How to write stable end-to-end tests for your React Native application
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
Yevheniia Hlovatska
Yevheniia Hlovatska
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
Using CodeMirror to Build a JavaScript Editor with Linting and AutoComplete
React Day Berlin 2022React Day Berlin 2022
86 min
Using CodeMirror to Build a JavaScript Editor with Linting and AutoComplete
Top Content
WorkshopFree
Hussien Khayoon
Kahvi Patel
2 authors
Using a library might seem easy at first glance, but how do you choose the right library? How do you upgrade an existing one? And how do you wade through the documentation to find what you want?
In this workshop, we’ll discuss all these finer points while going through a general example of building a code editor using CodeMirror in React. All while sharing some of the nuances our team learned about using this library and some problems we encountered.
Testing Web Applications Using Cypress
TestJS Summit - January, 2021TestJS Summit - January, 2021
173 min
Testing Web Applications Using Cypress
WorkshopFree
Gleb Bahmutov
Gleb Bahmutov
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.
Build a powerful DataGrid in few hours with Ag Grid
React Summit US 2023React Summit US 2023
96 min
Build a powerful DataGrid in few hours with Ag Grid
WorkshopFree
Mike Ryan
Mike Ryan
Does your React app need to efficiently display lots (and lots) of data in a grid? Do your users want to be able to search, sort, filter, and edit data? AG Grid is the best JavaScript grid in the world and is packed with features, highly performant, and extensible. In this workshop, you’ll learn how to get started with AG Grid, how we can enable sorting and filtering of data in the grid, cell rendering, and more. You will walk away from this free 3-hour workshop equipped with the knowledge for implementing AG Grid into your React application.
We all know that rolling our own grid solution is not easy, and let's be honest, is not something that we should be working on. We are focused on building a product and driving forward innovation. In this workshop, you'll see just how easy it is to get started with AG Grid.
Prerequisites: Basic React and JavaScript
Workshop level: Beginner
0 to Auth in an Hour Using NodeJS SDK
Node Congress 2023Node Congress 2023
63 min
0 to Auth in an Hour Using NodeJS SDK
WorkshopFree
Asaf Shen
Asaf Shen
Passwordless authentication may seem complex, but it is simple to add it to any app using the right tool.
We will enhance a full-stack JS application (Node.JS backend + React frontend) to authenticate users with OAuth (social login) and One Time Passwords (email), including:- User authentication - Managing user interactions, returning session / refresh JWTs- Session management and validation - Storing the session for subsequent client requests, validating / refreshing sessions
At the end of the workshop, we will also touch on another approach to code authentication using frontend Descope Flows (drag-and-drop workflows), while keeping only session validation in the backend. With this, we will also show how easy it is to enable biometrics and other passwordless authentication methods.
Table of contents- A quick intro to core authentication concepts- Coding- Why passwordless matters
Prerequisites- IDE for your choice- Node 18 or higher
Building out a meaningful test suite that's not all E2E
TestJS Summit 2023TestJS Summit 2023
89 min
Building out a meaningful test suite that's not all E2E
Workshop
David Burns
David Burns
We're all taught to follow the Testing Pyramid but the reality is that we build out the Testing Christmas Tree. In this workshop, David will talk you through how to break down projects and put the tests where they need to be. By the end of the workshop you will be able to update your projects so that anyone and everyone can start contributing and truly living up to "Quality is everyone job".
He will walk you through:- Component Testing- API Testing- Visual Regression Testing- A11Y testing
He will also talk you through how to get these all setup in your CI/CD pipeline so that you can get shorter and faster feedback loops.