Best Playwright-dotnet code snippet using Microsoft.Playwright.NUnit.Worker.new
PageGotoTests.cs
Source:PageGotoTests.cs
...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}...
WorkersTests.cs
Source:WorkersTests.cs
...45 }46 [PlaywrightTest("workers.spec.ts", "should emit created and destroyed events")]47 public async Task ShouldEmitCreatedAndDestroyedEvents()48 {49 var workerCreatedTcs = new TaskCompletionSource<IWorker>();50 Page.Worker += (_, e) => workerCreatedTcs.TrySetResult(e);51 var workerObj = await Page.EvaluateHandleAsync("() => new Worker(URL.createObjectURL(new Blob(['1'], {type: 'application/javascript'})))");52 var worker = await workerCreatedTcs.Task;53 var workerThisObj = await worker.EvaluateHandleAsync("() => this");54 var workerDestroyedTcs = new TaskCompletionSource<IWorker>();55 worker.Close += (sender, _) => workerDestroyedTcs.TrySetResult((IWorker)sender);56 await Page.EvaluateAsync("workerObj => workerObj.terminate()", workerObj);57 Assert.AreEqual(worker, await workerDestroyedTcs.Task);58 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => workerThisObj.GetPropertyAsync("self"));59 StringAssert.IsMatch("(Worker was closed)|(Target closed)", exception.Message);60 }61 [PlaywrightTest("workers.spec.ts", "should report console logs")]62 public async Task ShouldReportConsoleLogs()63 {64 var (message, _) = await TaskUtils.WhenAll(65 Page.WaitForConsoleMessageAsync(),66 Page.EvaluateAsync("() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], {type: 'application/javascript'})))")67 );68 Assert.AreEqual("1", message.Text);69 }70 [PlaywrightTest("workers.spec.ts", "should have JSHandles for console logs")]71 public async Task ShouldHaveJSHandlesForConsoleLogs()72 {73 var consoleTcs = new TaskCompletionSource<IConsoleMessage>();74 Page.Console += (_, e) => consoleTcs.TrySetResult(e);75 await Page.EvaluateAsync("() => new Worker(URL.createObjectURL(new Blob(['console.log(1,2,3,this)'], {type: 'application/javascript'})))");76 var log = await consoleTcs.Task;77 if (TestConstants.IsFirefox)78 {79 Assert.AreEqual("1 2 3 JSHandle@object", log.Text);80 }81 else82 {83 Assert.AreEqual("1 2 3 DedicatedWorkerGlobalScope", log.Text);84 }85 Assert.AreEqual(4, log.Args.Count());86 string json = await (await log.Args.ElementAt(3).GetPropertyAsync("origin")).JsonValueAsync<string>();87 Assert.AreEqual("null", json);88 }89 [PlaywrightTest("workers.spec.ts", "should evaluate")]90 public async Task ShouldEvaluate()91 {92 var workerCreatedTask = Page.WaitForWorkerAsync();93 await Page.EvaluateAsync("() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], {type: 'application/javascript'})))");94 await workerCreatedTask;95 Assert.AreEqual(2, await workerCreatedTask.Result.EvaluateAsync<int>("1+1"));96 }97 [PlaywrightTest("workers.spec.ts", "should report errors")]98 public async Task ShouldReportErrors()99 {100 var errorTcs = new TaskCompletionSource<string>();101 Page.PageError += (_, e) => errorTcs.TrySetResult(e);102 await Page.EvaluateAsync(@"() => new Worker(URL.createObjectURL(new Blob([`103 setTimeout(() => {104 // Do a console.log just to check that we do not confuse it with an error.105 console.log('hey');106 throw new Error('this is my error');107 })108 `], {type: 'application/javascript'})))");109 string errorLog = await errorTcs.Task;110 StringAssert.Contains("this is my error", errorLog);111 }112 [PlaywrightTest("workers.spec.ts", "should clear upon navigation")]113 public async Task ShouldClearUponNavigation()114 {115 await Page.GotoAsync(Server.EmptyPage);116 var workerCreatedTask = Page.WaitForWorkerAsync();117 await Page.EvaluateAsync("() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], { type: 'application/javascript' })))");118 var worker = await workerCreatedTask;119 Assert.That(Page.Workers, Has.Count.EqualTo(1));120 bool destroyed = false;121 worker.Close += (_, _) => destroyed = true;122 await Page.GotoAsync(Server.Prefix + "/one-style.html");123 Assert.True(destroyed);124 Assert.IsEmpty(Page.Workers);125 }126 [PlaywrightTest("workers.spec.ts", "should clear upon cross-process navigation")]127 public async Task ShouldClearUponCrossProcessNavigation()128 {129 await Page.GotoAsync(Server.EmptyPage);130 var workerCreatedTask = Page.WaitForWorkerAsync();131 await Page.EvaluateAsync("() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], { type: 'application/javascript' })))");132 var worker = await workerCreatedTask;133 Assert.That(Page.Workers, Has.Count.EqualTo(1));134 bool destroyed = false;135 worker.Close += (_, _) => destroyed = true;136 await Page.GotoAsync(Server.CrossProcessPrefix + "/empty.html");137 Assert.True(destroyed);138 Assert.IsEmpty(Page.Workers);139 }140 [PlaywrightTest("workers.spec.ts", "should report network activity")]141 public async Task ShouldReportNetworkActivity()142 {143 var (worker, _) = await TaskUtils.WhenAll(144 Page.WaitForWorkerAsync(),145 Page.GotoAsync(Server.Prefix + "/worker/worker.html")146 );147 string url = Server.Prefix + "/one-style.css";148 var requestTask = Page.WaitForRequestAsync(url);149 var responseTask = Page.WaitForResponseAsync(url);150 await worker.EvaluateAsync<JsonElement>("url => fetch(url).then(response => response.text()).then(console.log)", url);151 await TaskUtils.WhenAll(requestTask, responseTask);152 Assert.AreEqual(url, requestTask.Result.Url);153 Assert.AreEqual(requestTask.Result, responseTask.Result.Request);154 Assert.True(responseTask.Result.Ok);155 }156 [PlaywrightTest("workers.spec.ts", "should report network activity on worker creation")]157 public async Task ShouldReportNetworkActivityOnWorkerCreation()158 {159 await Page.GotoAsync(Server.EmptyPage);160 string url = Server.Prefix + "/one-style.css";161 var requestTask = Page.WaitForRequestAsync(url);162 var responseTask = Page.WaitForResponseAsync(url);163 await Page.EvaluateAsync(@"url => new Worker(URL.createObjectURL(new Blob([`164 fetch(""${url}"").then(response => response.text()).then(console.log);165 `], { type: 'application/javascript'})))", url);166 await TaskUtils.WhenAll(requestTask, responseTask);167 Assert.AreEqual(url, requestTask.Result.Url);168 Assert.AreEqual(requestTask.Result, responseTask.Result.Request);169 Assert.True(responseTask.Result.Ok);170 }171 [PlaywrightTest("workers.spec.ts", "should format number using context locale")]172 public async Task ShouldFormatNumberUsingContextLocale()173 {174 await using var context = await Browser.NewContextAsync(new() { Locale = "ru-RU" });175 var page = await context.NewPageAsync();176 await page.GotoAsync(Server.EmptyPage);177 var (worker, _) = await TaskUtils.WhenAll(178 page.WaitForWorkerAsync(),179 page.EvaluateAsync("() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], {type: 'application/javascript'})))"));180 Assert.AreEqual("10\u00A0000,2", await worker.EvaluateAsync<string>("() => (10000.20).toLocaleString()"));181 }182 }183}...
InterceptionTests.cs
Source:InterceptionTests.cs
...54 }55 [PlaywrightTest("interception.spec.ts", "should work with ignoreHTTPSErrors")]56 public async Task ShouldWorkWithIgnoreHTTPSErrors()57 {58 var context = await Browser.NewContextAsync(new()59 {60 IgnoreHTTPSErrors = true61 });62 var page = await context.NewPageAsync();63 await page.RouteAsync("**/*", (route) => route.ContinueAsync());64 var response = await page.GotoAsync(HttpsServer.EmptyPage);65 Assert.AreEqual((int)HttpStatusCode.OK, response.Status);66 await context.CloseAsync();67 }68 [PlaywrightTest("interception.spec.ts", "should work with navigation")]69 public async Task ShouldWorkWithNavigation()70 {71 var requests = new Dictionary<string, IRequest>();72 await Page.RouteAsync("**/*", (route) =>73 {74 requests.Add(route.Request.Url.Split('/').Last(), route.Request);75 route.ContinueAsync();76 });77 Server.SetRedirect("/rrredirect", "/frames/one-frame.html");78 await Page.GotoAsync(Server.Prefix + "/rrredirect");79 Assert.True(requests["rrredirect"].IsNavigationRequest);80 Assert.True(requests["frame.html"].IsNavigationRequest);81 Assert.False(requests["script.js"].IsNavigationRequest);82 Assert.False(requests["style.css"].IsNavigationRequest);83 }84 [PlaywrightTest("interception.spec.ts", "should intercept after a service worker")]85 public async Task ShouldInterceptAfterAServiceWorker()86 {87 await Page.GotoAsync(Server.Prefix + "/serviceworkers/fetchdummy/sw.html");88 await Page.EvaluateAsync("() => window.activationPromise");89 string swResponse = await Page.EvaluateAsync<string>("() => fetchDummy('foo')");90 Assert.AreEqual("responseFromServiceWorker:foo", swResponse);91 await Page.RouteAsync("**/foo", (route) =>92 {93 int slash = route.Request.Url.LastIndexOf("/");94 string name = route.Request.Url.Substring(slash + 1);95 route.FulfillAsync(new() { Status = (int)HttpStatusCode.OK, Body = "responseFromInterception:" + name, ContentType = "text/css" });96 });97 string swResponse2 = await Page.EvaluateAsync<string>("() => fetchDummy('foo')");98 Assert.AreEqual("responseFromServiceWorker:foo", swResponse2);99 string nonInterceptedResponse = await Page.EvaluateAsync<string>("() => fetchDummy('passthrough')");100 Assert.AreEqual("FAILURE: Not Found", nonInterceptedResponse);101 }102 }103}...
PageEventRequestTests.cs
Source:PageEventRequestTests.cs
...32 {33 [PlaywrightTest("page-event-request.spec.ts", "should fire for navigation requests")]34 public async Task ShouldFireForNavigationRequests()35 {36 var requests = new List<IRequest>();37 Page.Request += (_, e) => requests.Add(e);38 await Page.GotoAsync(Server.EmptyPage);39 Assert.That(requests, Has.Count.EqualTo(1));40 }41 [PlaywrightTest("page-event-request.spec.ts", "should fire for iframes")]42 public async Task ShouldFireForIframes()43 {44 var requests = new List<IRequest>();45 Page.Request += (_, e) => requests.Add(e);46 await Page.GotoAsync(Server.EmptyPage);47 await FrameUtils.AttachFrameAsync(Page, "frame1", Server.EmptyPage);48 Assert.AreEqual(2, requests.Count);49 }50 [PlaywrightTest("page-event-request.spec.ts", "should fire for fetches")]51 public async Task ShouldFireForFetches()52 {53 var requests = new List<IRequest>();54 Page.Request += (_, e) => requests.Add(e);55 await Page.GotoAsync(Server.EmptyPage);56 await Page.EvaluateAsync("fetch('/empty.html')");57 Assert.AreEqual(2, requests.Count);58 }59 [PlaywrightTest("page-event-request.spec.ts", "should report requests and responses handled by service worker")]60 public async Task ShouldReportRequestsAndResponsesHandledByServiceWorker()61 {62 await Page.GotoAsync(Server.Prefix + "/serviceworkers/fetchdummy/sw.html");63 await Page.EvaluateAsync("() => window.activationPromise");64 var (request, swResponse) = await TaskUtils.WhenAll(65 Page.WaitForRequestAsync("**/*"),66 Page.EvaluateAsync<string>("() => fetchDummy('foo')"));67 Assert.AreEqual("responseFromServiceWorker:foo", swResponse);...
WorkerAwareTest.cs
Source:WorkerAwareTest.cs
...35 internal class Worker36 {37 private static int _lastWorkedIndex = 0;38 public int WorkerIndex = Interlocked.Increment(ref _lastWorkedIndex);39 public Dictionary<string, IWorkerService> Services = new();40 }41 private static readonly ConcurrentStack<Worker> _allWorkers = new();42 private Worker _currentWorker;43 public int WorkerIndex { get; internal set; }44 public async Task<T> RegisterService<T>(string name, Func<Task<T>> factory) where T : class, IWorkerService45 {46 if (!_currentWorker.Services.ContainsKey(name))47 {48 _currentWorker.Services[name] = await factory().ConfigureAwait(false);49 }50 return _currentWorker.Services[name] as T;51 }52 [SetUp]53 public void WorkerSetup()54 {55 if (!_allWorkers.TryPop(out _currentWorker))56 {57 _currentWorker = new();58 }59 WorkerIndex = _currentWorker.WorkerIndex;60 }61 [TearDown]62 public async Task WorkerTeardown()63 {64 if (TestOk())65 {66 foreach (var kv in _currentWorker.Services)67 {68 await kv.Value.ResetAsync().ConfigureAwait(false);69 }70 _allWorkers.Push(_currentWorker);71 }...
BrowserTypeConnectOverCDPTests.cs
Source:BrowserTypeConnectOverCDPTests.cs
...35 [Skip(SkipAttribute.Targets.Firefox, SkipAttribute.Targets.Webkit)]36 public async Task ShouldConnectToAnExistingCDPSession()37 {38 int port = 9393 + WorkerIndex;39 IBrowser browserServer = await BrowserType.LaunchAsync(new() { Args = new[] { $"--remote-debugging-port={port}" } });40 try41 {42 IBrowser cdpBrowser = await BrowserType.ConnectOverCDPAsync($"http://localhost:{port}/");43 var contexts = cdpBrowser.Contexts;44 Assert.AreEqual(1, cdpBrowser.Contexts.Count);45 var page = await cdpBrowser.Contexts[0].NewPageAsync();46 Assert.AreEqual(2, await page.EvaluateAsync<int>("1 + 1"));47 await cdpBrowser.CloseAsync();48 }49 finally50 {51 await browserServer.CloseAsync();52 }53 }54 [PlaywrightTest("chromium/chromium.spec.ts", "should send extra headers with connect request")]55 [Skip(SkipAttribute.Targets.Firefox, SkipAttribute.Targets.Webkit)]56 public async Task ShouldSendExtraHeadersWithConnectRequest()57 {58 var waitForRequest = Server.WaitForWebSocketConnectionRequest();59 BrowserType.ConnectOverCDPAsync($"ws://localhost:{Server.Port}/ws", new()60 {61 Headers = new Dictionary<string, string> {62 { "x-foo-bar", "fookek" }63 },64 }).IgnoreException();65 var req = await waitForRequest;66 Assert.AreEqual("fookek", req.Headers["x-foo-bar"]);67 StringAssert.Contains("Playwright", req.Headers["user-agent"]);68 }69 }70}
HttpService.cs
Source:HttpService.cs
...34 {35 var workerIndex = test.WorkerIndex;36 return test.RegisterService("Http", async () =>37 {38 var http = new HttpService39 {40 Server = SimpleServer.Create(8907 + workerIndex * 2, TestUtils.FindParentDirectory("Playwright.Tests.TestServer")),41 HttpsServer = SimpleServer.CreateHttps(8907 + workerIndex * 2 + 1, TestUtils.FindParentDirectory("Playwright.Tests.TestServer"))42 };43 await Task.WhenAll(http.Server.StartAsync(), http.HttpsServer.StartAsync());44 return http;45 });46 }47 public Task ResetAsync()48 {49 Server.Reset();50 HttpsServer.Reset();51 return Task.CompletedTask;52 }...
BrowserService.cs
Source:BrowserService.cs
...29 {30 public IBrowser Browser { get; internal set; }31 public static Task<BrowserService> Register(WorkerAwareTest test, IBrowserType browserType)32 {33 return test.RegisterService("Browser", async () => new BrowserService34 {35 Browser = await browserType.LaunchAsync(new()36 {37 Headless = Environment.GetEnvironmentVariable("HEADED") != "1"38 }).ConfigureAwait(false)39 });40 }41 public Task ResetAsync() => Task.CompletedTask;42 public Task DisposeAsync() => Browser.CloseAsync();43 };44}
new
Using AI Code Generation
1var playwright = await Microsoft.Playwright.NUnit.Worker.CreatePlaywright();2var browser = await playwright.Chromium.LaunchAsync(new Microsoft.Playwright.LaunchOptions { Headless = false });3var context = await browser.NewContextAsync();4var page = await context.NewPageAsync();5await page.ScreenshotAsync(new Microsoft.Playwright.ScreenshotOptions { Path = "screenshot.png" });6await browser.CloseAsync();7var playwright = await Microsoft.Playwright.NUnit.Worker.CreatePlaywright();8var browser = await playwright.Firefox.LaunchAsync(new Microsoft.Playwright.LaunchOptions { Headless = false });9var context = await browser.NewContextAsync();10var page = await context.NewPageAsync();11await page.ScreenshotAsync(new Microsoft.Playwright.ScreenshotOptions { Path = "screenshot.png" });12await browser.CloseAsync();13var playwright = await Microsoft.Playwright.NUnit.Worker.CreatePlaywright();14var browser = await playwright.Webkit.LaunchAsync(new Microsoft.Playwright.LaunchOptions { Headless = false });15var context = await browser.NewContextAsync();16var page = await context.NewPageAsync();17await page.ScreenshotAsync(new Microsoft.Playwright.ScreenshotOptions { Path = "screenshot.png" });18await browser.CloseAsync();19var playwright = await Microsoft.Playwright.NUnit.Worker.CreatePlaywright();20var browser = await playwright.Chromium.LaunchAsync(new Microsoft.Playwright.LaunchOptions { Headless = false });21var context = await browser.NewContextAsync();22var page = await context.NewPageAsync();23await page.ScreenshotAsync(new Microsoft.Playwright.ScreenshotOptions { Path = "screenshot.png" });24await browser.CloseAsync();25var playwright = await Microsoft.Playwright.NUnit.Worker.CreatePlaywright();26var browser = await playwright.Firefox.LaunchAsync(new Microsoft.Playwright.L
new
Using AI Code Generation
1using Microsoft.Playwright.NUnit;2using NUnit.Framework;3using System;4using System.Collections.Generic;5using System.Text;6using System.Threading.Tasks;7{8 {9 public async Task Test1()10 {11 var page = await NewPage();12 await page.TypeAsync("input[name=q]", "Hello World");13 await page.PressAsync("input[name=q]", "Enter");14 await page.ScreenshotAsync(new Microsoft.Playwright.PageScreenshotOptions { Path = "screenshot.png" });15 }16 }17}
new
Using AI Code Generation
1using Microsoft.Playwright.NUnit;2using NUnit.Framework;3using System;4using System.Collections.Generic;5using System.Text;6using System.Threading.Tasks;7{8 {9 public async Task Test1()10 {11 using var playwright = await PlaywrightWorker.CreateAsync();12 var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Headless = false });13 var page = await browser.NewPageAsync();14 }15 }16}17using Microsoft.Playwright.NUnit;18using NUnit.Framework;19using System;20using System.Collections.Generic;21using System.Text;22using System.Threading.Tasks;23{24 {25 public async Task Test1()26 {27 using var playwright = await PlaywrightWorker.CreateAsync();28 var browser = await playwright.Firefox.LaunchAsync(new BrowserTypeLaunchOptions { Headless = false });29 var page = await browser.NewPageAsync();30 }31 }32}33using Microsoft.Playwright.NUnit;34using NUnit.Framework;35using System;36using System.Collections.Generic;37using System.Text;38using System.Threading.Tasks;39{40 {41 public async Task Test1()42 {43 using var playwright = await PlaywrightWorker.CreateAsync();44 var browser = await playwright.Webkit.LaunchAsync(new BrowserTypeLaunchOptions { Headless = false });45 var page = await browser.NewPageAsync();46 }47 }48}49using Microsoft.Playwright.NUnit;50using NUnit.Framework;51using System;52using System.Collections.Generic;53using System.Text;54using System.Threading.Tasks;55{56 {57 public async Task Test1()58 {59 using var playwright = await PlaywrightWorker.CreateAsync();60 var browser = await playwright.Webkit.LaunchAsync(new BrowserTypeLaunchOptions { Head
new
Using AI Code Generation
1using Microsoft.Playwright.NUnit;2using NUnit.Framework;3{4 {5 public async Task TestMethod()6 {7 await Page.ScreenshotAsync("test.png");8 }9 }10}11using Microsoft.Playwright.NUnit;12using NUnit.Framework;13{14 {15 public async Task TestMethod()16 {17 await Page.ScreenshotAsync("test.png");18 }19 }20}21using Microsoft.Playwright.NUnit;22using NUnit.Framework;23{24 {25 public async Task TestMethod()26 {27 await Page.ScreenshotAsync("test.png");28 }29 }30}31using Microsoft.Playwright.NUnit;32using NUnit.Framework;33{34 {35 public async Task TestMethod()36 {37 await Page.ScreenshotAsync("test.png");38 }39 }40}41using Microsoft.Playwright.NUnit;42using NUnit.Framework;43{44 {45 public async Task TestMethod()46 {47 await Page.ScreenshotAsync("test.png");48 }49 }50}51using Microsoft.Playwright.NUnit;52using NUnit.Framework;53{
new
Using AI Code Generation
1using Microsoft.Playwright.NUnit.Worker;2using NUnit.Framework;3using System;4using System.Collections.Generic;5using System.Text;6{7 {8 public void Test1()9 {10 Worker.RunTest("Test1", "Test1", "Test1");11 }12 }13}
new
Using AI Code Generation
1var worker = Microsoft.Playwright.NUnit.Worker.Instance;2var browser = worker.GetBrowser();3var context = worker.GetContext();4var page = worker.GetPage();5var frame = worker.GetFrame();6var elementHandle = worker.GetElementHandle();7var jsHandle = worker.GetJsHandle();8var consoleMessage = worker.GetConsoleMessage();9var dialog = worker.GetDialog();10var download = worker.GetDownload();11var request = worker.GetRequest();12var response = worker.GetResponse();13var route = worker.GetRoute();14var webSocket = worker.GetWebSocket();15var webWorker = worker.GetWebWorker();16var video = worker.GetVideo();
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!!