Fixtures en Playwright - Pequeña Guía

Rate this content
Bookmark

¿Qué son los fixtures? ¿Cómo puedo crear uno? ¿Cómo puedo usarlo? Responderé todas estas preguntas con un pequeño pero explicativo ejemplo de código en vivo.

Lia Moreira
Lia Moreira
6 min
07 Dec, 2023

Video Summary and Transcription

Los fixtures en Playwright son como pequeños entornos donde defines métodos y controlas el proceso de prueba. Al crear fixtures reutilizables, puedes hacer las pruebas más legibles y reutilizables. La estructura de un fixture consta de un bloque antes, la prueba y un bloque después. El uso de fixtures te permite acceder a los métodos creados en un objeto de página, mejorando la legibilidad y reutilización del código.

Available in English

1. Introducción a los Fixtures

Short description:

Hola a todos. Soy Lia, la guardiana de la calidad de la aplicación. Mi objetivo es ayudarte a entender los fixtures y cómo crear los tuyos. Los fixtures son como pequeños entornos en Playwright, donde defines métodos y cosas. Playwright nos da la oportunidad de crear nuestros propios fixtures, proporcionando control sobre el proceso de prueba.

Hola a todos. Soy Lia. Espero que se estén divirtiendo hoy. Mi descripción de trabajo en Bleep es ingeniera de aseguramiento de calidad, pero me gusta describirme como la guardiana de la calidad de la aplicación. Mi objetivo aquí es, al final de estos siete minutos más o menos, que obtengan una mejor comprensión de lo que es un fixture y cómo pueden crear el suyo propio.

Entonces, comencemos desde el principio. ¿Qué es un fixture? Bueno, me gusta describir los fixtures en Playwright como un pequeño entorno donde existen métodos y cosas que yo defino. Uso estas analogías como, imagina una piscina de bolas donde Playwright es la piscina de bolas y los fixtures son las pequeñas bolas que están dentro de la piscina de bolas.

¿Y por qué? ¿Por qué usas fixtures? Así que Playwright se basa en fixtures. Todo lo que usamos en Playwright es un fixture. La página es un fixture. El navegador de contexto es un fixture. Y como dije anteriormente, Playwright nos da la oportunidad de crear los nuestros. Y puedes preguntar, vale, si Playwright nos da la oportunidad, lo siento, si Playwright nos da el fixture ya, ¿por qué necesito crear el mío? Bueno, la respuesta es control. Pero vale, esto no está funcionando. Claro que necesitamos tener problemas. Vale, control. Vale. ¿Control de qué? Bueno, veamos un pequeño ejemplo.

2. Creando Fixtures Reutilizables

Short description:

Para hacer la prueba más legible y reutilizable, la paso a un objeto de página con mis propios métodos. Al crear un fixture, puedo hacer que estos métodos estén disponibles para su uso. La estructura del fixture consta de un bloque antes, la prueba y un bloque después. En lugar de importar la prueba y usar la página, importo y uso mi fixture en la prueba. Esto me permite acceder a los métodos que creé en el objeto de página, haciendo que el código sea más legible y reutilizable. Los fixtures de Playwright proporcionan control sobre los métodos utilizados en el fixture, creando un entorno pequeño y controlable.

Entonces, esta es una prueba que creé, y puedes ver que está utilizando el fixture de página. Estoy importando la prueba de Playwright. Tengo un antes. Estoy comprobando algunos títulos y rellenando algunos forms. Pero esto no es realmente reutilizable y no puedes entender realmente si no tienes el contexto de la aplicación, qué se está haciendo aquí.

Entonces, ¿cómo puedo hacer esto más fácil de leer y más reutilizable para todos los que necesitan agregar pruebas para usarlo? Entonces la respuesta es, voy a pasar esto a un objeto de página que tiene mis propios métodos. Y puedes ver aquí que tengo getTitle, clickButtons, fillForms. Entonces, estos son mis métodos, mis objetos de página, pero esto por sí solo no los hace disponibles en el fixture de página.

