How to use ShouldNavigateToEmptyPageWithDOMContentLoaded method of PuppeteerSharp.Tests.NavigationTests.PageGotoTests class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Tests.NavigationTests.PageGotoTests.ShouldNavigateToEmptyPageWithDOMContentLoaded

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

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

PageGotoTests.cs

Source: PageGotoTests.cs Github

copy
1using Microsoft.AspNetCore.Http;
2using System;
3using System.Collections.Generic;
4using System.IO;
5using System.Net;
6using System.Threading.Tasks;
7using Xunit;
8using Xunit.Abstractions;
9using PuppeteerSharp.Helpers;
10using PuppeteerSharp.Tests.Attributes;
11using PuppeteerSharp.Xunit;
12
13namespace PuppeteerSharp.Tests.NavigationTests
14{
15    [Collection(TestConstants.TestFixtureCollectionName)]
16    public class PageGotoTests : PuppeteerPageBaseTest
17    {
18        public PageGotoTests(ITestOutputHelper output) : base(output)
19        {
20        }
21
22        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should work")]
23        [PuppeteerFact]
24        public async Task ShouldWork()
25        {
26            await Page.GoToAsync(TestConstants.EmptyPage);
27            Assert.Equal(TestConstants.EmptyPage, Page.Url);
28        }
29
30        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should work with anchor navigation")]
31        [SkipBrowserFact(skipFirefox: true)]
32        public async Task ShouldWorkWithAnchorNavigation()
33        {
34            await Page.GoToAsync(TestConstants.EmptyPage);
35            Assert.Equal(TestConstants.EmptyPage, Page.Url);
36            await Page.GoToAsync($"{TestConstants.EmptyPage}#foo");
37            Assert.Equal($"{TestConstants.EmptyPage}#foo", Page.Url);
38            await Page.GoToAsync($"{TestConstants.EmptyPage}#bar");
39            Assert.Equal($"{TestConstants.EmptyPage}#bar", Page.Url);
40        }
41
42        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should work with redirects")]
43        [PuppeteerFact]
44        public async Task ShouldWorkWithRedirects()
45        {
46            Server.SetRedirect("/redirect/1.html", "/redirect/2.html");
47            Server.SetRedirect("/redirect/2.html", "/empty.html");
48
49            await Page.GoToAsync(TestConstants.ServerUrl + "/redirect/1.html");
50            await Page.GoToAsync(TestConstants.EmptyPage);
51        }
52
53        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should navigate to about:blank")]
54        [PuppeteerFact]
55        public async Task ShouldNavigateToAboutBlank()
56        {
57            var response = await Page.GoToAsync(TestConstants.AboutBlank);
58            Assert.Null(response);
59        }
60
61        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should return response when page changes its URL after load")]
62        [PuppeteerFact]
63        public async Task ShouldReturnResponseWhenPageChangesItsURLAfterLoad()
64        {
65            var response = await Page.GoToAsync(TestConstants.ServerUrl + "/historyapi.html");
66            Assert.Equal(HttpStatusCode.OK, response.Status);
67        }
68
69        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should work with subframes return 204")]
70        [SkipBrowserFact(skipFirefox: true)]
71        public async Task ShouldWorkWithSubframesReturn204()
72        {
73            Server.SetRoute("/frames/frame.html", context =>
74            {
75                context.Response.StatusCode = 204;
76                return Task.CompletedTask;
77            });
78            await Page.GoToAsync(TestConstants.ServerUrl + "/frames/one-frame.html");
79        }
80
81        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should fail when server returns 204")]
82        [SkipBrowserFact(skipFirefox: true)]
83        public async Task ShouldFailWhenServerReturns204()
84        {
85            Server.SetRoute("/empty.html", context =>
86            {
87                context.Response.StatusCode = 204;
88                return Task.CompletedTask;
89            });
90            var exception = await Assert.ThrowsAnyAsync<PuppeteerException>(
91                () => Page.GoToAsync(TestConstants.EmptyPage));
92
93            if (TestConstants.IsChrome)
94            {
95                Assert.Contains("net::ERR_ABORTED", exception.Message);
96            }
97            else
98            {
99                Assert.Contains("NS_BINDING_ABORTED", exception.Message);
100            }
101        }
102
103        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should navigate to empty page with domcontentloaded")]
104        [PuppeteerFact]
105        public async Task ShouldNavigateToEmptyPageWithDOMContentLoaded()
106        {
107            var response = await Page.GoToAsync(TestConstants.EmptyPage, waitUntil: new[]
108            {
109                WaitUntilNavigation.DOMContentLoaded
110            });
111            Assert.Equal(HttpStatusCode.OK, response.Status);
112            Assert.Null(response.SecurityDetails);
113        }
114
115        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should work when page calls history API in beforeunload")]
116        [PuppeteerFact]
117        public async Task ShouldWorkWhenPageCallsHistoryAPIInBeforeunload()
118        {
119            await Page.GoToAsync(TestConstants.EmptyPage);
120            await Page.EvaluateFunctionAsync(@"() =>
121            {
122                window.addEventListener('beforeunload', () => history.replaceState(null, 'initial', window.location.href), false);
123            }");
124            var response = await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html");
125            Assert.Equal(HttpStatusCode.OK, response.Status);
126        }
127
128        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should navigate to empty page with networkidle0")]
129        [SkipBrowserFact(skipFirefox: true)]
130        public async Task ShouldNavigateToEmptyPageWithNetworkidle0()
131        {
132            var response = await Page.GoToAsync(TestConstants.EmptyPage, new NavigationOptions { WaitUntil = new[] { WaitUntilNavigation.Networkidle0 } });
133            Assert.Equal(HttpStatusCode.OK, response.Status);
134        }
135
136        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should navigate to empty page with networkidle2")]
137        [SkipBrowserFact(skipFirefox: true)]
138        public async Task ShouldNavigateToEmptyPageWithNetworkidle2()
139        {
140            var response = await Page.GoToAsync(TestConstants.EmptyPage, new NavigationOptions { WaitUntil = new[] { WaitUntilNavigation.Networkidle2 } });
141            Assert.Equal(HttpStatusCode.OK, response.Status);
142        }
143
144        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should fail when navigating to bad url")]
145        [SkipBrowserFact(skipFirefox: true)]
146        public async Task ShouldFailWhenNavigatingToBadUrl()
147        {
148            var exception = await Assert.ThrowsAnyAsync<Exception>(async () => await Page.GoToAsync("asdfasdf"));
149
150            if (TestConstants.IsChrome)
151            {
152                Assert.Contains("Cannot navigate to invalid URL", exception.Message);
153            }
154            else
155            {
156                Assert.Contains("Invalid url", exception.Message);
157            }
158        }
159
160        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should fail when navigating to bad SSL")]
161        [SkipBrowserFact(skipFirefox: true)]
162        public async Task ShouldFailWhenNavigatingToBadSSL()
163        {
164            Page.Request += (_, e) => Assert.NotNull(e.Request);
165            Page.RequestFinished += (_, e) => Assert.NotNull(e.Request);
166            Page.RequestFailed += (_, e) => Assert.NotNull(e.Request);
167
168            var exception = await Assert.ThrowsAnyAsync<Exception>(async () => await Page.GoToAsync(TestConstants.HttpsPrefix + "/empty.html"));
169
170            if (TestConstants.IsChrome)
171            {
172                Assert.Contains("net::ERR_CERT_AUTHORITY_INVALID", exception.Message);
173            }
174            else
175            {
176                Assert.Contains("SSL_ERROR_UNKNOWN", exception.Message);
177            }
178        }
179
180        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should fail when navigating to bad SSL after redirects")]
181        [PuppeteerFact]
182        public async Task ShouldFailWhenNavigatingToBadSSLAfterRedirects()
183        {
184            var exception = await Assert.ThrowsAnyAsync<Exception>(async () => await Page.GoToAsync(TestConstants.HttpsPrefix + "/redirect/2.html"));
185
186            if (TestConstants.IsChrome)
187            {
188                Assert.Contains("net::ERR_CERT_AUTHORITY_INVALID", exception.Message);
189            }
190            else
191            {
192                Assert.Contains("SSL_ERROR_UNKNOWN", exception.Message);
193            }
194        }
195
196        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should fail when main resources failed to load")]
197        [PuppeteerFact]
198        public async Task ShouldFailWhenMainResourcesFailedToLoad()
199        {
200            var exception = await Assert.ThrowsAnyAsync<Exception>(async () => await Page.GoToAsync("http://localhost:44123/non-existing-url"));
201
202            if (TestConstants.IsChrome)
203            {
204                Assert.Contains("net::ERR_CONNECTION_REFUSED", exception.Message);
205            }
206            else
207            {
208                Assert.Contains("NS_ERROR_CONNECTION_REFUSED", exception.Message);
209            }
210        }
211
212        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should fail when exceeding maximum navigation timeout")]
213        [PuppeteerFact]
214        public async Task ShouldFailWhenExceedingMaximumNavigationTimeout()
215        {
216            Server.SetRoute("/empty.html", _ => Task.Delay(-1));
217
218            var exception = await Assert.ThrowsAnyAsync<Exception>(async ()
219                => await Page.GoToAsync(TestConstants.EmptyPage, new NavigationOptions { Timeout = 1 }));
220            Assert.Contains("Timeout of 1 ms exceeded", exception.Message);
221        }
222
223        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should fail when exceeding default maximum navigation timeout")]
224        [PuppeteerFact]
225        public async Task ShouldFailWhenExceedingDefaultMaximumNavigationTimeout()
226        {
227            Server.SetRoute("/empty.html", _ => Task.Delay(-1));
228
229            Page.DefaultNavigationTimeout = 1;
230            var exception = await Assert.ThrowsAnyAsync<Exception>(async () => await Page.GoToAsync(TestConstants.EmptyPage));
231            Assert.Contains("Timeout of 1 ms exceeded", exception.Message);
232        }
233
234        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should fail when exceeding default maximum timeout")]
235        [PuppeteerFact]
236        public async Task ShouldFailWhenExceedingDefaultMaximumTimeout()
237        {
238            // Hang for request to the empty.html
239            Server.SetRoute("/empty.html", _ => Task.Delay(-1));
240            Page.DefaultTimeout = 1;
241            var exception = await Assert.ThrowsAnyAsync<Exception>(async () => await Page.GoToAsync(TestConstants.EmptyPage));
242            Assert.Contains("Timeout of 1 ms exceeded", exception.Message);
243        }
244
245        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should prioritize default navigation timeout over default timeout")]
246        [PuppeteerFact]
247        public async Task ShouldPrioritizeDefaultNavigationTimeoutOverDefaultTimeout()
248        {
249            // Hang for request to the empty.html
250            Server.SetRoute("/empty.html", _ => Task.Delay(-1));
251            Page.DefaultTimeout = 0;
252            Page.DefaultNavigationTimeout = 1;
253            var exception = await Assert.ThrowsAnyAsync<Exception>(async () => await Page.GoToAsync(TestConstants.EmptyPage));
254            Assert.Contains("Timeout of 1 ms exceeded", exception.Message);
255        }
256
257        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should disable timeout when its set to 0")]
258        [PuppeteerFact]
259        public async Task ShouldDisableTimeoutWhenItsSetTo0()
260        {
261            var loaded = false;
262            void OnLoad(object sender, EventArgs e)
263            {
264                loaded = true;
265                Page.Load -= OnLoad;
266            }
267            Page.Load += OnLoad;
268
269            await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html", new NavigationOptions { Timeout = 0, WaitUntil = new[] { WaitUntilNavigation.Load } });
270            Assert.True(loaded);
271        }
272
273        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should work when navigating to valid url")]
274        [PuppeteerFact]
275        public async Task ShouldWorkWhenNavigatingToValidUrl()
276        {
277            var response = await Page.GoToAsync(TestConstants.EmptyPage);
278            Assert.Equal(HttpStatusCode.OK, response.Status);
279        }
280
281        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should work when navigating to data url")]
282        [SkipBrowserFact(skipFirefox: true)]
283        public async Task ShouldWorkWhenNavigatingToDataUrl()
284        {
285            var response = await Page.GoToAsync("data:text/html,hello");
286            Assert.Equal(HttpStatusCode.OK, response.Status);
287        }
288
289        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should work when navigating to 404")]
290        [PuppeteerFact]
291        public async Task ShouldWorkWhenNavigatingTo404()
292        {
293            var response = await Page.GoToAsync(TestConstants.ServerUrl + "/not-found");
294            Assert.Equal(HttpStatusCode.NotFound, response.Status);
295        }
296
297        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should return last response in redirect chain")]
298        [PuppeteerFact]
299        public async Task ShouldReturnLastResponseInRedirectChain()
300        {
301            Server.SetRedirect("/redirect/1.html", "/redirect/2.html");
302            Server.SetRedirect("/redirect/2.html", "/redirect/3.html");
303            Server.SetRedirect("/redirect/3.html", TestConstants.EmptyPage);
304
305            var response = await Page.GoToAsync(TestConstants.ServerUrl + "/redirect/1.html");
306            Assert.Equal(HttpStatusCode.OK, response.Status);
307            Assert.Equal(TestConstants.EmptyPage, response.Url);
308        }
309
310        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should wait for network idle to succeed navigation")]
311        [SkipBrowserFact(skipFirefox: true)]
312        public async Task ShouldWaitForNetworkIdleToSucceedNavigation()
313        {
314            var responses = new List<TaskCompletionSource<Func<HttpResponse, Task>>>();
315            var fetches = new Dictionary<string, TaskCompletionSource<bool>>();
316            foreach (var url in new[] {
317                "/fetch-request-a.js",
318                "/fetch-request-b.js",
319                "/fetch-request-c.js",
320                "/fetch-request-d.js" })
321            {
322                fetches[url] = new TaskCompletionSource<bool>();
323                Server.SetRoute(url, async context =>
324                {
325                    var taskCompletion = new TaskCompletionSource<Func<HttpResponse, Task>>();
326                    responses.Add(taskCompletion);
327                    fetches[context.Request.Path].SetResult(true);
328                    var actionResponse = await taskCompletion.Task;
329                    await actionResponse(context.Response).WithTimeout();
330                });
331            }
332
333            var initialFetchResourcesRequested = Task.WhenAll(
334                Server.WaitForRequest("/fetch-request-a.js"),
335                Server.WaitForRequest("/fetch-request-b.js"),
336                Server.WaitForRequest("/fetch-request-c.js")
337            );
338            var secondFetchResourceRequested = Server.WaitForRequest("/fetch-request-d.js");
339
340            var pageLoaded = new TaskCompletionSource<bool>();
341            void WaitPageLoad(object sender, EventArgs e)
342            {
343                pageLoaded.SetResult(true);
344                Page.Load -= WaitPageLoad;
345            }
346            Page.Load += WaitPageLoad;
347
348            var navigationFinished = false;
349            var navigationTask = Page.GoToAsync(TestConstants.ServerUrl + "/networkidle.html",
350                new NavigationOptions { WaitUntil = new[] { WaitUntilNavigation.Networkidle0 } })
351                .ContinueWith(res =>
352                {
353                    navigationFinished = true;
354                    return res.Result;
355                });
356
357            await pageLoaded.Task.WithTimeout();
358
359            Assert.False(navigationFinished);
360
361            await initialFetchResourcesRequested.WithTimeout();
362
363            Assert.False(navigationFinished);
364
365            await Task.WhenAll(
366                fetches["/fetch-request-a.js"].Task,
367                fetches["/fetch-request-b.js"].Task,
368                fetches["/fetch-request-c.js"].Task).WithTimeout();
369
370            foreach (var actionResponse in responses)
371            {
372                actionResponse.SetResult(response =>
373                {
374                    response.StatusCode = 404;
375                    return response.WriteAsync("File not found");
376                });
377            }
378
379            responses.Clear();
380
381            await secondFetchResourceRequested.WithTimeout();
382
383            Assert.False(navigationFinished);
384
385            await fetches["/fetch-request-d.js"].Task.WithTimeout();
386
387            foreach (var actionResponse in responses)
388            {
389                actionResponse.SetResult(response =>
390                {
391                    response.StatusCode = 404;
392                    return response.WriteAsync("File not found");
393                });
394            }
395
396            var navigationResponse = await navigationTask;
397            Assert.Equal(HttpStatusCode.OK, navigationResponse.Status);
398        }
399
400        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should navigate to dataURL and fire dataURL requests")]
401        [SkipBrowserFact(skipFirefox: true)]
402        public async Task ShouldNavigateToDataURLAndFireDataURLRequests()
403        {
404            var requests = new List<Request>();
405            Page.Request += (_, e) =>
406            {
407                if (!TestUtils.IsFavicon(e.Request))
408                {
409                    requests.Add(e.Request);
410                }
411            };
412            var dataUrl = "data:text/html,<div>yo</div>";
413            var response = await Page.GoToAsync(dataUrl);
414            Assert.Equal(HttpStatusCode.OK, response.Status);
415            Assert.Single(requests);
416            Assert.Equal(dataUrl, requests[0].Url);
417        }
418
419        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should navigate to URL with hash and fire requests without hash")]
420        [SkipBrowserFact(skipFirefox: true)]
421        public async Task ShouldNavigateToURLWithHashAndFireRequestsWithoutHash()
422        {
423            var requests = new List<Request>();
424            Page.Request += (_, e) =>
425            {
426                if (!TestUtils.IsFavicon(e.Request))
427                {
428                    requests.Add(e.Request);
429                }
430            };
431            var response = await Page.GoToAsync(TestConstants.EmptyPage + "#hash");
432            Assert.Equal(HttpStatusCode.OK, response.Status);
433            Assert.Equal(TestConstants.EmptyPage, response.Url);
434            Assert.Single(requests);
435            Assert.Equal(TestConstants.EmptyPage, requests[0].Url);
436        }
437
438        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should work with self requesting page")]
439        [PuppeteerFact]
440        public async Task ShouldWorkWithSelfRequestingPage()
441        {
442            var response = await Page.GoToAsync(TestConstants.ServerUrl + "/self-request.html");
443            Assert.Equal(HttpStatusCode.OK, response.Status);
444            Assert.Contains("self-request.html", response.Url);
445        }
446
447        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should fail when navigating and show the url at the error message")]
448        [PuppeteerFact]
449        public async Task ShouldFailWhenNavigatingAndShowTheUrlAtTheErrorMessage()
450        {
451            var url = TestConstants.HttpsPrefix + "/redirect/1.html";
452            var exception = await Assert.ThrowsAnyAsync<NavigationException>(async () => await Page.GoToAsync(url));
453            Assert.Contains(url, exception.Message);
454            Assert.Contains(url, exception.Url);
455        }
456
457        [PuppeteerTest("navigation.spec.ts", "Page.goto", "should send referer")]
458        [SkipBrowserFact(skipFirefox: true)]
459        public async Task ShouldSendReferer()
460        {
461            await Page.SetRequestInterceptionAsync(true);
462            Page.Request += async (_, e) => await e.Request.ContinueAsync();
463            string referer1 = null;
464            string referer2 = null;
465
466            await Task.WhenAll(
467                Server.WaitForRequest("/grid.html", r => referer1 = r.Headers["Referer"]),
468                Server.WaitForRequest("/digits/1.png", r => referer2 = r.Headers["Referer"]),
469                Page.GoToAsync(TestConstants.ServerUrl + "/grid.html", new NavigationOptions
470                {
471                    Referer = "http://google.com/"
472                })
473            );
474
475            Assert.Equal("http://google.com/", referer1);
476            // Make sure subresources do not inherit referer.
477            Assert.Equal(TestConstants.ServerUrl + "/grid.html", referer2);
478        }
479    }
480}
481
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 ShouldNavigateToEmptyPageWithDOMContentLoaded code on LambdaTest Cloud Grid

Execute automation tests with ShouldNavigateToEmptyPageWithDOMContentLoaded 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)