No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Automatización de Compras en Tienda Online con Playwright

9/17
Recursos

¿Cómo realizar pruebas en una tienda online con Playwright?

Las pruebas automatizadas son fundamentales en el desarrollo y mantenimiento de aplicaciones web, y Playwright es una herramienta poderosa para este fin. En esta guía, aprenderás a crear un caso de uso utilizando una tienda online para simular el proceso de añadir un producto al carrito y continuar comprando. Este ejercicio no solo pondrá a prueba tus habilidades en Playwright, sino que también te dará la oportunidad de mejorar tus conocimientos sobre testing automatizado.

¿Cuál es el objetivo del reto propuesto?

El reto consiste en crear un test que imite el flujo de un usuario en una tienda online. La tarea es seleccionar un producto, añadirlo al carrito, y luego continuar comprando, verificando siempre que el flujo se realiza correctamente.

  1. Navegar por la tienda virtual: Desliza para ver los productos disponibles y selecciona el primero que encuentres.
  2. Añadir al carrito: En la página de detalles del producto, añade tres unidades al carrito y elige el tamaño del producto deseado.
  3. Verificación del carrito: Asegúrate de que el producto ha sido añadido exitosamente al carrito mostrando un mensaje de confirmación.
  4. Continuar comprando: Haz clic en "Continue Shopping" para seguir explorando productos y verifica que el modal emergente desaparezca.

¿Cómo escribir el test con Playwright?

Para este reto, comienza creando un archivo llamado tiendaonline.spec.ts y sigue los pasos descritos. Aquí tienes una guía paso a paso:

// Importa las funciones necesarias de Playwright
import { test, expect } from '@playwright/test';

test('Añadir producto al carrito', async ({ page }) => {
  // Paso 1: Abre la tienda online
  await page.goto('http://automationpractice.com/index.php');
  
  // Paso 2: Realiza un hover sobre el primer producto
  await page.hover('#homefeatured li:nth-child(1)');
  
  // Paso 3: Haz clic en 'Ver más detalles'
  await page.click('#homefeatured li:nth-child(1) a[title="View"]');
  
  // Verifica que hemos navegado correctamente a la página de detalles del producto
  await expect(page).toHaveURL(/index.php\?id_product=1/);
  
  // Paso 4: Añade al menos tres productos al carrito
  await page.click('.product_quantity_up');
  await page.click('.product_quantity_up');
  
  // Paso 5: Selecciona el tamaño
  await page.selectOption('#group_1', '2');
  
  // Paso 6: Añade el producto al carrito
  await page.click('button[name="Submit"]');
  
  // Paso 7: Verifica que el producto se añadió exitosamente
  await expect(page.locator('#layer_cart')).toBeVisible();
  await expect(page.locator('#layer_cart')).toContainText('Product successfully added to your shopping cart');
  
  // Paso 8: Haz clic en "Continue Shopping" y verifica que el modal desaparece
  await page.click('.button-container span span[title="Continue shopping"]');
  await expect(page.locator('#layer_cart')).not.toBeVisible();
});

¿Qué hacer si los tests presentan problemas?

Si al ejecutar el test notas errores o tiempos de espera prolongados, considera realizar las siguientes acciones:

  • Optimización del tiempo: Si el test falla por tiempos de espera, retira el modo slow-mo para que las acciones se ejecuten a velocidad normal.
  • Depuración: Revisa cada selector cuidadosamente en el modo de inspección del navegador para asegurarte de que estás apuntando al elemento correcto.
  • Corrige identificadores de selectores: Utiliza IDs o clases únicas para evitar ambigüedades y problemas de selectores múltiples.

¿Cuáles son los beneficios de emplear pruebas automatizadas con Playwright?

Las pruebas automatizadas con Playwright no solo aumentan la eficiencia al evitar pruebas manuales repetitivas, sino que también mejoran la calidad de las aplicaciones mediante pruebas más exhaustivas. Con la capacidad de simular interacciones humanas precisas, Playwright permite a los desarrolladores detectar y corregir bugs en etapas tempranas del desarrollo.

¡Continúa mejorando y experimentando con más casos de uso! Cuantas más pruebas automatices, más seguro y libre de errores será tu software.

Aportes 16

Preguntas 0

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

Mi aporte del contenido actual de la página de ejemplo

import { test, expect } from '@playwright/test';