Entonces, lo que necesito hacer para que estén disponibles para usar es, bueno, crear un fixture. Entonces la estructura aquí es, necesito tener una función que le diga a Playwright, añade mi fixture a la tierra de la característica. Entonces la prueba es la tierra de las características y voy a extender mis propias características. Y en mi definición de fixture, va a estar mi prueba. Puedes usar otros fixtures como una sección de fixture para hacer cosas, pero lo principal aquí es la estructura. Entonces, la estructura para el fixture va a ser el bloque antes, la prueba y luego el bloque después. Entonces, lo que estoy haciendo aquí es, si miras la prueba inicial, tengo un gancho antes y comparando con mi fixture, el mismo gancho antes está allí. Luego voy a usar mis métodos en la página inicial y después de la ejecución, voy a hacer un console.log de algo.

Entonces, ¿cómo puedo usar esto en mi prueba? Entonces, en lugar de importar la prueba, en lugar de usar la página, ahora lo que voy a hacer es importar mi fixture y usar mi fixture en la prueba e importar mi prueba que es el fixture actual. Y como puedes ver allí, tiene acceso a mis métodos que creé en el objeto de página. Es un poco más legible y es muy reutilizable porque si quiero tener, digamos, otras 10 pruebas que pasen por esto, puedes simplemente reutilizarlo en lugar de tener que recodificar todo. Entonces, el control que nos dan los Fixtures de PlayWrite es que puedo decidir qué métodos necesito usar o qué quiero usar en mi fixture. Tengo un entorno realmente pequeño que es muy controlable y muy reutilizable. Entonces, espero que esto les dé un poco más de visión sobre los fixtures y cómo pueden usarlos en sus pruebas. Y eso es todo, chicos. Gracias.

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

Atomic Deployment for JS Hipsters
DevOps.js Conf 2024DevOps.js Conf 2024
25 min
Atomic Deployment for JS Hipsters
Deploying an app is all but an easy process. You will encounter a lot of glitches and pain points to solve to have it working properly. The worst is: that now that you can deploy your app in production, how can't you also deploy all branches in the project to get access to live previews? And be able to do a fast-revert on-demand?Fortunately, the classic DevOps toolkit has all you need to achieve it without compromising your mental health. By expertly mixing Git, Unix tools, and API calls, and orchestrating all of them with JavaScript, you'll master the secret of safe atomic deployments.No more need to rely on commercial services: become the perfect tool master and netlifize your app right at home!
Effective Performance Testing to your Server with Autocannon
TestJS Summit 2021TestJS Summit 2021
36 min
Effective Performance Testing to your Server with Autocannon
Top Content
Performance testing expertise that is developed for a long time. In order to measure your server performance you need a tool that can efficiently simulate a lot of abilities and give you good measurements according your analysing criteria.Autocannon NPM library gave me exactly that - that library is super easy to install and has a very simple API to work with. Within a really short amount of time you can start do performance testing to your application and get good measurements in development environment and in your performance labs, and generate complicated testing scenarios.In this talk I will introduce Autocannon, explain how to efficiently analyse your server performance with it, and show how it helped me to understand complicated performance issues in my Node.js servers. At the end of this lecture, developers will be able to have the ability to integrate a fast and easy tool in order to measure your server performance.
Delightful Integration Tests With Testcontainers
TestJS Summit 2022TestJS Summit 2022
21 min
Delightful Integration Tests With Testcontainers
Top Content
Dockerized services are an excellent tool for creating repeatable, isolated environments ideal for integration tests. In this session, we'll look at the Testcontainers libraries which provide flexible and intuitive API for programmatically controlling lifecycle of your service dependencies in Docker containers. Running databases, Kafka, Elasticsearch, and even cloud technologies, straight from your test code ensures environment config is always up-to-date and consistent during local development and in CI pipelines.You’ll learn everything necessary to start adding powerful integration tests to your codebase without the headache of managing external service dependencies manually!
Visual Regression with Puppeteer, Playwright and Cypress
TestJS Summit 2021TestJS Summit 2021
9 min
Visual Regression with Puppeteer, Playwright and Cypress
Visual Regression tests components via screenshot matching. I'll show how you do that in three different libraries/frameworks. Additionally, I will use Storybook to extract the components from your SPA choice.
Playwright Can Do This?
TestJS Summit 2022TestJS Summit 2022
23 min
Playwright Can Do This?
Guaranteeing that your application doesn't break while constantly shipping new features is tough. Obviously, with a continually growing app or site, you can't test everything manually all the time!Test automation and monitoring are crucial to avoiding shipping broken apps and sites. But what functionality should you test? When should you run your tests? And aren't complex test suites super slow?In this session, we'll get our hands on Playwright, the end-to-end testing framework, and learn how to automate headless browsers to ensure that you confidently ship new features.
The Lazy Developer Guide: How to Automate Code Updates?
DevOps.js Conf 2022DevOps.js Conf 2022
22 min
The Lazy Developer Guide: How to Automate Code Updates?
How to update hundreds of projects all at once? With organizations rapidly growing, demand for the scalability of the teams grows which directly impacts projects structure and ownership. The usual dilemma is mono- vs. multi-repos, but ... What if I tell you that it does not matter much? Both approaches can punch you in the face at some point, so perhaps it is better to think bottom-up.
Today I will walk you through some of the biggest challenges that exist in both approaches and those are managing dependencies across a few hundred projects, global code updates and many other things. I will also show you examples of how we solved this inside Infobip through building our own internal libraries.

