MediaAerea-TI
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- title: Guía de Pruebas Automatizadas con Playwright --- # Guía de Pruebas Automatizadas con Playwright **Manual Explicativo Detallado** --- ## Introducción Las pruebas automatizadas son un proceso fundamental dentro del desarrollo de software moderno, ya que permiten verificar que una aplicación funcione correctamente sin necesidad de realizar validaciones manuales repetitivas. Estas pruebas simulan el comportamiento real de un usuario y confirman que cada funcionalidad del sistema responde de la manera esperada. Playwright es una herramienta profesional de automatización desarrollada para probar aplicaciones web modernas. Permite ejecutar pruebas en diferentes navegadores, validar resultados automáticamente, detectar errores en interfaces y asegurar la calidad del software antes de su entrega o publicación. El propósito de esta guía es explicar detalladamente el funcionamiento de Playwright desde cero, mostrando distintas formas de utilizarlo, contemplando: - Diseño de pruebas con código - Diseño de pruebas con la herramienta de grabación integrada (Codegen) - Ejecución de pruebas con comandos desde Visual Studio Code De esta manera, cualquier persona puede comprender cómo implementar pruebas automatizadas correctamente. --- ## Requisitos previos y entorno necesario Antes de instalar y utilizar Playwright, es indispensable contar con ciertos componentes base en el sistema, ya que Playwright depende directamente de ellos para su correcto funcionamiento. ### Node.js (obligatorio) Playwright funciona sobre el entorno de ejecución Node.js. Su instalación es indispensable, ya que permite: - Ejecutar comandos `npx` - Instalar Playwright y sus dependencias - Ejecutar y administrar las pruebas automatizadas Sin Node.js, Playwright no puede instalarse ni ejecutarse. ### Python (recomendado en el entorno) En sistemas Windows es común contar con Python instalado. Aunque Playwright web se basa en Node.js, disponer de Python ayuda a evitar problemas de compatibilidad y errores durante la instalación o ejecución de herramientas auxiliares del sistema. En la práctica, contar con Python instalado contribuye a un entorno más estable. ### Visual Studio Code Visual Studio Code se utiliza como: - Editor principal del proyecto - Terminal integrada para ejecutar comandos - Herramienta de visualización y depuración Todo el flujo de trabajo descrito en esta guía se realiza desde la terminal integrada de VS Code. --- ## 1. ¿Qué es Playwright? Playwright es un framework de automatización que permite controlar navegadores web de forma programada para simular acciones reales de un usuario. Entre sus principales capacidades se encuentran: - Abrir páginas web automáticamente - Interactuar con botones, formularios y menús - Simular escritura en campos - Validar contenido visible - Verificar navegación - Ejecutar múltiples pruebas simultáneamente - Generar reportes automáticos Playwright trabaja con múltiples motores de navegador, lo que permite verificar que una aplicación funcione correctamente en distintos entornos. --- ## 2. Instalación de Playwright La instalación de Playwright se realiza una sola vez por proyecto y depende de que los requisitos previos estén correctamente configurados. ### Pasos de instalación 1. Abrir Visual Studio Code 2. Abrir la terminal dentro del proyecto 3. Ejecutar: ```bash npx init playwright@latest ``` 4. Seguir el asistente de instalación 5. Verificar la instalación ejecutando: ```bash npx playwright test ``` Si la instalación fue correcta, Playwright ejecutará pruebas de ejemplo y mostrará los resultados en la terminal. Ver ayuda general de Playwright ```bash npx playwright --help ``` Esto permite conocer todos los comandos disponibles desde la terminal. ### 2.1 Configuración del entorno (.env) En proyectos reales de automatización no es recomendable escribir directamente en el código datos sensibles como usuarios, contraseñas o direcciones URL. Para solucionar esto, se utilizan variables de entorno, las cuales permiten centralizar la configuración del sistema y reutilizarla en distintos entornos. Las variables de entorno se almacenan en un archivo .env, el cual no debe compartirse en repositorios públicos. ### Instalación de dependencia necesaria Para habilitar el uso de variables de entorno, se debe instalar el siguiente paquete: ```bash npm install dotenv ``` ### Beneficios del uso de variables de entorno - Permiten cambiar de entorno sin modificar los tests. - Protegen información sensible. - Facilitan la ejecución en entornos de QA, desarrollo y producción. - Mejoran la mantenibilidad del proyecto. --- ## 3. Diseño de pruebas usando código Este método es el más elaborado y completo, ya que permite controlar completamente el comportamiento de las pruebas. Los testers escriben scripts donde especifican paso a paso qué acciones debe realizar el navegador. ### ¿Cómo funciona? Cada prueba es un archivo dentro de la carpeta: ```bash tests/ ``` Dentro del archivo se define: - Nombre de prueba - Acciones - Validaciones ### Ejemplo explicado paso a paso ```bash const { test, expect } = require('@playwright/test'); test('Login correcto', async ({ page }) => { await page.goto('http://localhost:5500/Login.html'); await page.fill('#email', 'admin@test.com'); await page.fill('#password', '123'); await page.click('button[type=submit]'); await expect(page).toHaveURL(/Home.html/); }); ``` ### Explicación línea por línea - test() define un caso de prueba - page.goto() abre la página - fill() escribe en inputs - click() presiona botones - expect() valida resultado esperado Si una validación falla, la prueba se detiene y se marca como error. Se recomienda usar este método en sistemas que no tienen una interfaz visual, por ejemplo, APIs. --- ## 4. Diseño de pruebas utilizando Codegen Playwright incluye una función llamada codegen que permite grabar pruebas automáticamente mientras el usuario navega en el sistema. Este modo es ideal para personas que no tienen mucha experiencia en desarrollo o para crear pruebas rápidamente. Se recomienda usar este método cuando: - El tester no tiene experiencia de desarrollo - Se necesita crear pruebas rápidamente ### Funcionamiento Al ejecutar el comando: - Se abre un navegador controlado por Playwright - Se muestra una ventana con el registro de acciones - Cada clic, escritura y navegación es capturada automáticamente Playwright identifica los elementos, sus selectores y genera el flujo completo de la prueba. ### Cómo iniciar grabación Ejecutar en terminal: ```bash npx playwright codegen http://localhost:5500 ``` Se abrirá una ventana de navegador especial que grabará todas las acciones. ### Opciones avanzadas del comando codegen Grabar y generar prueba directamente en un archivo: ```bash npx playwright codegen --output tests/login.spec.js http://localhost:5500 ``` Grabar en modo móvil: ```bash npx playwright codegen --device="Pixel 5" http://localhost:5500 ``` Grabar usando un navegador específico: ```bash npx playwright codegen --browser=firefox http://localhost:5500 ``` ### Qué debe hacer el usuario Simplemente usar el sistema normalmente: - Escribir Datos - Dar clic - Navegar - Abrir módulos Playwright registrará automáticamente cada acción realizada. ### Resultado Mientras el usuario interactúa, Playwright genera el código correspondiente. Esto permite: - Aprender estructura de tests - Ahorrar tiempo - Crear pruebas base ### Uso del código generado El código generado: - Se copia y guarda en un archivo dentro de la carpeta tests/ - Puede ejecutarse directamente sin modificaciones - Sirve como base reutilizable ### Ventajas del modo grabador - No requiere programación - Fácil de usar - Ideal para aprendizaje - Genera código automáticamente - Reduce errores humanos ### Limitaciones - No genera validaciones complejas - El código puede necesitar limpieza - No es ideal para pruebas grandes --- ## 5. Validaciones esenciales en pruebas Una prueba automatizada no solo debe ejecutar acciones, también debe confirmar resultados. Sin validaciones, una prueba solo sería una simulación de navegación. Validaciones recomendadas: #### Validar texto visible Permite confirmar mensajes, títulos o estados. Ejemplo: verificar que aparezca “Bienvenido”. #### Validar existencia de elemento Permite confirmar que un componente existe. Ejemplo: botón Guardar visible. #### Validar URL Confirma que el sistema redirige correctamente. #### Validar valores de campos Permite verificar datos precargados o editados. ### 5.1 Uso de selectores estables con data-testid Uno de los problemas más comunes en las pruebas automatizadas es la inestabilidad de los selectores. Cuando se utilizan selectores basados en texto, clases o estructuras HTML, cualquier cambio visual puede romper las pruebas. Para evitar esto, se recomienda el uso de atributos exclusivos para pruebas, comúnmente llamados data-testid. #### ¿Por qué usar data-testid? - Los selectores no dependen del diseño visual - No se rompen al cambiar estilos o textos - Son claros y fáciles de mantener - Son el estándar en proyectos profesionales Este tipo de selectores permite que las pruebas sean más confiables y estables a largo plazo. --- ## 6. Organización profesional de casos de prueba Nombrar correctamente los tests facilita su mantenimiento y comprensión. Formato requerido: MODULO-ID-DESCRIPCION Ejemplo: LOGIN-01-LoginCorrecto LOGIN-02-LoginIncorrecto REPORTES-01-VerDetalle USUARIOS-01-Registro --- ## 7. Agrupación de pruebas (Suites) Las pruebas pueden organizarse en grupos para ejecutarse juntas. Tipos comunes: #### Smoke tests Validan funciones críticas: - Login - Carga inicial - Navegación #### Pruebas por módulo Permiten validar secciones específicas: - Administración - Reportes - Usuarios - Configuración --- ## 8. Ejecución de pruebas Para ejecutar todas las pruebas: ```bash npx playwright test ``` Para ver reporte visual: ```bash npx playwright show-report ``` El reporte muestra: - Pruebas exitosas - Pruebas fallidas - Errores detallados - Capturas - Tiempos #### Ejecución avanzada desde la terminal Ejecutar un solo archivo de prueba: ```bash npx playwright test tests/example.spec.js ``` Ejecutar pruebas en modo visual (con navegador visible): ```bash npx playwright test --headed ``` Ejecutar pruebas en modo debug paso a paso: ```bash npx playwright test --debug ``` Ejecutar solo pruebas que fallaron previamente: ```bash npx playwright test --last-failed ``` --- ## 9. Emulación de dispositivos Playwright permite simular dispositivos móviles sin configuraciones adicionales. Ejemplo: ```bash npx playwright codegen --device="iPhone 13" http://url.com ``` Esto permite validar diseño responsivo y flujos móviles. --- ## 10. Errores comunes y soluciones Problema: falla por carga lenta Solución: esperar elementos visibles Problema: selectores se rompen Solución: usar ID o data-testid Problema: pruebas dependientes Solución: hacerlas independientes Problema: API lenta Solución: esperar contenido renderizado Problema: error de permisos al ejecutar npx (Windows) Mensaje común: ejecución de scripts deshabilitada. Solución (ejecutar PowerShell como administrador): ```bash Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned ``` Problema: Playwright no abre navegador Solución: reinstalar navegadores ```bash npx playwright install --force ``` --- ## 11. Buenas prácticas profesionales - Crear pruebas pequeñas. - Validar siempre resultados. - Usar nombres claros. - No repetir lógica. - Mantener tests independientes. - Priorizar selectores estables. - Ejecutar pruebas localmente antes de subir cambios. - Usar --debug cuando una prueba falla. - Validar reportes después de cada ejecución. - Mantener consistencia en comandos de ejecución. - Documentar comandos usados en el proyecto. ---

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully