How to use ShouldSupportSomeFancyXpath method of Microsoft.Playwright.Tests.PageWaitForSelector2Tests class

Best Playwright-dotnet code snippet using Microsoft.Playwright.Tests.PageWaitForSelector2Tests.ShouldSupportSomeFancyXpath

Run Playwright-dotnet automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

PageWaitForSelector2Tests.cs

Source: PageWaitForSelector2Tests.cs Github

copy
1/*
2 * MIT License
3 *
4 * Copyright (c) Microsoft Corporation.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25using System;
26using System.Linq;
27using System.Threading.Tasks;
28using Microsoft.Playwright.NUnit;
29using NUnit.Framework;
30
31namespace Microsoft.Playwright.Tests
32{
33    public class PageWaitForSelector2Tests : PageTestEx
34    {
35        private const string AddElement = "tag => document.body.appendChild(document.createElement(tag))";
36
37        [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should survive cross-process navigation")]
38        public async Task ShouldSurviveCrossProcessNavigation()
39        {
40            bool boxFound = false;
41            var waitForSelector = Page.WaitForSelectorAsync(".box").ContinueWith(_ => boxFound = true);
42            await Page.GotoAsync(Server.EmptyPage);
43            Assert.False(boxFound);
44            await Page.ReloadAsync();
45            Assert.False(boxFound);
46            await Page.GotoAsync(Server.CrossProcessPrefix + "/grid.html");
47            await waitForSelector;
48            Assert.True(boxFound);
49        }
50
51        [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should wait for visible")]
52        public async Task ShouldWaitForVisible()
53        {
54            bool divFound = false;
55            var waitForSelector = Page.WaitForSelectorAsync("div", new() { State = WaitForSelectorState.Visible })
56                .ContinueWith(_ => divFound = true);
57            await Page.SetContentAsync("<div style='display: none; visibility: hidden;'>1</div>");
58            Assert.False(divFound);
59            await Page.EvaluateAsync("document.querySelector('div').style.removeProperty('display')");
60            Assert.False(divFound);
61            await Page.EvaluateAsync("document.querySelector('div').style.removeProperty('visibility')");
62            Assert.True(await waitForSelector);
63            Assert.True(divFound);
64        }
65
66        [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should not consider visible when zero-sized")]
67        public async Task ShouldNotConsiderVisibleWhenZeroSized()
68        {
69            await Page.SetContentAsync("<div style='width: 0; height: 0;'>1</div>");
70            var exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(() => Page.WaitForSelectorAsync("div", new() { Timeout = 1000 }));
71            StringAssert.Contains("Timeout 1000ms", exception.Message);
72            await Page.EvaluateAsync("() => document.querySelector('div').style.width = '10px'");
73            exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(() => Page.WaitForSelectorAsync("div", new() { Timeout = 1000 }));
74            StringAssert.Contains("Timeout 1000ms", exception.Message);
75            await Page.EvaluateAsync("() => document.querySelector('div').style.height = '10px'");
76            Assert.NotNull(await Page.WaitForSelectorAsync("div", new() { Timeout = 1000 }));
77        }
78
79        [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should wait for visible recursively")]
80        public async Task ShouldWaitForVisibleRecursively()
81        {
82            bool divVisible = false;
83            var waitForSelector = Page.WaitForSelectorAsync("div#inner", new() { State = WaitForSelectorState.Visible }).ContinueWith(_ => divVisible = true);
84            await Page.SetContentAsync("<div style='display: none; visibility: hidden;'><div id='inner'>hi</div></div>");
85            Assert.False(divVisible);
86            await Page.EvaluateAsync("document.querySelector('div').style.removeProperty('display')");
87            Assert.False(divVisible);
88            await Page.EvaluateAsync("document.querySelector('div').style.removeProperty('visibility')");
89            Assert.True(await waitForSelector);
90            Assert.True(divVisible);
91        }
92
93        [PlaywrightTest("page-wait-for-selector-2.spec.ts", "hidden should wait for removal")]
94        public async Task HiddenShouldWaitForRemoval()
95        {
96            await Page.SetContentAsync("<div>content</div>");
97            bool divRemoved = false;
98            var waitForSelector = Page.WaitForSelectorAsync("div", new() { State = WaitForSelectorState.Hidden })
99                .ContinueWith(_ => divRemoved = true);
100            await Page.WaitForSelectorAsync("div"); // do a round trip
101            Assert.False(divRemoved);
102            await Page.EvaluateAsync("document.querySelector('div').remove()");
103            Assert.True(await waitForSelector);
104            Assert.True(divRemoved);
105        }
106
107        [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should return null if waiting to hide non-existing element")]
108        public async Task ShouldReturnNullIfWaitingToHideNonExistingElement()
109        {
110            var handle = await Page.WaitForSelectorAsync("non-existing", new() { State = WaitForSelectorState.Hidden });
111            Assert.Null(handle);
112        }
113
114        [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should respect timeout")]
115        public async Task ShouldRespectTimeout()
116        {
117            var exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(()
118                => Page.WaitForSelectorAsync("div", new() { State = WaitForSelectorState.Attached, Timeout = 3000 }));
119
120            StringAssert.Contains("Timeout 3000ms exceeded", exception.Message);
121            StringAssert.Contains("waiting for selector \"div\"", exception.Message);
122        }
123
124        [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should have an error message specifically for awaiting an element to be hidden")]
125        public async Task ShouldHaveAnErrorMessageSpecificallyForAwaitingAnElementToBeHidden()
126        {
127            await Page.SetContentAsync("<div>content</div>");
128            var exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(()
129                => Page.WaitForSelectorAsync("div", new() { State = WaitForSelectorState.Hidden, Timeout = 1000 }));
130
131            StringAssert.Contains("Timeout 1000ms exceeded", exception.Message);
132            StringAssert.Contains("waiting for selector \"div\" to be hidden", exception.Message);
133        }
134
135        [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should respond to node attribute mutation")]
136        public async Task ShouldRespondToNodeAttributeMutation()
137        {
138            bool divFound = false;
139            var waitForSelector = Page.WaitForSelectorAsync(".zombo", new() { State = WaitForSelectorState.Attached }).ContinueWith(_ => divFound = true);
140            await Page.SetContentAsync("<div class='notZombo'></div>");
141            Assert.False(divFound);
142            await Page.EvaluateAsync("document.querySelector('div').className = 'zombo'");
143            Assert.True(await waitForSelector);
144        }
145
146        [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should return the element handle")]
147        public async Task ShouldReturnTheElementHandle()
148        {
149            var waitForSelector = Page.WaitForSelectorAsync(".zombo");
150            await Page.SetContentAsync("<div class='zombo'>anything</div>");
151            Assert.AreEqual("anything", await Page.EvaluateAsync<string>("x => x.textContent", await waitForSelector));
152        }
153
154        [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should have correct stack trace for timeout")]
155        public async Task ShouldHaveCorrectStackTraceForTimeout()
156        {
157            Exception exception = null;
158            try
159            {
160                await Page.WaitForSelectorAsync(".zombo", new() { Timeout = 10 });
161            }
162            catch (Exception e)
163            {
164                exception = e;
165            }
166            StringAssert.Contains("WaitForSelector2Tests", exception.ToString());
167        }
168
169        [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should support >> selector syntax")]
170        public async Task ShouldSupportSelectorSyntax()
171        {
172            await Page.GotoAsync(Server.EmptyPage);
173            var frame = Page.MainFrame;
174            var watchdog = frame.WaitForSelectorAsync("css=div >> css=span", new() { State = WaitForSelectorState.Attached });
175            await frame.EvaluateAsync(AddElement, "br");
176            await frame.EvaluateAsync(AddElement, "div");
177            await frame.EvaluateAsync("() => document.querySelector('div').appendChild(document.createElement('span'))");
178            var eHandle = await watchdog;
179            var tagProperty = await eHandle.GetPropertyAsync("tagName");
180            string tagName = await tagProperty.JsonValueAsync<string>();
181            Assert.AreEqual("SPAN", tagName);
182        }
183
184        [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should wait for detached if already detached")]
185        public async Task ShouldWaitForDetachedIfAlreadyDetached()
186        {
187            await Page.SetContentAsync("<section id=\"testAttribute\">43543</section>");
188            Assert.Null(await Page.WaitForSelectorAsync("css=div", new() { State = WaitForSelectorState.Detached }));
189        }
190
191        [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should wait for detached")]
192        public async Task ShouldWaitForDetached()
193        {
194            await Page.SetContentAsync("<section id=\"testAttribute\"><div>43543</div></section>");
195            var waitForTask = Page.WaitForSelectorAsync("css=div", new() { State = WaitForSelectorState.Detached });
196            Assert.False(waitForTask.IsCompleted);
197            await Page.WaitForSelectorAsync("css=section");
198            Assert.False(waitForTask.IsCompleted);
199            await Page.EvalOnSelectorAsync("div", "div => div.remove()");
200            await waitForTask;
201        }
202
203        [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should support some fancy xpath")]
204        public async Task ShouldSupportSomeFancyXpath()
205        {
206            await Page.SetContentAsync("<p>red herring</p><p>hello  world  </p>");
207            var waitForXPath = Page.WaitForSelectorAsync("//p[normalize-space(.)=\"hello world\"]");
208            Assert.AreEqual("hello  world  ", await Page.EvaluateAsync<string>("x => x.textContent", await waitForXPath));
209        }
210
211        [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should respect timeout xpath")]
212        public async Task ShouldRespectTimeoutXpath()
213        {
214            var exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(()
215                    => Page.WaitForSelectorAsync("//div", new() { State = WaitForSelectorState.Attached, Timeout = 3000 }));
216
217            StringAssert.Contains("Timeout 3000ms exceeded", exception.Message);
218            StringAssert.Contains("waiting for selector \"//div\"", exception.Message);
219        }
220
221        [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should run in specified frame xpath")]
222        public async Task ShouldRunInSpecifiedFrameXPath()
223        {
224            await FrameUtils.AttachFrameAsync(Page, "frame1", Server.EmptyPage);
225            await FrameUtils.AttachFrameAsync(Page, "frame2", Server.EmptyPage);
226            var frame1 = Page.Frames.First(f => f.Name == "frame1");
227            var frame2 = Page.Frames.First(f => f.Name == "frame2");
228            var waitForXPathPromise = frame2.WaitForSelectorAsync("//div", new() { State = WaitForSelectorState.Attached });
229            await frame1.EvaluateAsync(AddElement, "div");
230            await frame2.EvaluateAsync(AddElement, "div");
231            var eHandle = await waitForXPathPromise;
232            Assert.AreEqual(frame2, await eHandle.OwnerFrameAsync());
233        }
234
235        [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should throw when frame is detached xpath")]
236        public async Task ShouldThrowWhenFrameIsDetachedXPath()
237        {
238            await FrameUtils.AttachFrameAsync(Page, "frame1", Server.EmptyPage);
239            var frame = Page.FirstChildFrame();
240            var waitPromise = frame.WaitForSelectorAsync("//*[@class=\"box\"]");
241            await FrameUtils.DetachFrameAsync(Page, "frame1");
242            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => waitPromise);
243            StringAssert.Contains("Frame was detached", exception.Message);
244        }
245
246        [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should return the element handle xpath")]
247        public async Task ShouldReturnTheElementHandleXPath()
248        {
249            var waitForXPath = Page.WaitForSelectorAsync("//*[@class=\"zombo\"]");
250            await Page.SetContentAsync("<div class='zombo'>anything</div>");
251            Assert.AreEqual("anything", await Page.EvaluateAsync<string>("x => x.textContent", await waitForXPath));
252        }
253
254        [PlaywrightTest("page-wait-for-selector-2.spec.ts", "should allow you to select an element with single slash xpath")]
255        public async Task ShouldAllowYouToSelectAnElementWithSingleSlashXPath()
256        {
257            await Page.SetContentAsync("<div>some text</div>");
258            var waitForXPath = Page.WaitForSelectorAsync("//html/body/div");
259            Assert.AreEqual("some text", await Page.EvaluateAsync<string>("x => x.textContent", await waitForXPath));
260        }
261    }
262}
263
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)