Workshops on related topic

Automated accessibility testing with jest-axe and Lighthouse CI
TestJS Summit 2021TestJS Summit 2021
85 min
Automated accessibility testing with jest-axe and Lighthouse CI
Workshop
Bonnie Schulkin
Bonnie Schulkin
Do your automated tests include a11y checks? This workshop will cover how to get started with jest-axe to detect code-based accessibility violations, and Lighthouse CI to validate the accessibility of fully rendered pages. No amount of automated tests can replace manual accessibility testing, but these checks will make sure that your manual testers aren't doing more work than they need to.
Automated Testing Using WebdriverIO
TestJS Summit 2022TestJS Summit 2022
163 min
Automated Testing Using WebdriverIO
Workshop
Kevin Lamping
Kevin Lamping
In this workshop, I cover not only what WebdriverIO can do, but also how you'll be using it day-to-day. I've built the exercises around real-world scenarios that demonstrate how you would actually set things up. It's not just "what to do," but specifically "how to get there." We'll cover the fundamentals of Automated UI testing so you can write maintainable, useful tests for your website and/or web app.
JS Security Testing Automation for Developers on Every Build
TestJS Summit 2021TestJS Summit 2021
111 min
JS Security Testing Automation for Developers on Every Build
WorkshopFree
Oliver Moradov
Bar Hofesh
2 authors
As a developer, you need to deliver fast, and you simply don't have the time to constantly think about security. Still, if something goes wrong it's your job to fix it, but security testing blocks your automation, creates bottlenecks and just delays releases...but it doesn't have to...

NeuraLegion's developer-first Dynamic Application Security Testing (DAST) scanner enables developers to detect, prioritise and remediate security issues EARLY, on every commit, with NO false positives/alerts, without slowing you down.

Join this workshop to learn different ways developers can access Nexploit & start scanning without leaving the terminal!

We will be going through the set up end-to-end, whilst setting up a pipeline, running security tests and looking at the results.

Table of contents:
- What developer-first DAST (Dynamic Application Security Testing) actually is and how it works
- See where and how a modern, accurate dev-first DAST fits in the CI/CD
- Integrate NeuraLegion's Nexploit scanner with GitHub Actions
- Understand how modern applications, APIs and authentication mechanisms can be tested
- Fork a repo, set up a pipeline, run security tests and look at the results
Security Testing Automation for Developers on Every Build
GraphQL Galaxy 2021GraphQL Galaxy 2021
82 min
Security Testing Automation for Developers on Every Build
WorkshopFree
Oliver Moradov
Bar Hofesh
2 authors
As a developer, you need to deliver fast, and you simply don't have the time to constantly think about security. Still, if something goes wrong it's your job to fix it, but security testing blocks your automation, creates bottlenecks and just delays releases, especially with graphQL...but it doesn't have to...

NeuraLegion's developer-first Dynamic Application Security Testing (DAST) scanner enables developers to detect, prioritise and remediate security issues EARLY, on every commit, with NO false positives / alerts, without slowing you down.

Join this workshop to learn different ways developers can access NeuraLegion's DAST scanner & start scanning without leaving the terminal!

We will be going through the set up end-to-end, whilst setting up a pipeline for a vulnerable GraphQL target, running security tests and looking at the results.

Table of contents:
- What developer-first DAST (Dynamic Application Security Testing) actually is and how it works
- See where and how a modern, accurate dev-first DAST fits in the CI/CD
- Integrate NeuraLegion's scanner with GitHub Actions
- Understand how modern applications, GraphQL and other APIs and authentication mechanisms can be tested
- Fork a repo, set up a pipeline, run security tests and look at the results