From 0d8045cd502fb11e78ecdcaabae27def56c83717 Mon Sep 17 00:00:00 2001 From: Ryan Spore Date: Wed, 13 Nov 2024 11:49:51 -0800 Subject: [PATCH] Implements Locator.or_ --- lib/playwright/locator.ex | 14 +++++++++-- test/api/locator_test.exs | 51 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 2 deletions(-) diff --git a/lib/playwright/locator.ex b/lib/playwright/locator.ex index bc7170e..99eca22 100644 --- a/lib/playwright/locator.ex +++ b/lib/playwright/locator.ex @@ -902,8 +902,18 @@ defmodule Playwright.Locator do locator(context, "nth=#{index}") end - # @spec or(Locator.t(), Locator.t()) :: Locator.t() - # def or(locator, other) + @doc """ + Returns a new `Playwright.Locator` that matches either of the conditions of the given locators. + + This implements the `or` function for locators, but `or` is not an allowed function name in elixir. + """ + @spec or_(Locator.t(), Locator.t()) :: Locator.t() + def or_(%Locator{frame: frame} = locator, %Locator{frame: frame} = other) do + new(frame, locator.selector <> ">> internal:or=" <> Jason.encode!(other.selector)) + end + def or_(_, _) do + raise ArgumentError, "Locators must belong to the same frame" + end # @spec page(Locator.t()) :: Page.t() # def page(locator) diff --git a/test/api/locator_test.exs b/test/api/locator_test.exs index a24e9a2..34a0dc7 100644 --- a/test/api/locator_test.exs +++ b/test/api/locator_test.exs @@ -641,6 +641,57 @@ defmodule Playwright.LocatorTest do end end + describe "Locator.or_/2" do + test "returns a locator that matches either given condition", %{page: page} do + page + |> Page.set_content(""" +
+
pink
+
orange
+
green
+
+ """) + + pink = Page.locator(page, ".pink") + orange = Page.locator(page, ".orange") + redish = Locator.or_(pink, orange) + assert Locator.text_content(redish) == "pink" + + page + |> Page.set_content(""" +
+
orange
+
green
+
+ """) + + pink = Page.locator(page, ".pink") + orange = Page.locator(page, ".orange") + redish = Locator.or_(pink, orange) + + assert Locator.text_content(redish) == "orange" + end + + test "raises an error when the given locators don't share a frame", %{page: page, browser: browser} do + other_page = Playwright.Browser.new_page(browser) + + on_exit(:ok, fn -> + Playwright.Page.close(other_page) + end) + page + |> Page.set_content("
") + + div_locator = Page.locator(page, "div") + other_page + |> Page.set_content("") + span_locator = Page.locator(other_page, "span") + + assert_raise ArgumentError, "Locators must belong to the same frame", fn -> + Locator.or_(div_locator, span_locator) + end + end + end + describe "Locator.press/2" do test "focuses an element and 'presses' a key within it", %{page: page} do locator = Page.locator(page, "input")