test('carrito', async ({ page }) => { 

// ir a la pagina
await page.goto('https://automationexercise.com/products');

//hover en producto
await page.hover('a[href="/product_details/1"]');

//click en producto para ver mas detalles
await page.locator('a[href="/product_details/1"]');

//para evitar las ventanas emergentes
await page.goto('https://automationexercise.com/product_details/1');

//hacer click 2 veces
await page.locator('#quantity').click();
await page.locator('#quantity').fill('2');

//añadir al carrito
await page.getByText('Add to cart').click();

//hacer click en continuar
await page.getByText("Continue Shopping").click();

//verificar expect
await expect(page.getByText("Continue Shopping")).toBeHidden();
});

Ojalá se actualice la página de práctica. La página actual tiene ads flotantes que no permiten ejecutar el resto de código de la prueba.

Podría crear un script para cerra el anuncio publicitario, pero no siempre es el mismo tipo de anuncio y no siempre se cierra de la misma manera.

Veré si encuentro otro recurso útil e intentaré compartirlo.

Mi código ya en 2024 ```js import { test, expect } from '@playwright/test'; test("palying with assertions", async ({ page }) => { await page.goto('https://automationexercise.com/'); await page.mouse.wheel(0,550); await page.locator('[class="fa fa-plus-square"]').nth(0).click() await page.locator('#quantity').fill('3'); await page.getByText('Add to cart').click(); await expect(page.locator('[class="modal-title w-100"]')).toContainText('Added!') await page.locator('[class="btn btn-success close-modal btn-block"]').click() await expect(page.locator('[class="modal-content"]')).toBeHidden() await page.locator('[class="fa fa-home"]').click() await page.mouse.wheel(0,550); await page.locator('[class="product-image-wrapper"]').nth(0).click(); const productElement = page.locator('[data-product-id="1"]'); await productElement.nth(0).click() await page.locator('[class="btn btn-success close-modal btn-block"]').click() await page.locator('[class="product-image-wrapper"]').nth(1).click(); const productElement2 = page.locator('[data-product-id="2"]'); await productElement2.nth(1).click() await page.locator('[class="btn btn-success close-modal btn-block"]').click() }); ```
```js import { test, expect } from '@playwright/test'; test('Buy on the page', async ({ page }) => { //abrir pagina await page.goto('https://automationexercise.com/'); // await page.locator('(//i[contains(@class, \'fa fa-plus-square\')])[1]').click(); //verificar pagina visible await expect(page).toHaveURL('https://automationexercise.com/product_details/1'); //seleccionar cantidad await page.locator('#quantity').fill('3'); //Añadir al carro await page.locator('(//button[contains(normalize-space(), "Add to cart")])[1]').click(); //verificar modal await expect(page.locator('#cartModal')).toContainText('Added!'); //clic en continuar await page.locator('(//button[contains(normalize-space(), "Continue Shopping")])').click(); //verificar que el modal no es visible await expect(page.locator('.btn.btn-success.close-modal.btn-block')).not.toBeVisible(); }); ```import { test, expect } from '@playwright/test'; test('Buy on the page', async ({ page }) => {  //abrir pagina  await page.goto('https://automationexercise.com/');  //  await page.locator('(//i\[contains(@class, \\'fa fa-plus-square\\')])\[1]').click();  //verificar pagina visible  await expect(page).toHaveURL('https://automationexercise.com/product\_details/1');  //seleccionar cantidad  await page.locator('#quantity').fill('3');  //Añadir al carro  await page.locator('(//button\[contains(normalize-space(), "Add to cart")])\[1]').click();  //verificar modal  await expect(page.locator('#cartModal')).toContainText('Added!');  //clic en continuar  await page.locator('(//button\[contains(normalize-space(), "Continue Shopping")])').click();  //verificar que el modal no es visible  await expect(page.locator('.btn.btn-success.close-modal.btn-block')).not.toBeVisible();  });
Buen día comparto mi aporte: ```js import { test, expect } from '@playwright/test'; test('test', async ({ page }) => { await page.goto('https://automationexercise.com/'); await page.hover ('.choose > .nav > li > a'); await page.locator('.choose > .nav > li > a').first().click(); await expect(page).toHaveURL('https://automationexercise.com/product_details/1'); await page.locator('#quantity').fill('4'); await page.locator('button[class="btn btn-default cart"]').click(); await expect(page.locator('.modal-content')).toBeVisible(); await page.locator('.close-modal').click(); await expect(page.locator('.modal-content')).not.toBeVisible(); }); ```import { test, expect } from '@playwright/test'; test('test', async ({ page }) => {  await page.goto('https://automationexercise.com/');   await page.hover ('.choose > .nav > li > a');  await page.locator('.choose > .nav > li > a').first().click();  await expect(page).toHaveURL('https://automationexercise.com/product\_details/1');  await page.locator('#quantity').fill('4');  await page.locator('button\[class="btn btn-default cart"]').click();  await expect(page.locator('.modal-content')).toBeVisible();  await page.locator('.close-modal').click();  await expect(page.locator('.modal-content')).not.toBeVisible();  });
muy bien
por aqui mi solucion ![](https://static.platzi.com/media/user_upload/image-bd577745-fa47-415b-af36-edc4f1e12422.jpg)
```js import { test, expect } from '@playwright/test'; test("añadir producto al carrito", async ({ page }) => { // ir a la url https://automationexercise.com/products await page.goto("https://automationexercise.com/products"); //hover del primer producto que encontremos await page.hover("body > section:nth-child(3) > div > div > div.col-sm-9.padding-right > div > div:nth-child(3)"); //click en el primer producto ver mas detalles await page.click("body > section:nth-child(3) > div > div > div.col-sm-9.padding-right > div > div:nth-child(3) a:has-text('View Product')"); await expect(page).toHaveURL("https://automationexercise.com/product_details/1"); //click en el boton + (dos veces) await page.locator("#quantity").fill("3"); //seleccionar en el menu dropdown un nuevo tamaño //await page.locator('#group_1').selectOption({ index: 1 }); //click en boton añadir al carrito await page.click('body > section > div > div > div.col-sm-9.padding-right > div.product-details > div.col-sm-7 > div > span > button') // verificar (expect) "Added!" await expect(page.locator('#cartModal > div > div > div.modal-header > h4')).toBeVisible(); await expect(page.locator('#cartModal > div > div > div.modal-header > h4')).toContainText("Added!"); //click en boton continue shopping await page.click('#cartModal > div > div > div.modal-footer > button') //el modal debe no ser visible await page.click('#header > div > div > div > div.col-sm-8 > div > ul > li:nth-child(1) > a'); }); ```import { test, expect } from '@playwright/test'; test("añadir producto al carrito", async ({ page }) => {// ir a la url <https://automationexercise.com/products>    await page.goto("https://automationexercise.com/products");//hover del primer producto que encontremos    await page.hover("body > section:nth-child(3) > div > div > div.col-sm-9.padding-right > div > div:nth-child(3)");//click en el primer producto ver mas detalles    await page.click("body > section:nth-child(3) > div > div > div.col-sm-9.padding-right > div > div:nth-child(3) a:has-text('View Product')");    await expect(page).toHaveURL("https://automationexercise.com/product\_details/1");//click en el boton + (dos veces)    await page.locator("#quantity").fill("3");//seleccionar en el menu dropdown un nuevo tamaño    //await page.locator('#group\_1').selectOption({ index: 1 });//click en boton añadir al carrito    await page.click('body > section > div > div > div.col-sm-9.padding-right > div.product-details > div.col-sm-7 > div > span > button')// verificar (expect) "Added!"    await expect(page.locator('#cartModal > div > div > div.modal-header > h4')).toBeVisible();    await expect(page.locator('#cartModal > div > div > div.modal-header > h4')).toContainText("Added!");//click en boton continue shopping    await page.click('#cartModal > div > div > div.modal-footer > button')//el modal debe no ser visible    await page.click('#header > div > div > div > div.col-sm-8 > div > ul > li:nth-child(1) > a');}); Mi codigo
MI aporte, mezclando cosas de playwright y xpath ```js import { test, expect } from '@playwright/test'; test('test-reto', async ({ page }) => { await page.goto('https://automationexercise.com/#google_vignette'); await page.locator('.choose > .nav > li > a').first().click(); await page.locator('#quantity').fill('3'); await page.locator('//button [@class= "btn btn-default cart"]').click(); await expect(page.locator('//h4 [@class= "modal-title w-100"]')).toBeVisible(); await page.getByRole('button', {name: 'Continue Shopping'}).click(); await expect(page.locator('.modal-content')).toBeDisabled; }); ```import { test, expect } from '@playwright/test'; test('test-reto', async ({ page }) => {  await page.goto('https://automationexercise.com/#google\_vignette');     await page.locator('.choose > .nav > li > a').first().click();   await page.locator('#quantity').fill('3');    await page.locator('//button \[@class= "btn btn-default cart"]').click();  await expect(page.locator('//h4 \[@class= "modal-title w-100"]')).toBeVisible();   await page.getByRole('button', {name: 'Continue Shopping'}).click();   await expect(page.locator('.modal-content')).toBeDisabled; });
import { test, expect } from '@playwright/test';import { chromium } from 'playwright'; test('playing with assertios', async ({ page }) => { await page.goto('https://automationexercise.com/category\_products'); await page.locator('a\[href\*="product\_details/2"]').first().click(); await page.locator('#.quantity').fill('3'); await page.getByRole('button', { name: 'Add to cart' }).click(); await expect(page.locator('.modal-content')).toBeEnabled(); await expect(page.locator('.modal-header')).toContainText('Added!'); await page.locator('.close-modal').click(); await expect(page.locator('.modal-content')).toBeHidden(); })
import { test, expect } from "@playwright/test";

test("test", async ({ page }) => {
  await page.goto("https://automationexercise.com/");
  page
    .locator(".features_items")
    .locator(".product-image-wrapper")
    .filter({
      has: page.locator(".single-products > .productinfo > p", {
        hasText: "Blue Top",
      }),
    })
    .locator(".choose > .nav > li > a")
    .click();
  await page.mouse.click(0, 0);
  await page.locator("#quantity").fill("3");
  await page.getByRole("button", { name: " Add to cart" }).click();
  await expect(page.getByText("Added!")).toBeVisible();
  await page.getByRole("button", { name: "Continue Shopping" }).click();
  await expect(page.locator('#cartModal')).not.toBeVisible();
});

Asi quedo el mi tests de este reto:

<import { test, expect } from '@playwright/test';

test('Añadir producto al carrito', async ({ page }) => {
  //Abre en el navegaador la tienda virtual 
  await page.goto('https://automationexercise.com/products');
    
  //Desliza hasta ver los productos
  await page.locator('img[src="/get_product_picture/1"]').hover();

  // Haz click en "Ver más detalles" del primer producto
  await page.locator('a[href="/product_details/1"]').click();
 
  if (await page.frameLocator('iframe[name="aswift_5"]').frameLocator('iframe[name="ad_iframe"]').getByRole('button', { name: 'Close ad' }).isVisible()){
    await page.frameLocator('iframe[name="aswift_5"]').frameLocator('iframe[name="ad_iframe"]').getByRole('button', { name: 'Close ad' }).click();
  }
  expect(page).toHaveURL('https://automationexercise.com/product_details/1')

  // Usal el boton (+) para añadir 3 productos al carrito
  await page.locator('#quantity').fill('3');

  // Haz click en añadir al carrito
  await page.getByText('Add to cart').click();

  // Verifica que el modal y el texto de "Sucess" aparece
  expect(await page.locator('div[class="modal-dialog modal-confirm"]').isVisible()).toBeTruthy();
  await expect(page.getByText('Added!')).toBeVisible();

  // Haz click en el boton de "Continue Shopping"
  await page.getByText('Continue Shopping').click();

  // Verifica que el modal ya no es visible
  await expect(page.getByText('Continue Shopping')).toBeHidden();

});> 

Use el codegen para poder cerrar la publicidad pero es un buen avance

import { test, expect } from '@playwright/test';

test('challenge test', async ({ page }) => {
    // ir a la url
    await page.goto('https://automationexercise.com/products');
    // remove ad
    await page.locator('.grippy-host').click();
    // Click view product
    await page.locator('a[href="/product_details/1"]').click();
    // close ads
    await page.frameLocator('iframe[name="aswift_5"]').frameLocator('iframe[name="ad_iframe"]').getByRole('button', { name: 'Close ad' }).click();
    // Verify url
    await expect(page).toHaveURL('https://automationexercise.com/product_details/1')
    // Select quantity 3
    await page.locator('#quantity').fill('3')
    // click add to cart
    await page.getByRole('button', { name: ' Add to cart' }).click();
    // verify message added
    await expect(page.getByRole('heading', { name: 'Added!' })).toContainText('Added')
    // click continue shopping
    await page.getByRole('button', { name: 'Continue Shopping' }).click();
    // verify modal not visible
    await expect(page.getByRole('heading', { name: 'Added!' })).toBeHidden()

  
});

Lets go !! 🤙

Tambien para poder seleccionar el primer elemento se puede hacer de la siguiente manera:

await page.hover("#homefeatured > li:first-child")

Mi solución al reto.

import { test, expect } from '@playwright/test';

const BASE_URL = 'https://automationexercise.com/';

test('Order a product on Shop', async ({ page }) => {
  await page.goto(BASE_URL);
  await expect(page).toHaveURL(BASE_URL)
  await page.hover("a[href='/product_details/5']");
  await expect(page.getByText('View Product')).toHaveCount(34);
  await page.locator("a[href='/product_details/1']").click();
  const quantity = await page.locator("input[type='number']");
  await quantity.clear();
  await quantity.click();
  await quantity.fill("3");
  await page.getByText("Add to cart").click();
  await page.getByText("Continue Shopping").click();
  await expect(page.getByText("Continue Shopping")).toBeHidden();
});