utils.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { expect, type Page } from "@playwright/test";
  2. export async function clickOnRandomProductElement({ page }: { page: Page }) {
  3. const productLinks = page.getByTestId("ProductElement");
  4. await productLinks.first().waitFor();
  5. const count = await productLinks.count();
  6. const nth = Math.floor(Math.random() * count);
  7. return clickOnNthProductElement({ page, nth });
  8. }
  9. export async function clickOnNthProductElement({ page, nth }: { page: Page; nth: number }) {
  10. const productLinks = page.getByTestId("ProductElement");
  11. await productLinks.first().waitFor();
  12. const randomProductLink = productLinks.nth(nth);
  13. const name = await randomProductLink.getByRole("heading").textContent();
  14. const priceRange = await randomProductLink.getByTestId("ProductElement_PriceRange").textContent();
  15. const category = await randomProductLink.getByTestId("ProductElement_Category").textContent();
  16. await randomProductLink.click();
  17. await page.waitForURL("**/products/*");
  18. expect(name, "Missing product name").toBeTruthy();
  19. expect(priceRange, "Missing product priceRange").toBeTruthy();
  20. expect(category, "Missing product category").toBeTruthy();
  21. return { name: name!, priceRange: priceRange!, category: category! };
  22. }
  23. export async function getCurrentProductPrice({ page }: { page: Page }) {
  24. const price = await page.getByTestId("ProductElement_Price").textContent();
  25. expect(price, "Missing product price").toBeTruthy();
  26. return Number.parseFloat(price!.replace(/[^0-9\.]/g, ""));
  27. }
  28. export async function selectRandomAvailableVariant({ page }: { page: Page }) {
  29. // some products only have a single variant so this block can throw and it's expected
  30. try {
  31. await page.getByTestId("VariantSelector").waitFor({ timeout: 1000 });
  32. const variant = page.getByTestId("VariantSelector").getByRole("radio", { disabled: false });
  33. const count = await variant.count();
  34. if (count > 0) {
  35. await variant.nth(Math.floor(Math.random() * count)).click();
  36. }
  37. } catch {}
  38. await page.waitForURL(/\?variant=.+/);
  39. }
  40. export async function addCurrentProductToCart({ page }: { page: Page }) {
  41. expect(page.url()).toContain("/products/");
  42. expect(page.url()).toContain("?variant=");
  43. const checkoutButton = page.getByRole("button", { name: "Add to cart" });
  44. await checkoutButton.click();
  45. await checkoutButton.isEnabled();
  46. }
  47. export async function openCart({ page }: { page: Page }) {
  48. await page.getByTestId("CartNavItem").click();
  49. await page.getByText("Your Shopping Cart").waitFor();
  50. }