How to use ShouldRunInSpecifiedFrame method of Microsoft.Playwright.Tests.PageWaitForSelector1Tests class

Best Playwright-dotnet code snippet using Microsoft.Playwright.Tests.PageWaitForSelector1Tests.ShouldRunInSpecifiedFrame

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

PageWaitForSelector1Tests.cs

Source: PageWaitForSelector1Tests.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 PageWaitForSelector1Tests : PageTestEx
34    {
35        private const string AddElement = "tag => document.body.appendChild(document.createElement(tag))";
36
37        [PlaywrightTest("page-wait-for-selector-1.spec.ts", "should immediately resolve promise if node exists")]
38        public async Task ShouldImmediatelyResolveTaskIfNodeExists()
39        {
40            await Page.GotoAsync(Server.EmptyPage);
41            var frame = Page.MainFrame;
42            await frame.WaitForSelectorAsync("*");
43            await frame.EvaluateAsync(AddElement, "div");
44            await frame.WaitForSelectorAsync("div", new() { State = WaitForSelectorState.Attached });
45        }
46
47        [PlaywrightTest("page-wait-for-selector-1.spec.ts", "elementHandle.waitForSelector should immediately resolve if node exists")]
48        public async Task ElementHandleWaitForSelectorShouldImmediatelyResolveIfNodeExists()
49        {
50            await Page.SetContentAsync("<span>extra</span><div><span>target</span></div>");
51            var div = await Page.QuerySelectorAsync("div");
52            var span = await div.WaitForSelectorAsync("span", new() { State = WaitForSelectorState.Attached });
53            Assert.AreEqual("target", await span.EvaluateAsync<string>("e => e.textContent"));
54        }
55
56        [PlaywrightTest("page-wait-for-selector-1.spec.ts", "elementHandle.waitForSelector should wait")]
57        public async Task ElementHandleWaitForSelectorShouldWait()
58        {
59            await Page.SetContentAsync("<div></div>");
60            var div = await Page.QuerySelectorAsync("div");
61            var task = div.WaitForSelectorAsync("span", new() { State = WaitForSelectorState.Attached });
62            await div.EvaluateAsync("div => div.innerHTML = '<span>target</span>'");
63            var span = await task;
64            Assert.AreEqual("target", await span.EvaluateAsync<string>("e => e.textContent"));
65        }
66
67        [PlaywrightTest("page-wait-for-selector-1.spec.ts", "elementHandle.waitForSelector should timeout")]
68        public async Task ElementHandleWaitForSelectorShouldTimeout()
69        {
70            await Page.SetContentAsync("<div></div>");
71            var div = await Page.QuerySelectorAsync("div");
72            var exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(() => div.WaitForSelectorAsync("span", new() { State = WaitForSelectorState.Attached, Timeout = 100 }));
73            StringAssert.Contains("Timeout 100ms exceeded.", exception.Message);
74        }
75
76        [PlaywrightTest("page-wait-for-selector-1.spec.ts", "elementHandle.waitForSelector should throw on navigation")]
77        public async Task ElementHandleWaitForSelectorShouldThrowOnNavigation()
78        {
79            await Page.SetContentAsync("<div></div>");
80            var div = await Page.QuerySelectorAsync("div");
81            var task = div.WaitForSelectorAsync("span");
82
83            for (int i = 0; i < 10; i++)
84            {
85                await Page.EvaluateAsync("() => 1");
86            }
87
88            await Page.GotoAsync(Server.EmptyPage);
89            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => task);
90            StringAssert.Contains("Error: frame navigated while waiting for selector", exception.Message);
91        }
92
93        [PlaywrightTest("page-wait-for-selector-1.spec.ts", "should work with removed MutationObserver")]
94        public async Task ShouldWorkWithRemovedMutationObserver()
95        {
96            await Page.EvaluateAsync("delete window.MutationObserver");
97            var waitForSelector = Page.WaitForSelectorAsync(".zombo");
98
99            await TaskUtils.WhenAll(
100                waitForSelector,
101                Page.SetContentAsync("<div class='zombo'>anything</div>"));
102
103            Assert.AreEqual("anything", await Page.EvaluateAsync<string>("x => x.textContent", await waitForSelector));
104        }
105
106        [PlaywrightTest("page-wait-for-selector-1.spec.ts", "should resolve promise when node is added")]
107        public async Task ShouldResolveTaskWhenNodeIsAdded()
108        {
109            await Page.GotoAsync(Server.EmptyPage);
110            var frame = Page.MainFrame;
111            var watchdog = frame.WaitForSelectorAsync("div", new() { State = WaitForSelectorState.Attached });
112            await frame.EvaluateAsync(AddElement, "br");
113            await frame.EvaluateAsync(AddElement, "div");
114            var eHandle = await watchdog;
115            var property = await eHandle.GetPropertyAsync("tagName");
116            string tagName = await property.JsonValueAsync<string>();
117            Assert.AreEqual("DIV", tagName);
118        }
119
120        [PlaywrightTest("page-wait-for-selector-1.spec.ts", "should report logs while waiting for visible")]
121        public async Task ShouldReportLogsWhileWaitingForVisible()
122        {
123            await Page.GotoAsync(Server.EmptyPage);
124            var frame = Page.MainFrame;
125            var watchdog = frame.WaitForSelectorAsync("div", new() { Timeout = 5000 });
126
127            await frame.EvaluateAsync(@"() => {
128              const div = document.createElement('div');
129              div.className = 'foo bar';
130              div.id = 'mydiv';
131              div.setAttribute('style', 'display: none');
132              div.setAttribute('foo', '123456789012345678901234567890123456789012345678901234567890');
133              div.textContent = 'abcdefghijklmnopqrstuvwyxzabcdefghijklmnopqrstuvwyxzabcdefghijklmnopqrstuvwyxz';
134              document.body.appendChild(div);
135            }");
136
137            await GiveItTimeToLogAsync(frame);
138
139            await frame.EvaluateAsync("() => document.querySelector('div').remove()");
140            await GiveItTimeToLogAsync(frame);
141
142            await frame.EvaluateAsync(@"() => {
143              const div = document.createElement('div');
144              div.className = 'another';
145              div.style.display = 'none';
146              document.body.appendChild(div);
147            }");
148            await GiveItTimeToLogAsync(frame);
149
150            var exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(() => watchdog);
151
152            StringAssert.Contains("Timeout 5000ms", exception.Message);
153            StringAssert.Contains("waiting for selector \"div\" to be visible", exception.Message);
154            StringAssert.Contains("selector resolved to hidden <div id=\"mydiv\" class=\"foo bar\" foo=\"1234567890123456…>abcdefghijklmnopqrstuvwyxzabcdefghijklmnopqrstuvw…</div>", exception.Message);
155            StringAssert.Contains("selector did not resolve to any element", exception.Message);
156            StringAssert.Contains("selector resolved to hidden <div class=\"another\"></div>", exception.Message);
157        }
158
159        [PlaywrightTest("page-wait-for-selector-1.spec.ts", "should report logs while waiting for hidden")]
160        public async Task ShouldReportLogsWhileWaitingForHidden()
161        {
162            await Page.GotoAsync(Server.EmptyPage);
163            var frame = Page.MainFrame;
164
165            await frame.EvaluateAsync(@"() => {
166              const div = document.createElement('div');
167              div.className = 'foo bar';
168              div.id = 'mydiv';
169              div.textContent = 'hello';
170              document.body.appendChild(div);
171            }");
172
173            var watchdog = frame.WaitForSelectorAsync("div", new() { State = WaitForSelectorState.Hidden, Timeout = 5000 });
174            await GiveItTimeToLogAsync(frame);
175
176            await frame.EvaluateAsync(@"() => {
177              document.querySelector('div').remove();
178              const div = document.createElement('div');
179              div.className = 'another';
180              div.textContent = 'hello';
181              document.body.appendChild(div);
182            }");
183            await GiveItTimeToLogAsync(frame);
184
185            var exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(() => watchdog);
186
187            StringAssert.Contains("Timeout 5000ms", exception.Message);
188            StringAssert.Contains("waiting for selector \"div\" to be hidden", exception.Message);
189            StringAssert.Contains("selector resolved to visible <div id=\"mydiv\" class=\"foo bar\">hello</div>", exception.Message);
190            StringAssert.Contains("selector resolved to visible <div class=\"another\">hello</div>", exception.Message);
191        }
192
193        [PlaywrightTest("page-wait-for-selector-1.spec.ts", "should resolve promise when node is added in shadow dom")]
194        public async Task ShouldResolvePromiseWhenNodeIsAddedInShadowDom()
195        {
196            await Page.GotoAsync(Server.EmptyPage);
197            var watchdog = Page.WaitForSelectorAsync("span");
198
199            await Page.EvaluateAsync(@"() => {
200              const div = document.createElement('div');
201              div.attachShadow({mode: 'open'});
202              document.body.appendChild(div);
203            }");
204
205            await Page.EvaluateAsync(@"() => new Promise(f => setTimeout(f, 100))");
206
207            await Page.EvaluateAsync(@"() => {
208              const span = document.createElement('span');
209              span.textContent = 'Hello from shadow';
210              document.querySelector('div').shadowRoot.appendChild(span);
211            }");
212
213            var handle = await watchdog;
214
215            Assert.AreEqual("Hello from shadow", await handle.EvaluateAsync<string>("e => e.textContent"));
216        }
217
218        [PlaywrightTest("page-wait-for-selector-1.spec.ts", "should work when node is added through innerHTML")]
219        public async Task ShouldWorkWhenNodeIsAddedThroughInnerHTML()
220        {
221            await Page.GotoAsync(Server.EmptyPage);
222            var watchdog = Page.WaitForSelectorAsync("h3 div", new() { State = WaitForSelectorState.Attached });
223            await Page.EvaluateAsync(AddElement, "span");
224            await Page.EvaluateAsync("document.querySelector('span').innerHTML = '<h3><div></div></h3>'");
225            await watchdog;
226        }
227
228        [PlaywrightTest("page-wait-for-selector-1.spec.ts", "Page.$ waitFor is shortcut for main frame")]
229        public async Task PageWaitForSelectorAsyncIsShortcutForMainFrame()
230        {
231            await Page.GotoAsync(Server.EmptyPage);
232            await FrameUtils.AttachFrameAsync(Page, "frame1", Server.EmptyPage);
233            var otherFrame = Page.FirstChildFrame();
234            var watchdog = Page.WaitForSelectorAsync("div", new() { State = WaitForSelectorState.Attached });
235            await otherFrame.EvaluateAsync(AddElement, "div");
236            await Page.EvaluateAsync(AddElement, "div");
237            var eHandle = await watchdog;
238            Assert.AreEqual(Page.MainFrame, await eHandle.OwnerFrameAsync());
239        }
240
241        [PlaywrightTest("page-wait-for-selector-1.spec.ts", "should run in specified frame")]
242        public async Task ShouldRunInSpecifiedFrame()
243        {
244            await FrameUtils.AttachFrameAsync(Page, "frame1", Server.EmptyPage);
245            await FrameUtils.AttachFrameAsync(Page, "frame2", Server.EmptyPage);
246            var frame1 = Page.FirstChildFrame();
247            var frame2 = Page.Frames.ElementAt(2);
248            var waitForSelectorPromise = frame2.WaitForSelectorAsync("div", new() { State = WaitForSelectorState.Attached });
249            await frame1.EvaluateAsync(AddElement, "div");
250            await frame2.EvaluateAsync(AddElement, "div");
251            var eHandle = await waitForSelectorPromise;
252            Assert.AreEqual(frame2, await eHandle.OwnerFrameAsync());
253        }
254
255        [PlaywrightTest("page-wait-for-selector-1.spec.ts", "should throw when frame is detached")]
256        public async Task ShouldThrowWhenFrameIsDetached()
257        {
258            await FrameUtils.AttachFrameAsync(Page, "frame1", Server.EmptyPage);
259            var frame = Page.FirstChildFrame();
260            var waitTask = frame.WaitForSelectorAsync(".box").ContinueWith(task => task.Exception?.InnerException);
261            await FrameUtils.DetachFrameAsync(Page, "frame1");
262            var waitException = await waitTask;
263            Assert.NotNull(waitException);
264            StringAssert.Contains("Frame was detached", waitException.Message);
265        }
266
267        private async Task GiveItTimeToLogAsync(IFrame frame)
268        {
269            await frame.EvaluateAsync("() => new Promise(f => requestAnimationFrame(() => requestAnimationFrame(f)))");
270            await frame.EvaluateAsync("() => new Promise(f => requestAnimationFrame(() => requestAnimationFrame(f)))");
271        }
272    }
273}
274
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)