You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

1 Días
4 Hrs
46 Min
11 Seg

Ejecuta tus tests

4/17
Resources

How to run tests in three different ways with Playwright?

Getting started with Playwright involves not only generating tests, but also exploring them from various angles and formats. Here we guide you through the process, from opening the tests in Visual Studio Code and running them in the terminal, to using different configurations that Playwright offers to adjust the test execution according to your needs.

How to create and run a new test with Playwright?

One of the first things we want to master when working with Playwright is creating and running tests. You can follow these steps to get started:

  1. Create a new test:

    • Make sure you have Playwright installed in your working directory.
    • Use the command to generate a test:
      npx playwright-gen
    • Visit the UI Testing Playground site to practice your testing skills.
  2. Log actions:

    • Perform interactions on the website.
    • For example, navigating between different links such as "Aristotle" and "Resources".
  3. Copy and save the test:

    • Once you have recorded the actions, copy the test to a new file, e.g. uittesting.spec.ts.
  4. Run the test:

    • Use the following command to run your test:
      npx playwright test uittesting
      .
    • Make sure the file name is correct when running the test.

What happens when I run a test report in HTML?

Once you run your tests, Playwright generates an HTML report that allows you to examine the details of the test run.

  • Generate and view the report:
    • Use the command:
      npx playwright show-report
      .
    • This will open an interactive report in a browser where you can view all the steps of your tests, check which tests passed and failed, and identify any "flaky" or skipped tests.

How to run tests in headed mode and with slow animation?

Visualizing how tests run step-by-step can be crucial for debugging and tuning the expected behavior.

  1. Headed mode:

    • Run the tests showing the browser and actions:
      npx playwright test uittesting --headed
      .
    • Useful to see in real time how actions are performed in the browser.
  2. Slowmotion animation:

    • Adds options to the playwright.config.ts file to slow down execution speed when debugging or understanding actions clearly:
      // Add this setting inside launch optionsuse: { launchOptions: { slowMo: 300 // milliseconds }}
    • Set the duration of each action in milliseconds for better observation.

How to run multiple tests simultaneously and speed up your workflow?

With Playwright, you are not limited to running tests sequentially; you can run multiple tests and parallelize tasks to optimize workflow.

  • Configure multiple tests:

    • Define which folder contains the tests or if you need to run multiple files not necessarily ordered:
      npx playwright test # run all tests in the configured directory.
    • Use the automatic parallelization that Playwright offers: it will run multiple tests simultaneously using workers.
  • Customize and understand the execution:

    • Adjust the configuration file to define in which directory to look for tests and optimize the execution:
      • Comment out or clearly define the target folder to avoid unforeseen execution issues.

What to do if the test fails?

When a test fails, Playwright automatically displays the result in the browser to give detailed information about the failure.

  1. Locate and diagnose the error:

    • Check for an error in an element's selector, which may be causing a bug in the locators.
    • Sometimes correcting small inconsistencies in the selector solves big problems.
  2. Future testing:

    • In complicated situations, modify locators or review error lines from generated reports.

How to keep improving your Playwright skills?

In addition to practicing with the commands and settings shown, follow these recommendations:

  • Review additional documentation and resources:
    • Explore Playwright's official documentation to discover new features and optimizations.
    • Investigate new ways to organize and run tests to suit your specific workflows.

With this foundation, you will not only create efficient tests, but also get better at debugging and optimizing the performance of your applications. Continue to explore and grow in this fascinating area of web development!

Contributions 9

Questions 7

Sort by:

Want to see more contributions, questions and answers from the community?

Anatomía de los Test

El patrón más común para generar una prueba es mediante 3A (Arrange Act Asset). El cual explica la forma de organizar y estructurar las pruebas para que fuesen claras y entendibles, separando cada prueba según el enfoque se pretende dar.
.

  • Organización (Arrange). Inicializa los objetos, estableciendo sus estados o valores iniciales.
  • Acto (Act). La invocación de la prueba según sea el escenario estipulado.
  • Afirmación (Asset). Se verifica la acción, según sea lo esperado por la prueba.

