Best Playwright-dotnet code snippet using Microsoft.Playwright.Core.Frame.GotoAsync
PageGotoTests.cs
Source:PageGotoTests.cs
...36 {37 [PlaywrightTest("page-goto.spec.ts", "should work")]38 public async Task ShouldWork()39 {40 await Page.GotoAsync(Server.EmptyPage);41 Assert.AreEqual(Server.EmptyPage, Page.Url);42 }43 [PlaywrightTest("page-goto.spec.ts", "should work with file URL")]44 public async Task ShouldWorkWithFileURL()45 {46 string fileurl = new Uri(TestUtils.GetAsset(Path.Combine("frames", "two-frames.html"))).AbsoluteUri;47 await Page.GotoAsync(fileurl);48 Assert.AreEqual(fileurl.ToLower(), Page.Url.ToLower());49 Assert.AreEqual(3, Page.Frames.Count);50 }51 [PlaywrightTest("page-goto.spec.ts", "should use http for no protocol")]52 public async Task ShouldUseHttpForNoProtocol()53 {54 await Page.GotoAsync(Server.EmptyPage.Replace("http://", string.Empty));55 Assert.AreEqual(Server.EmptyPage, Page.Url);56 }57 [PlaywrightTest("page-goto.spec.ts", "should work cross-process")]58 public async Task ShouldWorkCrossProcess()59 {60 await Page.GotoAsync(Server.EmptyPage);61 Assert.AreEqual(Server.EmptyPage, Page.Url);62 string url = Server.CrossProcessPrefix + "/empty.html";63 IFrame requestFrame = null;64 Page.Request += (_, e) =>65 {66 if (e.Url == url)67 {68 requestFrame = e.Frame;69 }70 };71 var response = await Page.GotoAsync(url);72 Assert.AreEqual(url, Page.Url);73 Assert.AreEqual(Page.MainFrame, response.Frame);74 Assert.AreEqual(Page.MainFrame, requestFrame);75 Assert.AreEqual(url, response.Url);76 }77 [PlaywrightTest("page-goto.spec.ts", "should capture iframe navigation request")]78 public async Task ShouldCaptureIframeNavigationRequest()79 {80 await Page.GotoAsync(Server.EmptyPage);81 Assert.AreEqual(Server.EmptyPage, Page.Url);82 IFrame requestFrame = null;83 Page.Request += (_, e) =>84 {85 if (e.Url == Server.Prefix + "/frames/frame.html")86 {87 requestFrame = e.Frame;88 }89 };90 var response = await Page.GotoAsync(Server.Prefix + "/frames/one-frame.html");91 Assert.AreEqual(Server.Prefix + "/frames/one-frame.html", Page.Url);92 Assert.AreEqual(Page.MainFrame, response.Frame);93 Assert.AreEqual(Server.Prefix + "/frames/one-frame.html", response.Url);94 Assert.AreEqual(2, Page.Frames.Count);95 Assert.AreEqual(Page.FirstChildFrame(), requestFrame);96 }97 [PlaywrightTest("page-goto.spec.ts", "should capture cross-process iframe navigation request")]98 public async Task ShouldCaptureCrossProcessIframeNavigationRequest()99 {100 await Page.GotoAsync(Server.EmptyPage);101 Assert.AreEqual(Server.EmptyPage, Page.Url);102 IFrame requestFrame = null;103 Page.Request += (_, e) =>104 {105 if (e.Url == Server.CrossProcessPrefix + "/frames/frame.html")106 {107 requestFrame = e.Frame;108 }109 };110 var response = await Page.GotoAsync(Server.CrossProcessPrefix + "/frames/one-frame.html");111 Assert.AreEqual(Server.CrossProcessPrefix + "/frames/one-frame.html", Page.Url);112 Assert.AreEqual(Page.MainFrame, response.Frame);113 Assert.AreEqual(Server.CrossProcessPrefix + "/frames/one-frame.html", response.Url);114 Assert.AreEqual(2, Page.Frames.Count);115 Assert.AreEqual(Page.FirstChildFrame(), requestFrame);116 }117 [PlaywrightTest("page-goto.spec.ts", "should work with anchor navigation")]118 public async Task ShouldWorkWithAnchorNavigation()119 {120 await Page.GotoAsync(Server.EmptyPage);121 Assert.AreEqual(Server.EmptyPage, Page.Url);122 await Page.GotoAsync($"{Server.EmptyPage}#foo");123 Assert.AreEqual($"{Server.EmptyPage}#foo", Page.Url);124 await Page.GotoAsync($"{Server.EmptyPage}#bar");125 Assert.AreEqual($"{Server.EmptyPage}#bar", Page.Url);126 }127 [PlaywrightTest("page-goto.spec.ts", "should work with redirects")]128 public async Task ShouldWorkWithRedirects()129 {130 Server.SetRedirect("/redirect/1.html", "/redirect/2.html");131 Server.SetRedirect("/redirect/2.html", "/empty.html");132 var response = await Page.GotoAsync(Server.Prefix + "/redirect/1.html");133 Assert.AreEqual((int)HttpStatusCode.OK, response.Status);134 await Page.GotoAsync(Server.EmptyPage);135 }136 [PlaywrightTest("page-goto.spec.ts", "should navigate to about:blank")]137 public async Task ShouldNavigateToAboutBlank()138 {139 var response = await Page.GotoAsync(TestConstants.AboutBlank);140 Assert.Null(response);141 }142 [PlaywrightTest("page-goto.spec.ts", "should return response when page changes its URL after load")]143 public async Task ShouldReturnResponseWhenPageChangesItsURLAfterLoad()144 {145 var response = await Page.GotoAsync(Server.Prefix + "/historyapi.html");146 Assert.AreEqual((int)HttpStatusCode.OK, response.Status);147 }148 [PlaywrightTest("page-goto.spec.ts", "should work with subframes return 204")]149 public Task ShouldWorkWithSubframesReturn204()150 {151 Server.SetRoute("/frames/frame.html", context =>152 {153 context.Response.StatusCode = 204;154 return Task.CompletedTask;155 });156 return Page.GotoAsync(Server.Prefix + "/frames/one-frame.html");157 }158 [PlaywrightTest("page-goto.spec.ts", "should work with subframes return 204")]159 public async Task ShouldFailWhenServerReturns204()160 {161 Server.SetRoute("/empty.html", context =>162 {163 context.Response.StatusCode = 204;164 return Task.CompletedTask;165 });166 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(167 () => Page.GotoAsync(Server.EmptyPage));168 if (TestConstants.IsChromium)169 {170 StringAssert.Contains("net::ERR_ABORTED", exception.Message);171 }172 else if (TestConstants.IsFirefox)173 {174 StringAssert.Contains("NS_BINDING_ABORTED", exception.Message);175 }176 else177 {178 StringAssert.Contains("Aborted: 204 No Content", exception.Message);179 }180 }181 [PlaywrightTest("page-goto.spec.ts", "should navigate to empty page with domcontentloaded")]182 public async Task ShouldNavigateToEmptyPageWithDOMContentLoaded()183 {184 var response = await Page.GotoAsync(Server.EmptyPage, new() { WaitUntil = WaitUntilState.DOMContentLoaded });185 Assert.AreEqual((int)HttpStatusCode.OK, response.Status);186 }187 [PlaywrightTest("page-goto.spec.ts", "should work when page calls history API in beforeunload")]188 public async Task ShouldWorkWhenPageCallsHistoryAPIInBeforeunload()189 {190 await Page.GotoAsync(Server.EmptyPage);191 await Page.EvaluateAsync(@"() =>192 {193 window.addEventListener('beforeunload', () => history.replaceState(null, 'initial', window.location.href), false);194 }");195 var response = await Page.GotoAsync(Server.Prefix + "/grid.html");196 Assert.AreEqual((int)HttpStatusCode.OK, response.Status);197 }198 [PlaywrightTest("page-goto.spec.ts", "should fail when navigating to bad url")]199 public async Task ShouldFailWhenNavigatingToBadUrl()200 {201 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.GotoAsync("asdfasdf"));202 if (TestConstants.IsChromium || TestConstants.IsWebKit)203 {204 StringAssert.Contains("Cannot navigate to invalid URL", exception.Message);205 }206 else207 {208 StringAssert.Contains("Invalid url", exception.Message);209 }210 }211 [PlaywrightTest("page-goto.spec.ts", "should fail when navigating to bad SSL")]212 public async Task ShouldFailWhenNavigatingToBadSSL()213 {214 Page.Request += (_, e) => Assert.NotNull(e);215 Page.RequestFinished += (_, e) => Assert.NotNull(e);216 Page.RequestFailed += (_, e) => Assert.NotNull(e);217 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.GotoAsync(HttpsServer.Prefix + "/empty.html"));218 TestUtils.AssertSSLError(exception.Message);219 }220 [PlaywrightTest("page-goto.spec.ts", "should fail when navigating to bad SSL after redirects")]221 public async Task ShouldFailWhenNavigatingToBadSSLAfterRedirects()222 {223 Server.SetRedirect("/redirect/1.html", "/redirect/2.html");224 Server.SetRedirect("/redirect/2.html", "/empty.html");225 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.GotoAsync(HttpsServer.Prefix + "/redirect/1.html"));226 TestUtils.AssertSSLError(exception.Message);227 }228 [PlaywrightTest("page-goto.spec.ts", "should not crash when navigating to bad SSL after a cross origin navigation")]229 public async Task ShouldNotCrashWhenNavigatingToBadSSLAfterACrossOriginNavigation()230 {231 await Page.GotoAsync(Server.CrossProcessPrefix + "/empty.html");232 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.GotoAsync(HttpsServer.Prefix + "/empty.html"));233 TestUtils.AssertSSLError(exception.Message);234 }235 [PlaywrightTest("page-goto.spec.ts", "should throw if networkidle0 is passed as an option")]236 [Ignore("We don't need this test")]237 public void ShouldThrowIfNetworkIdle0IsPassedAsAnOption()238 { }239 [PlaywrightTest("page-goto.spec.ts", "should throw if networkidle2 is passed as an option")]240 [Ignore("We don't need this test")]241 public void ShouldThrowIfNetworkIdle2IsPassedAsAnOption()242 { }243 [PlaywrightTest("page-goto.spec.ts", "should throw if networkidle is passed as an option")]244 public async Task ShouldFailWhenMainResourcesFailedToLoad()245 {246 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.GotoAsync("http://localhost:44123/non-existing-url"));247 if (TestConstants.IsChromium)248 {249 StringAssert.Contains("net::ERR_CONNECTION_REFUSED", exception.Message);250 }251 else if (TestConstants.IsWebKit && TestConstants.IsWindows)252 {253 StringAssert.Contains("Couldn't connect to server", exception.Message);254 }255 else if (TestConstants.IsWebKit)256 {257 StringAssert.Contains("Could not connect", exception.Message);258 }259 else260 {261 StringAssert.Contains("NS_ERROR_CONNECTION_REFUSED", exception.Message);262 }263 }264 [PlaywrightTest("page-goto.spec.ts", "should fail when exceeding maximum navigation timeout")]265 public async Task ShouldFailWhenExceedingMaximumNavigationTimeout()266 {267 Server.SetRoute("/empty.html", _ => Task.Delay(-1));268 var exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(()269 => Page.GotoAsync(Server.EmptyPage, new() { Timeout = 1 }));270 StringAssert.Contains("Timeout 1ms exceeded", exception.Message);271 StringAssert.Contains(Server.EmptyPage, exception.Message);272 }273 [PlaywrightTest("page-goto.spec.ts", "should fail when exceeding maximum navigation timeout")]274 public async Task ShouldFailWhenExceedingDefaultMaximumNavigationTimeout()275 {276 Server.SetRoute("/empty.html", _ => Task.Delay(-1));277 Page.Context.SetDefaultNavigationTimeout(2);278 Page.SetDefaultNavigationTimeout(1);279 var exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(() => Page.GotoAsync(Server.EmptyPage));280 StringAssert.Contains("Timeout 1ms exceeded", exception.Message);281 StringAssert.Contains(Server.EmptyPage, exception.Message);282 }283 [PlaywrightTest("page-goto.spec.ts", "should fail when exceeding browser context navigation timeout")]284 public async Task ShouldFailWhenExceedingBrowserContextNavigationTimeout()285 {286 Server.SetRoute("/empty.html", _ => Task.Delay(-1));287 Page.Context.SetDefaultNavigationTimeout(2);288 var exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(() => Page.GotoAsync(Server.EmptyPage));289 StringAssert.Contains("Timeout 2ms exceeded", exception.Message);290 StringAssert.Contains(Server.EmptyPage, exception.Message);291 }292 [PlaywrightTest("page-goto.spec.ts", "should fail when exceeding default maximum timeout")]293 public async Task ShouldFailWhenExceedingDefaultMaximumTimeout()294 {295 Server.SetRoute("/empty.html", _ => Task.Delay(-1));296 Page.Context.SetDefaultTimeout(2);297 Page.SetDefaultTimeout(1);298 var exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(() => Page.GotoAsync(Server.EmptyPage));299 StringAssert.Contains("Timeout 1ms exceeded", exception.Message);300 StringAssert.Contains(Server.EmptyPage, exception.Message);301 }302 [PlaywrightTest("page-goto.spec.ts", "should fail when exceeding browser context timeout")]303 public async Task ShouldFailWhenExceedingBrowserContextTimeout()304 {305 Server.SetRoute("/empty.html", _ => Task.Delay(-1));306 Page.Context.SetDefaultTimeout(2);307 var exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(() => Page.GotoAsync(Server.EmptyPage));308 StringAssert.Contains("Timeout 2ms exceeded", exception.Message);309 StringAssert.Contains(Server.EmptyPage, exception.Message);310 }311 [PlaywrightTest("page-goto.spec.ts", "should prioritize default navigation timeout over default timeout")]312 public async Task ShouldPrioritizeDefaultNavigationTimeoutOverDefaultTimeout()313 {314 // Hang for request to the empty.html315 Server.SetRoute("/empty.html", _ => Task.Delay(-1));316 Page.SetDefaultTimeout(0);317 Page.SetDefaultNavigationTimeout(1);318 var exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(() => Page.GotoAsync(Server.EmptyPage));319 StringAssert.Contains("Timeout 1ms exceeded", exception.Message);320 StringAssert.Contains(Server.EmptyPage, exception.Message);321 }322 [PlaywrightTest("page-goto.spec.ts", "should disable timeout when its set to 0")]323 public async Task ShouldDisableTimeoutWhenItsSetTo0()324 {325 bool loaded = false;326 void OnLoad(object sender, IPage e)327 {328 loaded = true;329 Page.Load -= OnLoad;330 }331 Page.Load += OnLoad;332 await Page.GotoAsync(Server.Prefix + "/grid.html", new() { WaitUntil = WaitUntilState.Load, Timeout = 0 });333 Assert.True(loaded);334 }335 [PlaywrightTest("page-goto.spec.ts", "should fail when replaced by another navigation")]336 public async Task ShouldFailWhenReplacedByAnotherNavigation()337 {338 Task anotherTask = null;339 // Hang for request to the empty.html340 Server.SetRoute("/empty.html", _ =>341 {342 anotherTask = Page.GotoAsync(Server.Prefix + "/one-style.html");343 return Task.Delay(-1);344 });345 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.GotoAsync(Server.EmptyPage));346 await anotherTask;347 if (TestConstants.IsChromium)348 {349 StringAssert.Contains("net::ERR_ABORTED", exception.Message);350 }351 else if (TestConstants.IsWebKit)352 {353 StringAssert.Contains("Navigation interrupted by another one", exception.Message);354 }355 else356 {357 StringAssert.Contains("NS_BINDING_ABORTED", exception.Message);358 }359 }360 [PlaywrightTest("page-goto.spec.ts", "should work when navigating to valid url")]361 public async Task ShouldWorkWhenNavigatingToValidUrl()362 {363 var response = await Page.GotoAsync(Server.EmptyPage);364 Assert.AreEqual((int)HttpStatusCode.OK, response.Status);365 }366 [PlaywrightTest("page-goto.spec.ts", "should work when navigating to data url")]367 public async Task ShouldWorkWhenNavigatingToDataUrl()368 {369 var response = await Page.GotoAsync("data:text/html,hello");370 Assert.Null(response);371 }372 [PlaywrightTest("page-goto.spec.ts", "should work when navigating to 404")]373 public async Task ShouldWorkWhenNavigatingTo404()374 {375 var response = await Page.GotoAsync(Server.Prefix + "/not-found");376 Assert.AreEqual((int)HttpStatusCode.NotFound, response.Status);377 }378 [PlaywrightTest("page-goto.spec.ts", "should return last response in redirect chain")]379 public async Task ShouldReturnLastResponseInRedirectChain()380 {381 Server.SetRedirect("/redirect/1.html", "/redirect/2.html");382 Server.SetRedirect("/redirect/2.html", "/redirect/3.html");383 Server.SetRedirect("/redirect/3.html", Server.EmptyPage);384 var response = await Page.GotoAsync(Server.Prefix + "/redirect/1.html");385 Assert.AreEqual((int)HttpStatusCode.OK, response.Status);386 Assert.AreEqual(Server.EmptyPage, response.Url);387 }388 [PlaywrightTest("page-goto.spec.ts", "should not leak listeners during navigation")]389 [Ignore("We don't need this test")]390 public void ShouldNotLeakListenersDuringNavigation()391 { }392 [PlaywrightTest("page-goto.spec.ts", "should not leak listeners during bad navigation")]393 [Ignore("We don't need this test")]394 public void ShouldNotLeakListenersDuringBadNavigation()395 { }396 [PlaywrightTest("page-goto.spec.ts", "should not leak listeners during navigation of 11 pages")]397 [Ignore("We don't need this test")]398 public void ShouldNotLeakListenersDuringNavigationOf11Pages()399 { }400 [PlaywrightTest("page-goto.spec.ts", "should navigate to dataURL and not fire dataURL requests")]401 public async Task ShouldNavigateToDataURLAndNotFireDataURLRequests()402 {403 var requests = new List<IRequest>();404 Page.Request += (_, e) => requests.Add(e);405 string dataUrl = "data:text/html,<div>yo</div>";406 var response = await Page.GotoAsync(dataUrl);407 Assert.Null(response);408 Assert.IsEmpty(requests);409 }410 [PlaywrightTest("page-goto.spec.ts", "should navigate to URL with hash and fire requests without hash")]411 public async Task ShouldNavigateToURLWithHashAndFireRequestsWithoutHash()412 {413 var requests = new List<IRequest>();414 Page.Request += (_, e) => requests.Add(e);415 var response = await Page.GotoAsync(Server.EmptyPage + "#hash");416 Assert.AreEqual((int)HttpStatusCode.OK, response.Status);417 Assert.AreEqual(Server.EmptyPage, response.Url);418 Assert.That(requests, Has.Count.EqualTo(1));419 Assert.AreEqual(Server.EmptyPage, requests[0].Url);420 }421 [PlaywrightTest("page-goto.spec.ts", "should work with self requesting page")]422 public async Task ShouldWorkWithSelfRequestingPage()423 {424 var response = await Page.GotoAsync(Server.Prefix + "/self-request.html");425 Assert.AreEqual((int)HttpStatusCode.OK, response.Status);426 StringAssert.Contains("self-request.html", response.Url);427 }428 [PlaywrightTest("page-goto.spec.ts", "should fail when navigating and show the url at the error message")]429 public async Task ShouldFailWhenNavigatingAndShowTheUrlAtTheErrorMessage()430 {431 string url = HttpsServer.Prefix + "/redirect/1.html";432 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.GotoAsync(url));433 StringAssert.Contains(url, exception.Message);434 }435 [PlaywrightTest("page-goto.spec.ts", "should be able to navigate to a page controlled by service worker")]436 public async Task ShouldBeAbleToNavigateToAPageControlledByServiceWorker()437 {438 await Page.GotoAsync(Server.Prefix + "/serviceworkers/fetch/sw.html");439 await Page.EvaluateAsync("() => window.activationPromise");440 await Page.GotoAsync(Server.Prefix + "/serviceworkers/fetch/sw.html");441 }442 [PlaywrightTest("page-goto.spec.ts", "should send referer")]443 public async Task ShouldSendReferer()444 {445 string referer1 = null;446 string referer2 = null;447 await TaskUtils.WhenAll(448 Server.WaitForRequest("/grid.html", r => referer1 = r.Headers["Referer"]),449 Server.WaitForRequest("/digits/1.png", r => referer2 = r.Headers["Referer"]),450 Page.GotoAsync(Server.Prefix + "/grid.html", new() { Referer = "http://google.com/" })451 );452 Assert.AreEqual("http://google.com/", referer1);453 // Make sure subresources do not inherit referer.454 Assert.AreEqual(Server.Prefix + "/grid.html", referer2);455 Assert.AreEqual(Server.Prefix + "/grid.html", Page.Url);456 }457 [PlaywrightTest("page-goto.spec.ts", "should reject referer option when setExtraHTTPHeaders provides referer")]458 public async Task ShouldRejectRefererOptionWhenSetExtraHTTPHeadersProvidesReferer()459 {460 await Page.SetExtraHTTPHeadersAsync(new Dictionary<string, string>461 {462 ["referer"] = "http://microsoft.com/"463 });464 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() =>465 Page.GotoAsync(Server.Prefix + "/grid.html", new() { Referer = "http://google.com/" }));466 StringAssert.Contains("\"referer\" is already specified as extra HTTP header", exception.Message);467 StringAssert.Contains(Server.Prefix + "/grid.html", exception.Message);468 }469 [PlaywrightTest("page-goto.spec.ts", "should override referrer-policy")]470 public async Task ShouldOverrideReferrerPolicy()471 {472 Server.Subscribe("/grid.html", context =>473 {474 context.Response.Headers["Referrer-Policy"] = "no-referrer";475 });476 string referer1 = null;477 string referer2 = null;478 var reqTask1 = Server.WaitForRequest("/grid.html", r => referer1 = r.Headers["Referer"]);479 var reqTask2 = Server.WaitForRequest("/digits/1.png", r => referer2 = r.Headers["Referer"]);480 await TaskUtils.WhenAll(481 reqTask1,482 reqTask2,483 Page.GotoAsync(Server.Prefix + "/grid.html", new() { Referer = "http://microsoft.com/" }));484 Assert.AreEqual("http://microsoft.com/", referer1);485 // Make sure subresources do not inherit referer.486 Assert.Null(referer2);487 Assert.AreEqual(Server.Prefix + "/grid.html", Page.Url);488 }489 [PlaywrightTest("page-goto.spec.ts", "should fail when canceled by another navigation")]490 public async Task ShouldFailWhenCanceledByAnotherNavigation()491 {492 Server.SetRoute("/one-style.html", _ => Task.Delay(10_000));493 var request = Server.WaitForRequest("/one-style.html");494 var failed = Page.GotoAsync(Server.Prefix + "/one-style.html", new() { WaitUntil = TestConstants.IsFirefox ? WaitUntilState.NetworkIdle : WaitUntilState.Load });495 await request;496 await Page.GotoAsync(Server.EmptyPage);497 await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => failed);498 }499 [PlaywrightTest("page-goto.spec.ts", "should return when navigation is comitted if commit is specified")]500 [Skip(SkipAttribute.Targets.Firefox, SkipAttribute.Targets.Webkit)]501 public async Task ShouldReturnWhenNavigationIsComittedIfCommitIsSpecified()502 {503 Server.SetRoute("/empty.html", async context =>504 {505 context.Response.StatusCode = 200;506 context.Response.Headers.Add("content-type", "text/html");507 context.Response.Headers.Add("content-length", "8192");508 // Write enought bytes of the body to trigge response received event.509 var str = "<title>" + new string('a', 4100);510 await context.Response.WriteAsync(str);511 await context.Response.BodyWriter.FlushAsync();512 });513 var response = await Page.GotoAsync(Server.EmptyPage, new() { WaitUntil = TestConstants.IsFirefox ? WaitUntilState.NetworkIdle : WaitUntilState.Load });514 Assert.AreEqual(200, response.Status);515 }516 }517}...
PageNetworkRequestTest.cs
Source:PageNetworkRequestTest.cs
...36 public async Task ShouldWorkForMainFrameNavigationRequests()37 {38 var requests = new List<IRequest>();39 Page.Request += (_, e) => requests.Add(e);40 await Page.GotoAsync(Server.EmptyPage);41 Assert.That(requests, Has.Count.EqualTo(1));42 Assert.AreEqual(Page.MainFrame, requests[0].Frame);43 }44 [PlaywrightTest("page-network-request.spec.ts", "should work for subframe navigation request")]45 public async Task ShouldWorkForSubframeNavigationRequest()46 {47 var requests = new List<IRequest>();48 Page.Request += (_, e) => requests.Add(e);49 await Page.GotoAsync(Server.EmptyPage);50 await FrameUtils.AttachFrameAsync(Page, "frame1", Server.EmptyPage);51 Assert.AreEqual(2, requests.Count);52 Assert.AreEqual(Page.FirstChildFrame(), requests[1].Frame);53 }54 [PlaywrightTest("page-network-request.spec.ts", "should work for fetch requests")]55 public async Task ShouldWorkForFetchRequests()56 {57 await Page.GotoAsync(Server.EmptyPage);58 var requests = new List<IRequest>();59 Page.Request += (_, e) => requests.Add(e);60 await Page.EvaluateAsync("fetch('/digits/1.png')");61 Assert.AreEqual(1, requests.Where(r => !r.Url.Contains("favicon")).Count());62 Assert.AreEqual(Page.MainFrame, requests[0].Frame);63 }64 [PlaywrightTest("page-network-request.spec.ts", "should return headers")]65 public async Task ShouldReturnHeaders()66 {67 var response = await Page.GotoAsync(Server.EmptyPage);68 string expected = TestConstants.BrowserName switch69 {70 "chromium" => "Chrome",71 "firefox" => "Firefox",72 "webkit" => "WebKit",73 _ => "None"74 };75#pragma warning disable 061276 StringAssert.Contains(expected, response.Request.Headers["user-agent"]);77#pragma warning restore 061278 }79 [PlaywrightTest("page-network-request.spec.ts", "should return postData")]80 public async Task ShouldReturnPostData()81 {82 await Page.GotoAsync(Server.EmptyPage);83 Server.SetRoute("/post", _ => Task.CompletedTask);84 IRequest request = null;85 Page.Request += (_, e) => request = e;86 await Page.EvaluateHandleAsync("fetch('./post', { method: 'POST', body: JSON.stringify({ foo: 'bar'})})");87 Assert.NotNull(request);88 Assert.AreEqual("{\"foo\":\"bar\"}", request.PostData);89 }90 [PlaywrightTest("page-network-request.spec.ts", "should work with binary post data")]91 public async Task ShouldWorkWithBinaryPostData()92 {93 await Page.GotoAsync(Server.EmptyPage);94 Server.SetRoute("/post", _ => Task.CompletedTask);95 IRequest request = null;96 Page.Request += (_, e) => request = e;97 await Page.EvaluateHandleAsync("fetch('./post', { method: 'POST', body: new Uint8Array(Array.from(Array(256).keys())) })");98 Assert.NotNull(request);99 byte[] data = request.PostDataBuffer;100 Assert.AreEqual(256, data.Length);101 for (int index = 0; index < data.Length; index++)102 {103 Assert.AreEqual(index, data[index]);104 }105 }106 [PlaywrightTest("page-network-request.spec.ts", "should work with binary post data and interception")]107 public async Task ShouldWorkWithBinaryPostDataAndInterception()108 {109 await Page.GotoAsync(Server.EmptyPage);110 Server.SetRoute("/post", _ => Task.CompletedTask);111 await Page.RouteAsync("/post", (route) => route.ContinueAsync());112 IRequest request = null;113 Page.Request += (_, e) => request = e;114 await Page.EvaluateHandleAsync("fetch('./post', { method: 'POST', body: new Uint8Array(Array.from(Array(256).keys())) })");115 Assert.NotNull(request);116 byte[] data = request.PostDataBuffer;117 Assert.AreEqual(256, data.Length);118 for (int index = 0; index < data.Length; index++)119 {120 Assert.AreEqual(index, data[index]);121 }122 }123 [PlaywrightTest("page-network-request.spec.ts", "should be |undefined| when there is no post data")]124 public async Task ShouldBeUndefinedWhenThereIsNoPostData()125 {126 var response = await Page.GotoAsync(Server.EmptyPage);127 Assert.Null(response.Request.PostData);128 }129 [PlaywrightTest("page-network-request.spec.ts", "should parse the json post data")]130 public async Task ShouldParseTheJsonPostData()131 {132 await Page.GotoAsync(Server.EmptyPage);133 Server.SetRoute("/post", _ => Task.CompletedTask);134 IRequest request = null;135 Page.Request += (_, e) => request = e;136 await Page.EvaluateHandleAsync("fetch('./post', { method: 'POST', body: JSON.stringify({ foo: 'bar'})})");137 Assert.NotNull(request);138 Assert.AreEqual("bar", request.PostDataJSON()?.GetProperty("foo").ToString());139 }140 [PlaywrightTest("page-network-request.spec.ts", "should parse the data if content-type is application/x-www-form-urlencoded")]141 public async Task ShouldParseTheDataIfContentTypeIsApplicationXWwwFormUrlencoded()142 {143 await Page.GotoAsync(Server.EmptyPage);144 Server.SetRoute("/post", _ => Task.CompletedTask);145 IRequest request = null;146 Page.Request += (_, e) => request = e;147 await Page.SetContentAsync("<form method='POST' action='/post'><input type='text' name='foo' value='bar'><input type='number' name='baz' value='123'><input type='submit'></form>");148 await Page.ClickAsync("input[type=submit]");149 Assert.NotNull(request);150 var element = request.PostDataJSON();151 Assert.AreEqual("bar", element?.GetProperty("foo").ToString());152 Assert.AreEqual("123", element?.GetProperty("baz").ToString());153 }154 [PlaywrightTest("page-network-request.spec.ts", "should be |undefined| when there is no post data")]155 public async Task ShouldBeUndefinedWhenThereIsNoPostData2()156 {157 var response = await Page.GotoAsync(Server.EmptyPage);158 Assert.Null(response.Request.PostDataJSON());159 }160 [PlaywrightTest("page-network-request.spec.ts", "should return event source")]161 public async Task ShouldReturnEventSource()162 {163 const string sseMessage = "{\"foo\": \"bar\"}";164 Server.SetRoute("/sse", async ctx =>165 {166 ctx.Response.Headers["content-type"] = "text/event-stream";167 ctx.Response.Headers["connection"] = "keep-alive";168 ctx.Response.Headers["cache-control"] = "no-cache";169 await ctx.Response.Body.FlushAsync();170 await ctx.Response.WriteAsync($"data: {sseMessage}\r\r");171 await ctx.Response.Body.FlushAsync();172 });173 await Page.GotoAsync(Server.EmptyPage);174 var requests = new List<IRequest>();175 Page.Request += (_, e) => requests.Add(e);176 Assert.AreEqual(sseMessage, await Page.EvaluateAsync<string>(@"() => {177 const eventSource = new EventSource('/sse');178 return new Promise(resolve => {179 eventSource.onmessage = e => resolve(e.data);180 });181 }"));182 Assert.AreEqual("eventsource", requests[0].ResourceType);183 }184 [PlaywrightTest("page-network-request.spec.ts", "should return navigation bit")]185 public async Task ShouldReturnNavigationBit()186 {187 var requests = new Dictionary<string, IRequest>();188 Page.Request += (_, e) => requests[e.Url.Split('/').Last()] = e;189 Server.SetRedirect("/rrredirect", "/frames/one-frame.html");190 await Page.GotoAsync(Server.Prefix + "/rrredirect");191 Assert.True(requests["rrredirect"].IsNavigationRequest);192 Assert.True(requests["one-frame.html"].IsNavigationRequest);193 Assert.True(requests["frame.html"].IsNavigationRequest);194 Assert.False(requests["script.js"].IsNavigationRequest);195 Assert.False(requests["style.css"].IsNavigationRequest);196 }197 [PlaywrightTest("page-network-request.spec.ts", "Request.isNavigationRequest", "should return navigation bit when navigating to image")]198 public async Task ShouldReturnNavigationBitWhenNavigatingToImage()199 {200 var requests = new List<IRequest>();201 Page.Request += (_, e) => requests.Add(e);202 await Page.GotoAsync(Server.Prefix + "/pptr.png");203 Assert.True(requests[0].IsNavigationRequest);204 }205 [PlaywrightTest("page-network-request.spec.ts", "should set bodySize and headersSize")]206 public async Task ShouldSetBodySizeAndHeaderSize()207 {208 await Page.GotoAsync(Server.EmptyPage);209 var tsc = new TaskCompletionSource<RequestSizesResult>();210 Page.Request += async (sender, r) =>211 {212 await (await r.ResponseAsync()).FinishedAsync();213 tsc.SetResult(await r.SizesAsync());214 };215 await Page.EvaluateAsync("() => fetch('./get', { method: 'POST', body: '12345'}).then(r => r.text())");216 var sizes = await tsc.Task;217 Assert.AreEqual(5, sizes.RequestBodySize);218 Assert.GreaterOrEqual(sizes.RequestHeadersSize, 200);219 }220 [PlaywrightTest("page-network-request.spec.ts", "should should set bodySize to 0 if there was no body")]221 public async Task ShouldSetBodysizeTo0IfThereWasNoBody()222 {223 await Page.GotoAsync(Server.EmptyPage);224 var tsc = new TaskCompletionSource<RequestSizesResult>();225 Page.Request += async (sender, r) =>226 {227 await (await r.ResponseAsync()).FinishedAsync();228 tsc.SetResult(await r.SizesAsync());229 };230 await Page.EvaluateAsync("() => fetch('./get').then(r => r.text())");231 var sizes = await tsc.Task;232 Assert.AreEqual(0, sizes.RequestBodySize);233 Assert.GreaterOrEqual(sizes.RequestHeadersSize, 200);234 }235 [PlaywrightTest("page-network-request.spec.ts", "should should set bodySize, headersSize, and transferSize")]236 [Skip(SkipAttribute.Targets.Firefox, SkipAttribute.Targets.Chromium, SkipAttribute.Targets.Webkit)]237 public async Task ShouldSetAllTheResponseSizes()238 {239 Server.SetRoute("/get", async ctx =>240 {241 ctx.Response.Headers["Content-Type"] = "text/plain; charset=utf-8";242 await ctx.Response.WriteAsync("abc134");243 await ctx.Response.CompleteAsync();244 });245 await Page.GotoAsync(Server.EmptyPage);246 var tsc = new TaskCompletionSource<RequestSizesResult>();247 Page.Request += async (sender, r) =>248 {249 await (await r.ResponseAsync()).FinishedAsync();250 tsc.SetResult(await r.SizesAsync());251 };252 var message = await Page.EvaluateAsync<string>("() => fetch('./get').then(r => r.arrayBuffer()).then(b => b.bufferLength)");253 var sizes = await tsc.Task;254 Assert.AreEqual(6, sizes.ResponseBodySize);255 Assert.GreaterOrEqual(sizes.ResponseHeadersSize, 142);256 }257 [PlaywrightTest("page-network-request.spec.ts", "should should set bodySize to 0 when there was no response body")]258 public async Task ShouldSetBodySizeTo0WhenNoResponseBody()259 {260 var response = await Page.GotoAsync(Server.EmptyPage);261 await response.FinishedAsync();262 var sizes = await response.Request.SizesAsync();263 Assert.AreEqual(0, sizes.ResponseBodySize);264 Assert.GreaterOrEqual(sizes.ResponseHeadersSize, 142);265 }266 [PlaywrightTest("page-network-request.spec.ts", "should report raw headers")]267 public async Task ShouldReportRawHeaders()268 {269 var expectedHeaders = new Dictionary<string, string>();270 Server.SetRoute("/headers", async ctx =>271 {272 expectedHeaders.Clear();273 foreach (var header in ctx.Request.Headers)274 {275 expectedHeaders.Add(header.Key.ToLower(), header.Value);276 }277 await ctx.Response.CompleteAsync();278 });279 await Page.GotoAsync(Server.EmptyPage);280 //Page.RunAndWaitForRequestFinishedAsync(281 // async () => await Page.EvaluateAsync("**/*")282 var requestTask = Page.WaitForRequestAsync("**/*");283 var evalTask = Page.EvaluateAsync(@"() =>284fetch('/headers', {285 headers: [286 ['header-a', 'value-a'],287 ['header-b', 'value-b'],288 ['header-a', 'value-a-1'],289 ['header-a', 'value-a-2'],290 ]291 })292");293 await Task.WhenAll(requestTask, evalTask);...
PageNetworkIdleTests.cs
Source:PageNetworkIdleTests.cs
...38 {39 [PlaywrightTest("page-network-idle.spec.ts", "should navigate to empty page with networkidle")]40 public async Task ShouldNavigateToEmptyPageWithNetworkIdle()41 {42 var response = await Page.GotoAsync(Server.EmptyPage, new() { WaitUntil = WaitUntilState.NetworkIdle });43 Assert.AreEqual((int)HttpStatusCode.OK, response.Status);44 }45 [PlaywrightTest("page-network-idle.spec.ts", "should wait for networkidle to succeed navigation")]46 public Task ShouldWaitForNetworkIdleToSucceedNavigation()47 => NetworkIdleTestAsync(Page.MainFrame, () => Page.GotoAsync(Server.Prefix + "/networkidle.html", new() { WaitUntil = WaitUntilState.NetworkIdle }));48 [PlaywrightTest("page-network-idle.spec.ts", "should wait for networkidle to succeed navigation with request from previous navigation")]49 public async Task ShouldWaitForToSucceedNavigationWithRequestFromPreviousNavigation()50 {51 await Page.GotoAsync(Server.EmptyPage);52 Server.SetRoute("/foo.js", _ => Task.CompletedTask);53 await Page.SetContentAsync("<script>fetch('foo.js')</script>");54 await NetworkIdleTestAsync(Page.MainFrame, () => Page.GotoAsync(Server.Prefix + "/networkidle.html", new() { WaitUntil = WaitUntilState.NetworkIdle }));55 }56 [PlaywrightTest("page-network-idle.spec.ts", "should wait for networkidle in waitForNavigation")]57 public Task ShouldWaitForInWaitForNavigation()58 => NetworkIdleTestAsync(59 Page.MainFrame,60 () =>61 {62 var task = Page.WaitForNavigationAsync(new() { WaitUntil = WaitUntilState.NetworkIdle });63 Page.GotoAsync(Server.Prefix + "/networkidle.html");64 return task;65 });66 [PlaywrightTest("page-network-idle.spec.ts", "should wait for networkidle in setContent")]67 public async Task ShouldWaitForInSetContent()68 {69 await Page.GotoAsync(Server.EmptyPage);70 await NetworkIdleTestAsync(71 Page.MainFrame,72 () => Page.SetContentAsync("<script src='networkidle.js'></script>", new() { WaitUntil = WaitUntilState.NetworkIdle }),73 true);74 }75 [PlaywrightTest("page-network-idle.spec.ts", "should wait for networkidle in setContent with request from previous navigation")]76 public async Task ShouldWaitForNetworkIdleInSetContentWithRequestFromPreviousNavigation()77 {78 await Page.GotoAsync(Server.EmptyPage);79 Server.SetRoute("/foo.js", _ => Task.CompletedTask);80 await Page.SetContentAsync("<script>fetch('foo.js')</script>");81 await NetworkIdleTestAsync(82 Page.MainFrame,83 () => Page.SetContentAsync("<script src='networkidle.js'></script>", new() { WaitUntil = WaitUntilState.NetworkIdle }),84 true);85 }86 [PlaywrightTest("page-network-idle.spec.ts", "should wait for networkidle when navigating iframe")]87 public async Task ShouldWaitForNetworkIdleWhenNavigatingIframe()88 {89 await Page.GotoAsync(Server.Prefix + "/frames/one-frame.html");90 var frame = Page.FirstChildFrame();91 await NetworkIdleTestAsync(92 frame,93 () => frame.GotoAsync(Server.Prefix + "/networkidle.html", new() { WaitUntil = WaitUntilState.NetworkIdle }));94 }95 [PlaywrightTest("page-network-idle.spec.ts", "should wait for networkidle in setContent from the child frame")]96 public async Task ShouldWaitForInSetContentFromTheChildFrame()97 {98 await Page.GotoAsync(Server.EmptyPage);99 await NetworkIdleTestAsync(100 Page.MainFrame,101 () => Page.SetContentAsync("<iframe src='networkidle.html'></iframe>", new() { WaitUntil = WaitUntilState.NetworkIdle }),102 true);103 }104 [PlaywrightTest("page-network-idle.spec.ts", "should wait for networkidle from the child frame")]105 public Task ShouldWaitForFromTheChildFrame()106 => NetworkIdleTestAsync(107 Page.MainFrame,108 () => Page.GotoAsync(Server.Prefix + "/networkidle-frame.html", new() { WaitUntil = WaitUntilState.NetworkIdle }));109 [PlaywrightTest("page-network-idle.spec.ts", "should wait for networkidle from the popup")]110 public async Task ShouldWaitForNetworkIdleFromThePopup()111 {112 await Page.GotoAsync(Server.EmptyPage);113 await Page.SetContentAsync(@"114 <button id=box1 onclick=""window.open('./popup/popup.html')"">Button1</button>115 <button id=box2 onclick=""window.open('./popup/popup.html')"">Button2</button>116 <button id=box3 onclick=""window.open('./popup/popup.html')"">Button3</button>117 <button id=box4 onclick=""window.open('./popup/popup.html')"">Button4</button>118 <button id=box5 onclick=""window.open('./popup/popup.html')"">Button5</button>119 ");120 for (int i = 1; i < 6; i++)121 {122 var popupTask = Page.WaitForPopupAsync();123 await Task.WhenAll(124 Page.WaitForPopupAsync(),125 Page.ClickAsync("#box" + i));126 await popupTask.Result.WaitForLoadStateAsync(LoadState.NetworkIdle);...
PageWaitForUrlTests.cs
Source:PageWaitForUrlTests.cs
...34 {35 [PlaywrightTest("page-wait-for-url.spec.ts", "should work")]36 public async Task ShouldWork()37 {38 await Page.GotoAsync(Server.EmptyPage);39 await Page.EvaluateAsync("url => window.location.href = url", Server.Prefix + "/grid.html");40 await Page.WaitForURLAsync("**/grid.html");41 }42 [PlaywrightTest("page-wait-for-url.spec.ts", "should respect timeout")]43 public async Task ShouldRespectTimeout()44 {45 var task = Page.WaitForURLAsync("**/frame.html", new() { Timeout = 2500 });46 await Page.GotoAsync(Server.EmptyPage);47 var exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(() => task);48 StringAssert.Contains("Timeout 2500ms exceeded.", exception.Message);49 }50 [PlaywrightTest("page-wait-for-url.spec.ts", "should work with both domcontentloaded and load")]51 public async Task UrlShouldWorkWithBothDomcontentloadedAndLoad()52 {53 var responseTask = new TaskCompletionSource<bool>();54 Server.SetRoute("/one-style.css", async (ctx) =>55 {56 if (await responseTask.Task)57 {58 await ctx.Response.WriteAsync("Some css");59 }60 });61 var waitForRequestTask = Server.WaitForRequest("/one-style.css");62 var navigationTask = Page.GotoAsync(Server.Prefix + "/one-style.html");63 var domContentLoadedTask = Page.WaitForURLAsync("**/one-style.html", new() { WaitUntil = WaitUntilState.DOMContentLoaded });64 var bothFiredTask = Task.WhenAll(65 Page.WaitForURLAsync("**/one-style.html", new() { WaitUntil = WaitUntilState.Load }),66 domContentLoadedTask);67 await waitForRequestTask;68 await domContentLoadedTask;69 Assert.False(bothFiredTask.IsCompleted);70 responseTask.TrySetResult(true);71 await bothFiredTask;72 await navigationTask;73 }74 [PlaywrightTest("page-wait-for-url.spec.ts", "should work with clicking on anchor links")]75 public async Task ShouldWorkWithClickingOnAnchorLinks()76 {77 await Page.GotoAsync(Server.EmptyPage);78 await Page.SetContentAsync("<a href='#foobar'>foobar</a>");79 await Page.ClickAsync("a");80 await Page.WaitForURLAsync("**/*#foobar");81 }82 [PlaywrightTest("page-wait-for-url.spec.ts", "should work with history.pushState()")]83 public async Task ShouldWorkWithHistoryPushState()84 {85 await Page.GotoAsync(Server.EmptyPage);86 await Page.SetContentAsync(@"87 <a onclick='javascript:replaceState()'>SPA</a>88 <script>89 function replaceState() { history.replaceState({}, '', '/replaced.html') }90 </script>91 ");92 await Page.ClickAsync("a");93 await Page.WaitForURLAsync("**/replaced.html");94 Assert.AreEqual(Server.Prefix + "/replaced.html", Page.Url);95 }96 [PlaywrightTest("page-wait-for-url.spec.ts", "should work with DOM history.back()/history.forward()")]97 public async Task ShouldWorkWithDOMHistoryBackHistoryForward()98 {99 await Page.GotoAsync(Server.EmptyPage);100 await Page.SetContentAsync(@"101 <a id=back onclick='javascript:goBack()'>back</a>102 <a id=forward onclick='javascript:goForward()'>forward</a>103 <script>104 function goBack() { history.back(); }105 function goForward() { history.forward(); }106 history.pushState({}, '', '/first.html');107 history.pushState({}, '', '/second.html');108 </script>109 ");110 Assert.AreEqual(Server.Prefix + "/second.html", Page.Url);111 await Task.WhenAll(Page.WaitForURLAsync("**/first.html"), Page.ClickAsync("a#back"));112 Assert.AreEqual(Server.Prefix + "/first.html", Page.Url);113 await Task.WhenAll(Page.WaitForURLAsync("**/second.html"), Page.ClickAsync("a#forward"));114 Assert.AreEqual(Server.Prefix + "/second.html", Page.Url);115 }116 [PlaywrightTest("page-wait-for-url.spec.ts", "should work with url match for same document navigations")]117 public async Task ShouldWorkWithUrlMatchForSameDocumentNavigations()118 {119 await Page.GotoAsync(Server.EmptyPage);120 var waitPromise = Page.WaitForURLAsync(new Regex("third\\.html"));121 Assert.False(waitPromise.IsCompleted);122 await Page.EvaluateAsync(@"() => {123 history.pushState({}, '', '/first.html');124 }");125 Assert.False(waitPromise.IsCompleted);126 await Page.EvaluateAsync(@"() => {127 history.pushState({}, '', '/second.html');128 }");129 Assert.False(waitPromise.IsCompleted);130 await Page.EvaluateAsync(@"() => {131 history.pushState({}, '', '/third.html');132 }");133 await waitPromise;134 }135 [PlaywrightTest("page-wait-for-url.spec.ts", "should work on frame")]136 public async Task ShouldWorkOnFrame()137 {138 await Page.GotoAsync(Server.Prefix + "/frames/one-frame.html");139 var frame = Page.Frames.ElementAt(1);140 await TaskUtils.WhenAll(141 frame.WaitForURLAsync("**/grid.html"),142 frame.EvaluateAsync("url => window.location.href = url", Server.Prefix + "/grid.html"));143 ;144 }145 }146}...
PageWaitForLoadStateTests.cs
Source:PageWaitForLoadStateTests.cs
...46 ctx.Response.StatusCode = 404;47 await ctx.Response.WriteAsync("File not found");48 }49 });50 var navigationTask = Page.GotoAsync(Server.Prefix + "/one-style.html");51 await waitForRequestTask;52 var waitLoadTask = Page.WaitForLoadStateAsync();53 responseTask.TrySetResult(true);54 await waitLoadTask;55 await navigationTask;56 }57 [PlaywrightTest("page-wait-for-load-state.ts", "should respect timeout")]58 public async Task ShouldRespectTimeout()59 {60 Server.SetRoute("/one-style.css", _ => Task.Delay(Timeout.Infinite));61 await Page.GotoAsync(Server.Prefix + "/one-style.html", new() { WaitUntil = WaitUntilState.DOMContentLoaded });62 var exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(() => Page.WaitForLoadStateAsync(LoadState.Load, new() { Timeout = 1 }));63 StringAssert.Contains("Timeout 1ms exceeded", exception.Message);64 }65 [PlaywrightTest("page-wait-for-load-state.ts", "should resolve immediately if loaded")]66 public async Task ShouldResolveImmediatelyIfLoaded()67 {68 await Page.GotoAsync(Server.Prefix + "/one-style.html");69 await Page.WaitForLoadStateAsync();70 }71 [PlaywrightTest("page-wait-for-load-state.ts", "should resolve immediately if load state matches")]72 public async Task ShouldResolveImmediatelyIfLoadStateMatches()73 {74 var responseTask = new TaskCompletionSource<bool>();75 var waitForRequestTask = Server.WaitForRequest("/one-style.css");76 Server.SetRoute("/one-style.css", async (ctx) =>77 {78 if (await responseTask.Task)79 {80 ctx.Response.StatusCode = 404;81 await ctx.Response.WriteAsync("File not found");82 }83 });84 var navigationTask = Page.GotoAsync(Server.Prefix + "/one-style.html");85 await waitForRequestTask;86 await Page.WaitForLoadStateAsync(LoadState.DOMContentLoaded);87 responseTask.TrySetResult(true);88 await navigationTask;89 }90 [PlaywrightTest("page-wait-for-load-state.ts", "should work with pages that have loaded before being connected to")]91 [Skip(SkipAttribute.Targets.Firefox, SkipAttribute.Targets.Webkit)]92 public async Task ShouldWorkWithPagesThatHaveLoadedBeforeBeingConnectedTo()93 {94 await Page.GotoAsync(Server.EmptyPage);95 await Page.EvaluateAsync(@"async () => {96 const child = window.open(document.location.href);97 while (child.document.readyState !== 'complete' || child.document.location.href === 'about:blank')98 await new Promise(f => setTimeout(f, 100));99 }");100 var pages = Context.Pages;101 Assert.AreEqual(2, pages.Count);102 // order is not guaranteed103 var mainPage = pages.FirstOrDefault(p => ReferenceEquals(Page, p));104 var connectedPage = pages.Single(p => !ReferenceEquals(Page, p));105 Assert.NotNull(mainPage);106 Assert.AreEqual(Server.EmptyPage, mainPage.Url);107 Assert.AreEqual(Server.EmptyPage, connectedPage.Url);108 await connectedPage.WaitForLoadStateAsync();109 Assert.AreEqual(Server.EmptyPage, connectedPage.Url);110 }111 [PlaywrightTest("page-wait-for-load-state.spec.ts", "should work for frame")]112 public async Task ShouldWorkForFrame()113 {114 await Page.GotoAsync(Server.Prefix + "/frames/one-frame.html");115 var frame = Page.Frames.ElementAt(1);116 TaskCompletionSource<bool> requestTask = new TaskCompletionSource<bool>();117 TaskCompletionSource<bool> routeReachedTask = new TaskCompletionSource<bool>();118 await Page.RouteAsync(Server.Prefix + "/one-style.css", async (route) =>119 {120 routeReachedTask.TrySetResult(true);121 await requestTask.Task;122 await route.ContinueAsync();123 });124 await frame.GotoAsync(Server.Prefix + "/one-style.html", new() { WaitUntil = WaitUntilState.DOMContentLoaded });125 await routeReachedTask.Task;126 var loadTask = frame.WaitForLoadStateAsync();127 await Page.EvaluateAsync("1");128 Assert.False(loadTask.IsCompleted);129 requestTask.TrySetResult(true);130 await loadTask;131 }132 }133}...
FrameGoToTests.cs
Source:FrameGoToTests.cs
...35 {36 [PlaywrightTest("frame-goto.spec.ts", "should navigate subframes")]37 public async Task ShouldNavigateSubFrames()38 {39 await Page.GotoAsync(Server.Prefix + "/frames/one-frame.html");40 Assert.AreEqual(1, Page.Frames.Where(f => f.Url.Contains("/frames/one-frame.html")).Count());41 Assert.AreEqual(1, Page.Frames.Where(f => f.Url.Contains("/frames/frame.html")).Count());42 var childFrame = Page.FirstChildFrame();43 var response = await childFrame.GotoAsync(Server.EmptyPage);44 Assert.AreEqual((int)HttpStatusCode.OK, response.Status);45 Assert.AreEqual(response.Frame, childFrame);46 }47 [PlaywrightTest("frame-goto.spec.ts", "should reject when frame detaches")]48 public async Task ShouldRejectWhenFrameDetaches()49 {50 await Page.GotoAsync(Server.Prefix + "/frames/one-frame.html");51 Server.SetRoute("/empty.html", _ => Task.Delay(10000));52 var waitForRequestTask = Server.WaitForRequest("/empty.html");53 var navigationTask = Page.FirstChildFrame().GotoAsync(Server.EmptyPage);54 await waitForRequestTask;55 await Page.EvalOnSelectorAsync("iframe", "frame => frame.remove()");56 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => navigationTask);57 StringAssert.Contains("frame was detached", exception.Message);58 }59 [PlaywrightTest("frame-goto.spec.ts", "should continue after client redirect")]60 public async Task ShouldContinueAfterClientRedirect()61 {62 Server.SetRoute("/frames/script.js", _ => Task.Delay(10000));63 string url = Server.Prefix + "/frames/child-redirect.html";64 var exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(() => Page.GotoAsync(url, new() { WaitUntil = WaitUntilState.NetworkIdle, Timeout = 5000 }));65 StringAssert.Contains("Timeout 5000ms", exception.Message);66 StringAssert.Contains($"navigating to \"{url}\", waiting until \"networkidle\"", exception.Message);67 }68 [PlaywrightTest("frame-goto.spec.ts", "should return matching responses")]69 public async Task ShouldReturnMatchingResponses()70 {71 await Page.GotoAsync(Server.EmptyPage);72 // Attach three frames.73 var matchingData = new MatchingResponseData[]74 {75 new() { FrameTask = FrameUtils.AttachFrameAsync(Page, "frame1", Server.EmptyPage)},76 new() { FrameTask = FrameUtils.AttachFrameAsync(Page, "frame2", Server.EmptyPage)},77 new() { FrameTask = FrameUtils.AttachFrameAsync(Page, "frame3", Server.EmptyPage)}78 };79 await TaskUtils.WhenAll(matchingData.Select(m => m.FrameTask));80 // Navigate all frames to the same URL.81 var requestHandler = new RequestDelegate(async (context) =>82 {83 if (int.TryParse(context.Request.Query["index"], out int index))84 {85 await context.Response.WriteAsync(await matchingData[index].ServerResponseTcs.Task);86 }87 });88 Server.SetRoute("/one-style.html?index=0", requestHandler);89 Server.SetRoute("/one-style.html?index=1", requestHandler);90 Server.SetRoute("/one-style.html?index=2", requestHandler);91 for (int i = 0; i < 3; ++i)92 {93 var waitRequestTask = Server.WaitForRequest("/one-style.html");94 matchingData[i].NavigationTask = matchingData[i].FrameTask.Result.GotoAsync($"{Server.Prefix}/one-style.html?index={i}");95 await waitRequestTask;96 }97 // Respond from server out-of-order.98 string[] serverResponseTexts = new string[] { "AAA", "BBB", "CCC" };99 for (int i = 0; i < 3; ++i)100 {101 matchingData[i].ServerResponseTcs.TrySetResult(serverResponseTexts[i]);102 var response = await matchingData[i].NavigationTask;103 Assert.AreEqual(matchingData[i].FrameTask.Result, response.Frame);104 Assert.AreEqual(serverResponseTexts[i], await response.TextAsync());105 }106 }107 class MatchingResponseData108 {...
IgnoreHttpsErrorsTests.cs
Source:IgnoreHttpsErrorsTests.cs
...38 public async Task ShouldWork()39 {40 await using var context = await Browser.NewContextAsync(new() { IgnoreHTTPSErrors = true });41 var page = await context.NewPageAsync();42 var responseTask = page.GotoAsync(HttpsServer.EmptyPage);43 var response = responseTask.Result;44 Assert.AreEqual((int)HttpStatusCode.OK, response.Status);45 }46 [PlaywrightTest("ignorehttpserrors.spec.ts", "should isolate contexts")]47 public async Task ShouldIsolateContexts()48 {49 await using (var context = await Browser.NewContextAsync(new() { IgnoreHTTPSErrors = true }))50 {51 var page = await context.NewPageAsync();52 var response = await page.GotoAsync(HttpsServer.Prefix + "/empty.html");53 Assert.AreEqual((int)HttpStatusCode.OK, response.Status);54 }55 await using (var context = await Browser.NewContextAsync())56 {57 var page = await context.NewPageAsync();58 await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => page.GotoAsync(HttpsServer.Prefix + "/empty.html"));59 }60 }61 [PlaywrightTest("ignorehttpserrors.spec.ts", "should work with mixed content")]62 public async Task ShouldWorkWithMixedContent()63 {64 HttpsServer.SetRoute("/mixedcontent.html", async (context) =>65 {66 await context.Response.WriteAsync($"<iframe src='{Server.EmptyPage}'></iframe>");67 });68 await using var context = await Browser.NewContextAsync(new() { IgnoreHTTPSErrors = true });69 var page = await context.NewPageAsync();70 await page.GotoAsync(HttpsServer.Prefix + "/mixedcontent.html", new() { WaitUntil = WaitUntilState.DOMContentLoaded });71 Assert.AreEqual(2, page.Frames.Count);72 Assert.AreEqual(3, await page.MainFrame.EvaluateAsync<int>("1 + 2"));73 Assert.AreEqual(5, await page.FirstChildFrame().EvaluateAsync<int>("2 + 3"));74 }75 [PlaywrightTest("ignorehttpserrors.spec.ts", "should work with WebSocket")]76 public async Task ShouldWorkWithWebSocket()77 {78 HttpsServer.SendOnWebSocketConnection("incoming");79 await using var context = await Browser.NewContextAsync(new() { IgnoreHTTPSErrors = true });80 var page = await context.NewPageAsync();81 string value = await page.EvaluateAsync<string>(@"endpoint => {82 let cb;83 const result = new Promise(f => cb = f);84 const ws = new WebSocket(endpoint);...
BinaryHttpClientTest.cs
Source:BinaryHttpClientTest.cs
1// Licensed to the .NET Foundation under one or more agreements.2// The .NET Foundation licenses this file to you under the MIT license.3using System;4using System.Linq;5using System.Threading.Tasks;6using BasicTestApp.HttpClientTest;7using Microsoft.AspNetCore.BrowserTesting;8using Microsoft.AspNetCore.Components.E2ETest.Infrastructure.ServerFixtures;9using Microsoft.AspNetCore.Components.E2ETest.Infrastructure;10using Microsoft.AspNetCore.Testing;11using PlaywrightSharp;12using TestServer;13using Xunit;14using Xunit.Abstractions;15namespace Microsoft.AspNetCore.Components.E2ETest.Tests16{17 public class BinaryHttpClientTest : PlaywrightTestBase,18 IClassFixture<BasicTestAppServerSiteFixture<CorsStartup>>,19 IClassFixture<DevHostServerFixture<BasicTestApp.Program>>20 {21 private readonly DevHostServerFixture<BasicTestApp.Program> _devHostServerFixture;22 readonly ServerFixture _apiServerFixture;23 //IWebElement _appElement;24 //IWebElement _responseStatus;25 //IWebElement _responseStatusText;26 //IWebElement _testOutcome;27 public BinaryHttpClientTest(28 DevHostServerFixture<BasicTestApp.Program> devHostServerFixture,29 BasicTestAppServerSiteFixture<CorsStartup> apiServerFixture,30 ITestOutputHelper output)31 : base(output)32 {33 _devHostServerFixture = devHostServerFixture;34 _devHostServerFixture.PathBase = "/subdir";35 _apiServerFixture = apiServerFixture;36 }37 //protected override void InitializeAsyncCore()38 //{39 // //Browser.Navigate(_devHostServerFixture.RootUri, "/subdir", noReload: true);40 // //_appElement = Browser.MountTestComponent<BinaryHttpRequestsComponent>();41 //}42 [Fact]43 public async Task CanSendAndReceiveBytes()44 {45 if (BrowserManager.IsAvailable(BrowserKind.Chromium))46 {47 await using var browser = await BrowserManager.GetBrowserInstance(BrowserKind.Chromium, BrowserContextInfo);48 var page = await browser.NewPageAsync();49 await page.GoToAsync(_devHostServerFixture.RootUri + "/subdir/api/data");50/* var socket = BrowserContextInfo.Pages[page].WebSockets.SingleOrDefault() ??51 (await page.WaitForEventAsync(PageEvent.WebSocket)).WebSocket;52 // Receive render batch53 await socket.WaitForEventAsync(WebSocketEvent.FrameReceived);54 await socket.WaitForEventAsync(WebSocketEvent.FrameSent);55 // JS interop call to intercept navigation56 await socket.WaitForEventAsync(WebSocketEvent.FrameReceived);57 await socket.WaitForEventAsync(WebSocketEvent.FrameSent);58 await page.WaitForSelectorAsync("ul");*/59 await page.CloseAsync();60 }61 //IssueRequest("/subdir/api/data");62 //Assert.Equal("OK", _responseStatus.Text);63 //Assert.Equal("OK", _responseStatusText.Text);64 //Assert.Equal("", _testOutcome.Text);65 }66 private void IssueRequest()67 {68 //var targetUri = new Uri(_apiServerFixture.RootUri, relativeUri);69 //SetValue("request-uri", targetUri.AbsoluteUri);70 //_appElement.FindElement(By.Id("send-request")).Click();71 //_responseStatus = Browser.Exists(By.Id("response-status"));72 //_responseStatusText = _appElement.FindElement(By.Id("response-status-text"));73 //_testOutcome = _appElement.FindElement(By.Id("test-outcome"));74 }75 }76}...
GotoAsync
Using AI Code Generation
1using Microsoft.Playwright;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions10 {11 });12 var page = await browser.NewPageAsync();13 }14 }15}
GotoAsync
Using AI Code Generation
1using Microsoft.Playwright;2using System.Threading.Tasks;3{4 {5 static async Task Main(string[] args)6 {7 using var playwright = await Playwright.CreateAsync();8 await using var browser = await playwright.Chromium.LaunchAsync();9 var context = await browser.NewContextAsync();10 var page = await context.NewPageAsync();11 }12 }13}
GotoAsync
Using AI Code Generation
1using Microsoft.Playwright;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Webkit.LaunchAsync(new BrowserTypeLaunchOptions10 {11 });12 var page = await browser.NewPageAsync();13 await page.GotoAsync(url);14 await page.ClickAsync("#L2AGLb");15 await page.GotoAsync("https
GotoAsync
Using AI Code Generation
1await page.GoBackAsync();2await page.GoBackAsync();3await page.GoBackAsync();4await page.GoForwardAsync();5await page.GoForwardAsync();6await page.GoForwardAsync();7await page.ReloadAsync();8await page.WaitForNavigationAsync();9await page.WaitForLoadStateAsync(LoadState.Load);10await page.WaitForRequestAsync("**/*.css");11await page.WaitForResponseAsync("**/*.css");12await page.WaitForEventAsync(PageEvent.Load);13await page.WaitForFunctionAsync("() => window.innerWidth < 100");14await page.WaitForSelectorAsync("input");
GotoAsync
Using AI Code Generation
1await frame.WaitForSelectorAsync("input[title='Search']");2await frame.WaitForSelectorAsync("input[title='Search']", new WaitForSelectorOptions { Timeout = 30000 });3await frame.WaitForSelectorAsync("input[title='Search']");4await frame.WaitForSelectorAsync("input[title='Search']", new WaitForSelectorOptions { Timeout = 30000 });5await frame.WaitForSelectorAsync("input[title='Search']");6await frame.WaitForSelectorAsync("input[title='Search']", new WaitForSelectorOptions { Timeout = 30000 });7await frame.WaitForSelectorAsync("input[title='Search']");8await frame.WaitForSelectorAsync("input[title='Search']", new WaitForSelectorOptions { Timeout = 30000 });9await frame.WaitForSelectorAsync("input[title='Search']");10await frame.WaitForSelectorAsync("input[title='Search']", new WaitForSelectorOptions { Timeout = 30000 });11await frame.WaitForSelectorAsync("input[title='Search']");12await frame.WaitForSelectorAsync("input[title='Search']", new WaitForSelectorOptions { Timeout = 30000 });13await frame.WaitForSelectorAsync("input[title='Search']");14await frame.WaitForSelectorAsync("input[title='Search']", new WaitForSelectorOptions { Timeout = 30000 });15await frame.WaitForSelectorAsync("input[title='Search']");16await frame.WaitForSelectorAsync("input[title='Search']", new WaitForSelectorOptions { Timeout = 30000 });17await frame.WaitForSelectorAsync("input[title='Search']");18await frame.WaitForSelectorAsync("input[title='Search']", new WaitForSelectorOptions { Timeout = 30000 });
GotoAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using Microsoft.Playwright;4using System.Threading;5{6 {7 static async Task Main(string[] args)8 {9 using var playwright = await Playwright.CreateAsync();10 await using var browser = await playwright.Chromium.LaunchAsync(new LaunchOptions { Headless = false });11 var page = await browser.NewPageAsync();12 Thread.Sleep(5000);13 Thread.Sleep(5000);14 Thread.Sleep(5000);15 await browser.CloseAsync();16 }17 }18}
GotoAsync
Using AI Code Generation
1public async Task GotoAsync(string url, string referer, string userAgent, bool acceptDownloads)2{3 await _frame.GotoAsync(url, new GotoOptions { Referer = referer, UserAgent = userAgent, AcceptDownloads = acceptDownloads });4}5public async Task WaitForSelectorAsync(string selector, int timeout)6{7 await _frame.WaitForSelectorAsync(selector, new WaitForSelectorOptions { Timeout = timeout });8}9public async Task WaitForXPathAsync(string selector, int timeout)10{11 await _frame.WaitForXPathAsync(selector, new WaitForSelectorOptions { Timeout = timeout });12}13public async Task SetContentAsync(string html, int timeout)14{15 await _frame.SetContentAsync(html, new NavigationOptions { Timeout = timeout });16}17public async Task SetInputFilesAsync(string selector, string[] files, int timeout)18{19 var element = await _frame.QuerySelectorAsync(selector, new WaitForSelectorOptions { Timeout = timeout });20 await element.SetInputFilesAsync(files);21}22public async Task ClickAsync(string selector, int timeout)23{24 var element = await _frame.QuerySelectorAsync(selector, new WaitForSelectorOptions { Timeout = timeout });25 await element.ClickAsync();26}27public async Task FillAsync(string selector, string value, int timeout)28{29 var element = await _frame.QuerySelectorAsync(selector, new WaitForSelectorOptions { Timeout = timeout });30 await element.FillAsync(value);31}32public async Task PressAsync(string selector, string key, int timeout)33{34 var element = await _frame.QuerySelectorAsync(selector, new WaitForSelectorOptions { Timeout = timeout });35 await element.PressAsync(key);36}
GotoAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using Microsoft.Playwright;4using Microsoft.Playwright.Core;5{6 {7 static async Task Main(string[] args)8 {9 await using var playwright = await Playwright.CreateAsync();10 await using var browser = await playwright.Chromium.LaunchAsync();11 var context = await browser.NewContextAsync();12 var page = await context.NewPageAsync();13 await browser.CloseAsync();14 }15 }16}
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!