How to use ShouldReturnNullIfParentPageHasBeenClosed method of Microsoft.Playwright.Tests.PageBasicTests class

Best Playwright-dotnet code snippet using Microsoft.Playwright.Tests.PageBasicTests.ShouldReturnNullIfParentPageHasBeenClosed

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

PageBasicTests.cs

Source: PageBasicTests.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.Text.RegularExpressions;
28using System.Threading.Tasks;
29using NUnit.Framework;
30
31namespace Microsoft.Playwright.Tests
32{
33    public class PageBasicTests : PageTestEx
34    {
35        [PlaywrightTest("page-basic.spec.ts", "should reject all promises when page is closed")]
36        public async Task ShouldRejectAllPromisesWhenPageIsClosed()
37        {
38            var newPage = await Context.NewPageAsync();
39            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => TaskUtils.WhenAll(
40                newPage.EvaluateAsync<string>("() => new Promise(r => { })"),
41                newPage.CloseAsync()
42            ));
43            StringAssert.Contains("Target closed", exception.Message);
44        }
45
46        [PlaywrightTest("page-basic.spec.ts", "async stacks should work")]
47        public async Task AsyncStacksShouldWork()
48        {
49            Server.SetRoute("/empty.html", context =>
50            {
51                context.Abort();
52                return Task.CompletedTask;
53            });
54            Exception exception = null;
55            try
56            {
57                await Page.GotoAsync(Server.EmptyPage);
58            }
59            catch (Exception ex)
60            {
61                exception = ex;
62            }
63            StringAssert.Contains(nameof(PageBasicTests) + ".cs", exception.StackTrace);
64        }
65
66        [PlaywrightTest("page-basic.spec.ts", "Page.press should work")]
67        public async Task PagePressShouldWork()
68        {
69            await Page.GotoAsync(Server.Prefix + "/input/textarea.html");
70            await Page.PressAsync("textarea", "a");
71            Assert.AreEqual("a", await Page.EvaluateAsync<string>("() => document.querySelector('textarea').value"));
72        }
73
74        [PlaywrightTest("page-basic.spec.ts", "Frame.press should work")]
75        public async Task FramePressShouldWork()
76        {
77            await Page.SetContentAsync($"<iframe name =inner src=\"{Server.Prefix}/input/textarea.html\"></iframe>");
78            var frame = Page.Frames.Single(f => f.Name == "inner");
79            await frame.PressAsync("textarea", "a");
80            Assert.AreEqual("a", await frame.EvaluateAsync<string>("() => document.querySelector('textarea').value"));
81        }
82
83        [PlaywrightTest("page-basic.spec.ts", "page.frame should respect name")]
84        public async Task ShouldReturnTheCorrectBrowserInstance()
85        {
86            await Page.SetContentAsync("<iframe name=target></iframe>");
87            Assert.Null(Page.Frames.FirstOrDefault(f => f.Name == "bogus"));
88            var frame = Page.Frames.FirstOrDefault(f => f.Name == "target");
89            Assert.AreEqual(Page.MainFrame.ChildFrames.First(), frame);
90        }
91
92        [PlaywrightTest("page-basic.spec.ts", "page.frame should respect url")]
93        public async Task ShouldRespectUrl()
94        {
95            await Page.SetContentAsync($"<iframe src=\"{Server.EmptyPage}\"></iframe>");
96            Assert.Null(Page.Frames.FirstOrDefault(f => f.Name == "bogus"));
97            var frame = Page.Frames.FirstOrDefault(f => f.Url.Contains("empty"));
98            Assert.AreEqual(Page.MainFrame.ChildFrames.First(), frame);
99        }
100
101        [PlaywrightTest("page-basic.spec.ts", "should provide access to the opener page")]
102        public async Task ShouldProvideAccessToTheOpenerPage()
103        {
104            var (popupEvent, _) = await TaskUtils.WhenAll(
105                Page.WaitForPopupAsync(),
106                Page.EvaluateAsync("() => window.open('about:blank')")
107            );
108            var opener = await popupEvent.OpenerAsync();
109            Assert.AreEqual(Page, opener);
110        }
111
112        [PlaywrightTest("page-basic.spec.ts", "should return null if parent page has been closed")]
113        public async Task ShouldReturnNullIfParentPageHasBeenClosed()
114        {
115            var (popupEvent, _) = await TaskUtils.WhenAll(
116                Page.WaitForPopupAsync(),
117                Page.EvaluateAsync("() => window.open('about:blank')")
118            );
119            await Page.CloseAsync();
120            var opener = await popupEvent.OpenerAsync();
121            Assert.Null(opener);
122        }
123
124        [PlaywrightTest("page-basic.spec.ts", "should return the page title")]
125        public async Task ShouldReturnThePageTitle()
126        {
127            await Page.GotoAsync(Server.Prefix + "/title.html");
128            Assert.AreEqual("Woof-Woof", await Page.TitleAsync());
129        }
130
131        [PlaywrightTest("page-basic.spec.ts", "page.url should work")]
132        public async Task PageUrlShouldWork()
133        {
134            Assert.AreEqual("about:blank", Page.Url);
135            await Page.GotoAsync(Server.EmptyPage);
136            Assert.AreEqual(Server.EmptyPage, Page.Url);
137        }
138
139        [PlaywrightTest("page-basic.spec.ts", "should include hashes")]
140        public async Task ShouldIncludeHashes()
141        {
142            await Page.GotoAsync(Server.EmptyPage + "#hash");
143            Assert.AreEqual(Server.EmptyPage + "#hash", Page.Url);
144            await Page.EvaluateAsync("() => window.location.hash = 'dynamic'");
145            Assert.AreEqual(Server.EmptyPage + "#dynamic", Page.Url);
146        }
147
148        [PlaywrightTest("page-basic.spec.ts", "should fail with error upon disconnect")]
149        public async Task ShouldFailWithErrorUponDisconnect()
150        {
151            var task = Page.WaitForDownloadAsync();
152            await Page.CloseAsync();
153            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => task);
154            StringAssert.Contains("Page closed", exception.Message);
155        }
156
157        [PlaywrightTest("page-basic.spec.ts", "should have sane user agent")]
158        public async Task ShouldHaveASaneUserAgent()
159        {
160            string userAgent = await Page.EvaluateAsync<string>("() => navigator.userAgent");
161            string[] parts = Regex.Split(userAgent, "[()]").Select(t => t.Trim()).ToArray();
162
163            Assert.AreEqual("Mozilla/5.0", parts[0]);
164
165            if (TestConstants.IsFirefox)
166            {
167                string[] engineBrowser = parts[2].Split(' ');
168                Assert.That(engineBrowser[0], Does.StartWith("Gecko"));
169                Assert.That(engineBrowser[1], Does.StartWith("Firefox"));
170            }
171            else
172            {
173                Assert.That(parts[2], Does.StartWith("AppleWebKit/"));
174                Assert.AreEqual("KHTML, like Gecko", parts[3]);
175                string[] engineBrowser = parts[4].Split(' ');
176                Assert.That(engineBrowser[1], Does.StartWith("Safari/"));
177
178                if (TestConstants.IsChromium)
179                {
180                    StringAssert.Contains("Chrome/", engineBrowser[0]);
181                }
182                else
183                {
184                    Assert.That(engineBrowser[0], Does.StartWith("Version"));
185                }
186            }
187        }
188
189        [PlaywrightTest("page-basic.spec.ts", "should work with window.close")]
190        public async Task ShouldWorkWithWindowClose()
191        {
192            var newPageTask = Page.WaitForPopupAsync();
193            await Page.EvaluateAsync<string>("() => window['newPage'] = window.open('about:blank')");
194            var newPage = await newPageTask;
195            var closedTsc = new TaskCompletionSource<bool>();
196            newPage.Close += (_, _) => closedTsc.SetResult(true);
197            await Page.EvaluateAsync<string>("() => window['newPage'].close()");
198            await closedTsc.Task;
199        }
200
201        [PlaywrightTest("page-basic.spec.ts", "should work with page.close")]
202        public async Task ShouldWorkWithPageClose()
203        {
204            var newPage = await Context.NewPageAsync();
205            var closedTsc = new TaskCompletionSource<bool>();
206            newPage.Close += (_, _) => closedTsc.SetResult(true);
207            await newPage.CloseAsync();
208            await closedTsc.Task;
209        }
210
211        [PlaywrightTest("page-basic.spec.ts", "should fire load when expected")]
212        public Task ShouldFireLoadWhenExpected()
213        {
214            var loadEvent = new TaskCompletionSource<bool>();
215            Page.Load += (_, _) => loadEvent.TrySetResult(true);
216
217            return TaskUtils.WhenAll(
218                loadEvent.Task,
219                Page.GotoAsync("about:blank")
220            );
221        }
222
223        [PlaywrightTest("page-basic.spec.ts", "should fire domcontentloaded when expected")]
224        public async Task ShouldFireDOMcontentloadedWhenExpected()
225        {
226            var task = Page.GotoAsync("about:blank");
227            await Page.WaitForLoadStateAsync(LoadState.DOMContentLoaded);
228            await task;
229        }
230
231        [PlaywrightTest("page-basic.spec.ts", "should set the page close state")]
232        public async Task ShouldSetThePageCloseState()
233        {
234            var newPage = await Context.NewPageAsync();
235            Assert.False(newPage.IsClosed);
236            await newPage.CloseAsync();
237            Assert.True(newPage.IsClosed);
238        }
239
240        [PlaywrightTest("page-basic.spec.ts", "should terminate network waiters")]
241        public async Task ShouldTerminateNetworkWaiters()
242        {
243            var newPage = await Context.NewPageAsync();
244            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => TaskUtils.WhenAll(
245                newPage.WaitForRequestAsync(Server.EmptyPage),
246                newPage.WaitForResponseAsync(Server.EmptyPage),
247                newPage.CloseAsync()
248            ));
249            for (int i = 0; i < 2; i++)
250            {
251                string message = exception.Message;
252                StringAssert.Contains("Page closed", message);
253                Assert.That(message, Does.Not.Contain("Timeout"));
254            }
255        }
256
257        [PlaywrightTest("page-basic.spec.ts", "should be callable twice")]
258        public async Task ShouldBeCallableTwice()
259        {
260            var newPage = await Context.NewPageAsync();
261            await TaskUtils.WhenAll(
262                newPage.CloseAsync(),
263                newPage.CloseAsync());
264
265            await newPage.CloseAsync();
266        }
267
268        [PlaywrightTest("page-basic.spec.ts", "should not be visible in context.pages")]
269        public async Task ShouldNotBeVisibleInContextPages()
270        {
271            var newPage = await Context.NewPageAsync();
272            CollectionAssert.Contains(Context.Pages, newPage);
273            await newPage.CloseAsync();
274            CollectionAssert.DoesNotContain(Context.Pages, newPage);
275        }
276
277        [PlaywrightTest("page-basic.spec.ts", "")]
278        public async Task DragAndDropShouldWork()
279        {
280            var page = await Context.NewPageAsync();
281            await page.GotoAsync(Server.Prefix + "/drag-n-drop.html");
282            await page.DragAndDropAsync("#source", "#target");
283            Assert.IsTrue(await page.EvalOnSelectorAsync<bool>("#target", "target => target.contains(document.querySelector('#source'))"));
284        }
285
286        [PlaywrightTest("page-drag.spec.ts", "")]
287        public async Task DragAndDropWithLocatorsShouldWork()
288        {
289            var page = await Context.NewPageAsync();
290            await page.GotoAsync(Server.Prefix + "/drag-n-drop.html");
291            await page.Locator("#source").DragToAsync(page.Locator("#target"));
292            Assert.IsTrue(await page.EvalOnSelectorAsync<bool>("#target", "target => target.contains(document.querySelector('#source'))"));
293        }
294    }
295}
296
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)