.

describe('Button', () => {
	// Arrage of block/section
	const handleClick = () => console.log('On Click')

	test('Should be able to show text in button', () => {
		// Arrage of test
		const buttonText = 'Click Me!'
		const component = await mount(
<Button onClick=handleClick>{buttonText}</Button>)

		// Act
		await component.click();

		// Assert
		await expect(component).toContainText('Click Me!');
	})
	test('Should be able to pass a callback function', () => { ... })
})

Test

ℹ️ Definición
Testing es el proceso de ejecutar un programa con el objetivo de encontrar errores. Si el “testing” es exitoso, entonces podemos asegurarnos que los features están cumplidos.

.
Las ventajas de poseer testing son:

  • Conocemos mejor el código y sus implicaciones en otros procesos (integración testing).
  • Reducimos el tiempo de desarrollo y horas de revisión para encontrar el “error”.

.

Principios del testing

  1. Todos los “test” deberán estar orientados a los requerimientos del cliente o negocio.
  2. Los “test”, deberán establecer, en conjunto, los alcances o puntos críticos de una aplicación.

.
Existen 4 definiciones en las pruebas:

  • Anomalía, es un comportamiento que no se espera dentro del sistema.
  • Defecto, situación que se puede reproducir y se sabe que causa problemas al sistema.
  • Fallo, incapacidad del sistema dentro de los márgenes conocidos.
  • Error, acción humana que genera desperfectos en el sistema.

.
Digamos por ejemplo:
Contamos con un despertador que todas las mañanas a las 9 AM suena su alarma, pero desde hace unos días ya no lo hace, eso es una anomalía, en caso de que hubiera llegado con una manecilla rota, seria defecto, si necesita luz para funcionar que, por una tormenta, se nos va la luz y ya no sirve, es fallo y por último si utilizas tu despertador para otro fin, es un error.
.

Tipos de pruebas

Pruebas unitarias

  • Las pruebas unitarias son el nivel básico, limitadas al recurso de la aplicación. Consisten en las pruebas individuales de métodos y funciones de clases, componentes o módulos.

Pruebas de integración

  • Las pruebas de integración verifican que, los diferentes módulos o servicios, trabajen para su objetivo.

Pruebas funcionales

  • Enfocadas sobre los requerimientos de una aplicación, validan la salida de una acción y no se detienen para revisar estados intermedios de un sistema.

Pruebas de satisfacción o Alpha

  • Son pruebas que son ejecutadas para verificar si un sistema satisface sus requerimientos de negocio. Requieren que la aplicación esté en una fase llamada “testing or test”, el cual supone que se encuentra lista para replicar el comportamiento del usuario.

Entre sus validaciones pudieran ser:

  • El rendimiento del sistema.
  • Cambios visuales o adaptativos.

Son típicamente echas por el equipo de QA.

Pruebas de usuario o Beta

  • Esta prueba es conducida por uno o varios clientes. Esta versión es lanzada para “simular” un entorno real.

Dependiendo de su ámbito, puede contener diferentes contextos:

  • Escala o audiencia.
  • Sistema operativo o dispositivo final.
  • Seguridad.
  • Estrés.
  • Comunicación.

A la par estoy tomando el curso de accesibilidad web y observo que en la documentacion hay una opcion, tiene documentacion de leer para rato

para la prueba del error, el reporte no me abrió automaticamente
Soy nuevo en este rol, me ha gustado lo que veo que puede hacer esta herramienta, pero quiero saber si hay forma de que no se inicie en incognito, ya que esto me activa captcha y al ejecutar el test este falla. Estoy usando python (pytest) gracias por la orientación.
mi caso de test para chromium todo el tiempo falla por timeout "Test timeout of 60000ms exceeded." intente meter una configuracion en el "plawright.config.ts" pero me sigue mostrando el error
Soy tester manual, inicio un nuevo rol cómo automatizador, es increíble cómo sintetiza el proceso Playwright.
comence a hacer mis test con js y veo que mi config es totalmente diferente al de ts :/

Super!