How to use ShouldHaveADefaultTimeout method of Microsoft.Playwright.Tests.PageWaitForNavigationTests class

Best Playwright-dotnet code snippet using Microsoft.Playwright.Tests.PageWaitForNavigationTests.ShouldHaveADefaultTimeout

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

PageWaitForNavigationTests.cs

Source: PageWaitForNavigationTests.cs Github

copy
1/*
2 * MIT License
3 *
4 * Copyright (c) 2020 Darío Kondratiuk
5 * Modifications copyright (c) Microsoft Corporation.
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in all
15 * copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 * SOFTWARE.
24 */
25
26using System;
27using System.Collections.Generic;
28using System.Linq;
29using System.Net;
30using System.Threading.Tasks;
31using Microsoft.Playwright.Helpers;
32using Microsoft.Playwright.NUnit;
33using NUnit.Framework;
34
35namespace Microsoft.Playwright.Tests
36{
37    public class PageWaitForNavigationTests : PageTestEx
38    {
39        [PlaywrightTest("page-wait-for-navigation.spec.ts", "should work")]
40        public async Task ShouldWork()
41        {
42            await Page.GotoAsync(Server.EmptyPage);
43            var waitForNavigationResult = Page.WaitForNavigationAsync();
44            await TaskUtils.WhenAll(
45                waitForNavigationResult,
46                Page.EvaluateAsync("url => window.location.href = url", Server.Prefix + "/grid.html")
47            );
48            var response = await waitForNavigationResult;
49            Assert.AreEqual((int)HttpStatusCode.OK, response.Status);
50            StringAssert.Contains("grid.html", response.Url);
51        }
52
53        [PlaywrightTest("page-wait-for-navigation.spec.ts", "should respect timeout")]
54        public async Task ShouldRespectTimeout()
55        {
56            var waitForNavigationResult = Page.WaitForNavigationAsync(new() { UrlString = "**/frame.html", Timeout = 5000 });
57
58            await Page.GotoAsync(Server.EmptyPage);
59
60            var exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(() => waitForNavigationResult);
61
62            StringAssert.Contains("Timeout 5000ms exceeded", exception.Message);
63            StringAssert.Contains("waiting for navigation to \"**/frame.html\" until \"Load\"", exception.Message);
64            StringAssert.Contains($"navigated to \"{Server.EmptyPage}\"", exception.Message);
65        }
66
67        [PlaywrightTest("page-wait-for-navigation.spec.ts", "should work with both domcontentloaded and load")]
68        public async Task NavShouldWorkWithBothDomcontentloadedAndLoad()
69        {
70            var responseCompleted = new TaskCompletionSource<bool>();
71            Server.SetRoute("/one-style.css", _ => responseCompleted.Task);
72
73            var waitForRequestTask = Server.WaitForRequest("/one-style.css");
74            var navigationTask = Page.GotoAsync(Server.Prefix + "/one-style.html");
75            var domContentLoadedTask = Page.WaitForNavigationAsync(new() { WaitUntil = WaitUntilState.DOMContentLoaded });
76
77            bool bothFired = false;
78            var bothFiredTask = TaskUtils.WhenAll(
79                domContentLoadedTask,
80                Page.WaitForNavigationAsync(new() { WaitUntil = WaitUntilState.Load })).ContinueWith(_ => bothFired = true);
81
82            await waitForRequestTask;
83            await domContentLoadedTask;
84            Assert.False(bothFired);
85            responseCompleted.SetResult(true);
86            await bothFiredTask;
87            await navigationTask;
88        }
89
90        [PlaywrightTest("page-wait-for-navigation.spec.ts", "should work with clicking on anchor links")]
91        public async Task ShouldWorkWithClickingOnAnchorLinks()
92        {
93            await Page.GotoAsync(Server.EmptyPage);
94            await Page.SetContentAsync("<a href='#foobar'>foobar</a>");
95            var navigationTask = Page.WaitForNavigationAsync();
96            await TaskUtils.WhenAll(
97                navigationTask,
98                Page.ClickAsync("a")
99            );
100            Assert.Null(await navigationTask);
101            Assert.AreEqual(Server.EmptyPage + "#foobar", Page.Url);
102        }
103
104        [PlaywrightTest("page-wait-for-navigation.spec.ts", "should work with clicking on links which do not commit navigation")]
105        public async Task ShouldWorkWithClickingOnLinksWhichDoNotCommitNavigation()
106        {
107            await Page.GotoAsync(Server.EmptyPage);
108            await Page.SetContentAsync($"<a href='{HttpsServer.Prefix}/empty.html'>foobar</a>");
109            var navigationTask = Page.WaitForNavigationAsync();
110            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => TaskUtils.WhenAll(
111                navigationTask,
112                Page.ClickAsync("a")
113            ));
114            TestUtils.AssertSSLError(exception.Message);
115        }
116
117        [PlaywrightTest("page-wait-for-navigation.spec.ts", "should work with history.pushState()")]
118        public async Task ShouldWorkWithHistoryPushState()
119        {
120            await Page.GotoAsync(Server.EmptyPage);
121            await Page.SetContentAsync(@"
122              <a onclick='javascript:pushState()'>SPA</a>
123              <script>
124                function pushState() { history.pushState({}, '', 'wow.html') }
125              </script>
126            ");
127            var navigationTask = Page.WaitForNavigationAsync();
128            await TaskUtils.WhenAll(
129                navigationTask,
130                Page.ClickAsync("a")
131            );
132            Assert.Null(await navigationTask);
133            Assert.AreEqual(Server.Prefix + "/wow.html", Page.Url);
134        }
135
136        [PlaywrightTest("page-wait-for-navigation.spec.ts", "should work with history.replaceState()")]
137        public async Task ShouldWorkWithHistoryReplaceState()
138        {
139            await Page.GotoAsync(Server.EmptyPage);
140            await Page.SetContentAsync(@"
141              <a onclick='javascript:pushState()'>SPA</a>
142              <script>
143                function pushState() { history.pushState({}, '', 'replaced.html') }
144              </script>
145            ");
146            var navigationTask = Page.WaitForNavigationAsync();
147            await TaskUtils.WhenAll(
148                navigationTask,
149                Page.ClickAsync("a")
150            );
151            Assert.Null(await navigationTask);
152            Assert.AreEqual(Server.Prefix + "/replaced.html", Page.Url);
153        }
154
155        [PlaywrightTest("page-wait-for-navigation.spec.ts", "should work with DOM history.back()/history.forward()")]
156        public async Task ShouldWorkWithDOMHistoryBackAndHistoryForward()
157        {
158            await Page.GotoAsync(Server.EmptyPage);
159            await Page.SetContentAsync(@"
160              <a id=back onclick='javascript:goBack()'>back</a>
161              <a id=forward onclick='javascript:goForward()'>forward</a>
162              <script>
163                function goBack() { history.back(); }
164                function goForward() { history.forward(); }
165                history.pushState({}, '', '/first.html');
166                history.pushState({}, '', '/second.html');
167              </script>
168            ");
169            Assert.AreEqual(Server.Prefix + "/second.html", Page.Url);
170            var navigationTask = Page.WaitForNavigationAsync();
171            await TaskUtils.WhenAll(
172                navigationTask,
173                Page.ClickAsync("a#back")
174            );
175            Assert.Null(await navigationTask);
176            Assert.AreEqual(Server.Prefix + "/first.html", Page.Url);
177            navigationTask = Page.WaitForNavigationAsync();
178            await TaskUtils.WhenAll(
179                navigationTask,
180                Page.ClickAsync("a#forward")
181            );
182            Assert.Null(await navigationTask);
183            Assert.AreEqual(Server.Prefix + "/second.html", Page.Url);
184        }
185
186        [PlaywrightTest("page-wait-for-navigation.spec.ts", "should work when subframe issues window.stop()")]
187        public async Task ShouldWorkWhenSubframeIssuesWindowStop()
188        {
189            //This test is slightly different from the one in PW because of .NET Threads (or thanks to .NET Threads)
190            var framesNavigated = new List<IFrame>();
191            IFrame frame = null;
192
193            var frameAttachedTaskSource = new TaskCompletionSource<IFrame>();
194            Page.FrameAttached += (_, e) =>
195            {
196                frameAttachedTaskSource.SetResult(e);
197            };
198            var frameNavigatedTaskSource = new TaskCompletionSource<bool>();
199            Page.FrameNavigated += (_, e) =>
200            {
201                if (frame != null)
202                {
203                    if (e == frame)
204                    {
205                        frameNavigatedTaskSource.TrySetResult(true);
206                    }
207                }
208                else
209                {
210                    framesNavigated.Add(frame);
211                }
212            };
213
214            Server.SetRoute("/frames/style.css", _ => Task.CompletedTask);
215            var navigationTask = Page.GotoAsync(Server.Prefix + "/frames/one-frame.html");
216
217            frame = await frameAttachedTaskSource.Task;
218
219            if (framesNavigated.Contains(frame))
220            {
221                frameNavigatedTaskSource.TrySetResult(true);
222            }
223
224            await frameNavigatedTaskSource.Task;
225            await TaskUtils.WhenAll(
226                frame.EvaluateAsync("() => window.stop()"),
227                navigationTask
228            );
229        }
230
231        [PlaywrightTest("page-wait-for-navigation.spec.ts", "should work with url match")]
232        public async Task ShouldWorkWithUrlMatch()
233        {
234            IResponse response1 = null;
235            var response1Task = Page.WaitForNavigationAsync(new() { UrlRegex = new("one-style\\.html") }).ContinueWith(t => response1 = t.Result);
236            IResponse response2 = null;
237            var response2Task = Page.WaitForNavigationAsync(new() { UrlRegex = new("\\/frame.html") }).ContinueWith(t => response2 = t.Result);
238            IResponse response3 = null;
239            var response3Task = Page.WaitForNavigationAsync(new()
240            {
241                UrlFunc = (url) =>
242                {
243                    var query = new Uri(url).Query.ParseQueryString();
244                    return query.ContainsKey("foo") && query["foo"] == "bar";
245                }
246            }).ContinueWith(t => response3 = t.Result);
247
248            Assert.Null(response1);
249            Assert.Null(response2);
250            Assert.Null(response3);
251            await Page.GotoAsync(Server.EmptyPage);
252            Assert.Null(response1);
253            Assert.Null(response2);
254            Assert.Null(response3);
255            await Page.GotoAsync(Server.Prefix + "/frame.html");
256            Assert.Null(response1);
257            await response2Task;
258            Assert.NotNull(response2);
259            Assert.Null(response3);
260            await Page.GotoAsync(Server.Prefix + "/one-style.html");
261            await response1Task;
262            Assert.NotNull(response1);
263            Assert.NotNull(response2);
264            Assert.Null(response3);
265            await Page.GotoAsync(Server.Prefix + "/frame.html?foo=bar");
266            await response3Task;
267            Assert.NotNull(response1);
268            Assert.NotNull(response2);
269            Assert.NotNull(response3);
270            await Page.GotoAsync(Server.EmptyPage);
271            Assert.AreEqual(Server.Prefix + "/one-style.html", response1.Url);
272            Assert.AreEqual(Server.Prefix + "/frame.html", response2.Url);
273            Assert.AreEqual(Server.Prefix + "/frame.html?foo=bar", response3.Url);
274        }
275
276        [PlaywrightTest("page-wait-for-navigation.spec.ts", "should work with url match for same document navigations")]
277        public async Task ShouldWorkWithUrlMatchForSameDocumentNavigations()
278        {
279            await Page.GotoAsync(Server.EmptyPage);
280            bool resolved = false;
281            var waitTask = Page.WaitForNavigationAsync(new() { UrlRegex = new("third\\.html") }).ContinueWith(_ => resolved = true);
282
283            Assert.False(resolved);
284
285            await Page.EvaluateAsync("() => history.pushState({}, '', '/first.html')");
286            Assert.False(resolved);
287
288            await Page.EvaluateAsync("() => history.pushState({}, '', '/second.html')");
289            Assert.False(resolved);
290
291            await Page.EvaluateAsync("() => history.pushState({}, '', '/third.html')");
292            await waitTask;
293            Assert.True(resolved);
294        }
295
296        [PlaywrightTest("page-wait-for-navigation.spec.ts", "should work for cross-process navigations")]
297        public async Task ShouldWorkForCrossProcessNavigations()
298        {
299            await Page.GotoAsync(Server.EmptyPage);
300            var waitTask = Page.WaitForNavigationAsync(new() { WaitUntil = WaitUntilState.DOMContentLoaded });
301
302            string url = Server.CrossProcessPrefix + "/empty.html";
303            var gotoTask = Page.GotoAsync(url);
304            var response = await waitTask;
305            Assert.AreEqual(url, response.Url);
306            Assert.AreEqual(url, Page.Url);
307            Assert.AreEqual(url, await Page.EvaluateAsync<string>("document.location.href"));
308            await gotoTask;
309        }
310
311        [PlaywrightTest("page-wait-for-navigation.spec.ts", "should work on frame")]
312        public async Task ShouldWorkOnFrame()
313        {
314            await Page.GotoAsync(Server.Prefix + "/frames/one-frame.html");
315            var frame = Page.Frames.ElementAt(1);
316            var (response, _) = await TaskUtils.WhenAll(
317                frame.WaitForNavigationAsync(),
318                frame.EvaluateAsync("url => window.location.href = url", Server.Prefix + "/grid.html")
319            );
320            Assert.AreEqual((int)HttpStatusCode.OK, response.Status);
321            StringAssert.Contains("grid.html", response.Url);
322            Assert.AreEqual(frame, response.Frame);
323            StringAssert.Contains("/frames/one-frame.html", Page.Url);
324        }
325
326        [PlaywrightTest]
327        [Timeout(45_000)]
328        public async Task ShouldHaveADefaultTimeout()
329        {
330            await Page.GotoAsync(Server.Prefix + "/frames/one-frame.html");
331            await PlaywrightAssert.ThrowsAsync<TimeoutException>(async () => await Page.RunAndWaitForNavigationAsync(() => Task.CompletedTask));
332        }
333
334        [PlaywrightTest]
335        [Timeout(5_000)]
336        public async Task ShouldTakeTimeoutIntoAccount()
337        {
338            await Page.GotoAsync(Server.Prefix + "/frames/one-frame.html");
339            Page.SetDefaultNavigationTimeout(1_000);
340            await PlaywrightAssert.ThrowsAsync<TimeoutException>(async () => await Page.RunAndWaitForNavigationAsync(() => Task.CompletedTask));
341        }
342
343        [PlaywrightTest]
344        public async Task ShouldNotFailWithWaitForEvent()
345        {
346            var failed = false;
347            TaskScheduler.UnobservedTaskException += (_, e) =>
348            {
349                e.SetObserved();
350                failed = true;
351            };
352
353            await Page.GotoAsync(Server.EmptyPage);
354            await Page.MainFrame.SetContentAsync(@$"
355<!DOCTYPE html>
356<html>
357<body>
358<form action='{Server.EmptyPage}'>
359  <input type='text' id='fname' name='fname' value='John'><br>
360  <input type='submit' value='Submit'>
361</form> 
362</body>
363</html>
364");
365            await Task.Delay(TimeSpan.FromSeconds(3));
366            await Page.RunAndWaitForNavigationAsync(async () =>
367            {
368                await Page.ClickAsync("text=Submit");
369                await Task.Delay(TimeSpan.FromSeconds(3));
370            });
371
372            Assert.False(failed);
373        }
374    }
375}
376
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)