How to use ShouldReportWhenANewPageIsCreatedAndClosed method of Microsoft.Playwright.Tests.BrowserContextPageEventTests class

Best Playwright-dotnet code snippet using Microsoft.Playwright.Tests.BrowserContextPageEventTests.ShouldReportWhenANewPageIsCreatedAndClosed

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

BrowserContextPageEventTests.cs

Source: BrowserContextPageEventTests.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.Collections.Generic;
26using System.Threading.Tasks;
27using Microsoft.Playwright.NUnit;
28using NUnit.Framework;
29
30namespace Microsoft.Playwright.Tests
31{
32    public class BrowserContextPageEventTests : BrowserTestEx
33    {
34        [PlaywrightTest("browsercontext-page-event.spec.ts", "should have url")]
35        public async Task ShouldHaveUrl()
36        {
37            await using var context = await Browser.NewContextAsync();
38            var page = await context.NewPageAsync();
39
40            var (otherPage, _) = await TaskUtils.WhenAll(
41                context.WaitForPageAsync(),
42                page.EvaluateAsync("url => window.open(url)", Server.EmptyPage));
43
44            Assert.AreEqual(Server.EmptyPage, otherPage.Url);
45        }
46
47        [PlaywrightTest("browsercontext-page-event.spec.ts", "should have url after domcontentloaded")]
48        public async Task ShouldHaveUrlAfterDomcontentloaded()
49        {
50            await using var context = await Browser.NewContextAsync();
51            var page = await context.NewPageAsync();
52
53            var (otherPage, _) = await TaskUtils.WhenAll(
54                context.WaitForPageAsync(),
55                page.EvaluateAsync("url => window.open(url)", Server.EmptyPage));
56
57            await otherPage.WaitForLoadStateAsync(LoadState.DOMContentLoaded);
58            Assert.AreEqual(Server.EmptyPage, otherPage.Url);
59        }
60
61        [PlaywrightTest("browsercontext-page-event.spec.ts", "should have about:blank url with domcontentloaded")]
62        public async Task ShouldHaveAboutBlankUrlWithDomcontentloaded()
63        {
64            await using var context = await Browser.NewContextAsync();
65            var page = await context.NewPageAsync();
66
67            var otherPage = await context.RunAndWaitForPageAsync(async () =>
68            {
69                await page.EvaluateAsync("url => window.open(url)", "about:blank");
70            });
71            await otherPage.WaitForLoadStateAsync(LoadState.DOMContentLoaded);
72            Assert.AreEqual("about:blank", otherPage.Url);
73        }
74
75        [PlaywrightTest("browsercontext-page-event.spec.ts", "should have about:blank for empty url with domcontentloaded")]
76        public async Task ShouldHaveAboutBlankUrlForEmptyUrlWithDomcontentloaded()
77        {
78            await using var context = await Browser.NewContextAsync();
79            var page = await context.NewPageAsync();
80
81            var otherPage = await context.RunAndWaitForPageAsync(async () =>
82            {
83                await page.EvaluateAsync("() => window.open()");
84            });
85            await otherPage.WaitForLoadStateAsync(LoadState.DOMContentLoaded);
86            Assert.AreEqual("about:blank", otherPage.Url);
87        }
88
89        [PlaywrightTest("browsercontext-page-event.spec.ts", "should report when a new page is created and closed")]
90        public async Task ShouldReportWhenANewPageIsCreatedAndClosed()
91        {
92            await using var context = await Browser.NewContextAsync();
93            var page = await context.NewPageAsync();
94
95            var otherPage = await context.RunAndWaitForPageAsync(async () =>
96            {
97                await page.EvaluateAsync("url => window.open(url)", Server.CrossProcessPrefix + "/empty.html");
98            });
99
100            StringAssert.Contains(Server.CrossProcessPrefix, otherPage.Url);
101            Assert.AreEqual("Hello world", await otherPage.EvaluateAsync<string>("() => ['Hello', 'world'].join(' ')"));
102            Assert.NotNull(await otherPage.QuerySelectorAsync("body"));
103
104
105            var allPages = context.Pages;
106            CollectionAssert.Contains(allPages, page);
107            CollectionAssert.Contains(allPages, otherPage);
108
109            var closeEventReceived = new TaskCompletionSource<bool>();
110            otherPage.Close += (_, _) => closeEventReceived.TrySetResult(true);
111
112            await otherPage.CloseAsync();
113            await closeEventReceived.Task;
114
115            allPages = context.Pages;
116            CollectionAssert.Contains(allPages, page);
117            CollectionAssert.DoesNotContain(allPages, otherPage);
118        }
119
120        [PlaywrightTest("browsercontext-page-event.spec.ts", "should report initialized pages")]
121        public async Task ShouldReportInitializedPages()
122        {
123            await using var context = await Browser.NewContextAsync();
124            var pageTask = context.WaitForPageAsync();
125            _ = context.NewPageAsync();
126            var newPage = await pageTask;
127            Assert.AreEqual("about:blank", newPage.Url);
128
129            var popupTask = context.WaitForPageAsync();
130            var evaluateTask = newPage.EvaluateAsync("() => window.open('about:blank')");
131            var popup = await popupTask;
132            Assert.AreEqual("about:blank", popup.Url);
133            await evaluateTask;
134        }
135
136        [PlaywrightTest("browsercontext-page-event.spec.ts", "should not crash while redirecting of original request was missed")]
137        public async Task ShouldNotCrashWhileRedirectingOfOriginalRequestWasMissed()
138        {
139            await using var context = await Browser.NewContextAsync();
140            var page = await context.NewPageAsync();
141
142            Server.SetRoute("/one-style.css", context =>
143            {
144                context.Response.Redirect("/one-style.css");
145                return Task.CompletedTask;
146            });
147
148            // Open a new page. Use window.open to connect to the page later.
149            var pageCreatedTask = context.WaitForPageAsync();
150            await TaskUtils.WhenAll(
151                pageCreatedTask,
152                page.EvaluateAsync("url => window.open(url)", Server.Prefix + "/one-style.html"),
153                Server.WaitForRequest("/one-style.css"));
154
155            var newPage = pageCreatedTask.Result;
156
157            await newPage.WaitForLoadStateAsync(LoadState.DOMContentLoaded);
158            Assert.AreEqual(Server.Prefix + "/one-style.html", newPage.Url);
159        }
160
161        [PlaywrightTest("browsercontext-page-event.spec.ts", "should have an opener")]
162        public async Task ShouldHaveAnOpener()
163        {
164            await using var context = await Browser.NewContextAsync();
165            var page = await context.NewPageAsync();
166            await page.GotoAsync(Server.EmptyPage);
167
168            var (popupEvent, _) = await TaskUtils.WhenAll(
169              context.WaitForPageAsync(),
170              page.GotoAsync(Server.Prefix + "/popup/window-open.html"));
171
172            var popup = popupEvent;
173            Assert.AreEqual(Server.Prefix + "/popup/popup.html", popup.Url);
174            Assert.AreEqual(page, await popup.OpenerAsync());
175            Assert.Null(await page.OpenerAsync());
176        }
177
178        [PlaywrightTest("browsercontext-page-event.spec.ts", "should fire page lifecycle events")]
179        public async Task ShouldFirePageLoadStates()
180        {
181            await using var context = await Browser.NewContextAsync();
182            var events = new List<string>();
183
184            context.Page += (_, e) =>
185            {
186                events.Add("CREATED: " + e.Url);
187                e.Close += (sender, _) => events.Add("DESTROYED: " + ((IPage)sender).Url);
188            };
189
190            var page = await context.NewPageAsync();
191            await page.GotoAsync(Server.EmptyPage);
192            await page.CloseAsync();
193            Assert.AreEqual(
194                new List<string>()
195                {
196                    "CREATED: about:blank",
197                    $"DESTROYED: {Server.EmptyPage}"
198                },
199                events);
200        }
201
202        [PlaywrightTest("browsercontext-page-event.spec.ts", "should work with Shift-clicking")]
203        [Skip(SkipAttribute.Targets.Webkit)]
204        public async Task ShouldWorkWithShiftClicking()
205        {
206            // WebKit: Shift+Click does not open a new window.
207            await using var context = await Browser.NewContextAsync();
208            var page = await context.NewPageAsync();
209            await page.GotoAsync(Server.EmptyPage);
210            await page.SetContentAsync("<a href=\"/one-style.html\">yo</a>");
211
212            var popupEventTask = context.WaitForPageAsync();
213            await TaskUtils.WhenAll(
214              popupEventTask,
215              page.ClickAsync("a", new() { Modifiers = new[] { KeyboardModifier.Shift } }));
216
217            Assert.Null(await popupEventTask.Result.OpenerAsync());
218        }
219
220        [PlaywrightTest("browsercontext-page-event.spec.ts", "should report when a new page is created and closed")]
221        [Skip(SkipAttribute.Targets.Webkit, SkipAttribute.Targets.Firefox)]
222        public async Task ShouldWorkWithCtrlClicking()
223        {
224            // Firefox: reports an opener in this case.
225            // WebKit: Ctrl+Click does not open a new tab.
226            await using var context = await Browser.NewContextAsync();
227            var page = await context.NewPageAsync();
228            await page.GotoAsync(Server.EmptyPage);
229            await page.SetContentAsync("<a href=\"/one-style.html\">yo</a>");
230
231            var popupEventTask = context.WaitForPageAsync();
232            await TaskUtils.WhenAll(
233              popupEventTask,
234              page.ClickAsync("a", new() { Modifiers = new[] { TestConstants.IsMacOSX ? KeyboardModifier.Meta : KeyboardModifier.Control } }));
235
236            Assert.Null(await popupEventTask.Result.OpenerAsync());
237        }
238    }
239}
240
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

Trigger ShouldReportWhenANewPageIsCreatedAndClosed code on LambdaTest Cloud Grid

Execute automation tests with ShouldReportWhenANewPageIsCreatedAndClosed on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
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)