How to use TestUtils class of Microsoft.Playwright.Tests package

Best Playwright-dotnet code snippet using Microsoft.Playwright.Tests.TestUtils

BrowserContextViewportTests.cs

Source:BrowserContextViewportTests.cs Github

copy

Full Screen

...29    public class BrowserContextViewportTests : PageTestEx30    {31        [PlaywrightTest("browsercontext-viewport.spec.ts", "should get the proper default viewport size")]32        public Task ShouldGetTheProperDefaultViewPortSize()33            => TestUtils.VerifyViewportAsync(Page, 1280, 720);34        [PlaywrightTest("browsercontext-viewport.spec.ts", "should set the proper viewport size")]35        public async Task ShouldSetTheProperViewportSize()36        {37            await TestUtils.VerifyViewportAsync(Page, 1280, 720);38            await Page.SetViewportSizeAsync(123, 456);39            await TestUtils.VerifyViewportAsync(Page, 123, 456);40        }41        [PlaywrightTest("browsercontext-viewport.spec.ts", "should emulate device width")]42        public async Task ShouldEmulateDeviceWidth()43        {44            await TestUtils.VerifyViewportAsync(Page, 1280, 720);45            await Page.SetViewportSizeAsync(200, 200);46            Assert.AreEqual(200, await Page.EvaluateAsync<int>("window.innerWidth"));47            Assert.True(await Page.EvaluateAsync<bool?>("() => matchMedia('(min-device-width: 100px)').matches"));48            Assert.False(await Page.EvaluateAsync<bool?>("() => matchMedia('(min-device-width: 300px)').matches"));49            Assert.False(await Page.EvaluateAsync<bool?>("() => matchMedia('(max-device-width: 100px)').matches"));50            Assert.True(await Page.EvaluateAsync<bool?>("() => matchMedia('(max-device-width: 300px)').matches"));51            Assert.False(await Page.EvaluateAsync<bool?>("() => matchMedia('(device-width: 500px)').matches"));52            Assert.True(await Page.EvaluateAsync<bool?>("() => matchMedia('(device-width: 200px)').matches"));53            await Page.SetViewportSizeAsync(500, 500);54            Assert.True(await Page.EvaluateAsync<bool?>("() => matchMedia('(min-device-width: 400px)').matches"));55            Assert.False(await Page.EvaluateAsync<bool?>("() => matchMedia('(min-device-width: 600px)').matches"));56            Assert.False(await Page.EvaluateAsync<bool?>("() => matchMedia('(max-device-width: 400px)').matches"));57            Assert.True(await Page.EvaluateAsync<bool?>("() => matchMedia('(max-device-width: 600px)').matches"));58            Assert.False(await Page.EvaluateAsync<bool?>("() => matchMedia('(device-width: 200px)').matches"));59            Assert.True(await Page.EvaluateAsync<bool?>("() => matchMedia('(device-width: 500px)').matches"));60        }61        [PlaywrightTest("browsercontext-viewport.spec.ts", "should emulate device height")]62        public async Task ShouldEmulateDeviceHeight()63        {64            await TestUtils.VerifyViewportAsync(Page, 1280, 720);65            await Page.SetViewportSizeAsync(200, 200);66            Assert.AreEqual(200, await Page.EvaluateAsync<int>("window.innerWidth"));67            Assert.True(await Page.EvaluateAsync<bool?>("() => matchMedia('(min-device-height: 100px)').matches"));68            Assert.False(await Page.EvaluateAsync<bool?>("() => matchMedia('(min-device-height: 300px)').matches"));69            Assert.False(await Page.EvaluateAsync<bool?>("() => matchMedia('(max-device-height: 100px)').matches"));70            Assert.True(await Page.EvaluateAsync<bool?>("() => matchMedia('(max-device-height: 300px)').matches"));71            Assert.False(await Page.EvaluateAsync<bool?>("() => matchMedia('(device-height: 500px)').matches"));72            Assert.True(await Page.EvaluateAsync<bool?>("() => matchMedia('(device-height: 200px)').matches"));73            await Page.SetViewportSizeAsync(500, 500);74            Assert.True(await Page.EvaluateAsync<bool?>("() => matchMedia('(min-device-height: 400px)').matches"));75            Assert.False(await Page.EvaluateAsync<bool?>("() => matchMedia('(min-device-height: 600px)').matches"));76            Assert.False(await Page.EvaluateAsync<bool?>("() => matchMedia('(max-device-height: 400px)').matches"));77            Assert.True(await Page.EvaluateAsync<bool?>("() => matchMedia('(max-device-height: 600px)').matches"));78            Assert.False(await Page.EvaluateAsync<bool?>("() => matchMedia('(device-height: 200px)').matches"));79            Assert.True(await Page.EvaluateAsync<bool?>("() => matchMedia('(device-height: 500px)').matches"));80        }81        [PlaywrightTest("browsercontext-viewport.spec.ts", "should not have touch by default")]82        public async Task ShouldNotHaveTouchByDefault()83        {84            await Page.GotoAsync(Server.Prefix + "/mobile.html");85            Assert.False(await Page.EvaluateAsync<bool>("'ontouchstart' in window"));86            await Page.GotoAsync(Server.Prefix + "/detect-touch.html");87            Assert.AreEqual("NO", await Page.EvaluateAsync<string>("document.body.textContent.trim()"));88        }89        [PlaywrightTest("browsercontext-viewport.spec.ts", "should support touch with null viewport")]90        public async Task ShouldSupportTouchWithNullViewport()91        {92            await using var context = await Browser.NewContextAsync(new() { ViewportSize = null, HasTouch = true });93            var page = await context.NewPageAsync();94            await page.GotoAsync(Server.Prefix + "/mobile.html");95            Assert.True(await page.EvaluateAsync<bool>("'ontouchstart' in window"));96        }97        [PlaywrightTest("browsercontext-viewport.spec.ts", "should respect screensize")]98        [Skip(SkipAttribute.Targets.Firefox)]99        public async Task ShouldSupportScreenSize()100        {101            await using var context = await Browser.NewContextAsync(new()102            {103                ScreenSize = new ScreenSize()104                {105                    Width = 750,106                    Height = 1334,107                },108                ViewportSize = new ViewportSize()109                {110                    Width = 375,111                    Height = 667112                }113            });114            var page = await context.NewPageAsync();115            Assert.True(await page.EvaluateAsync<bool?>("() => matchMedia('(device-height: 1334px)').matches"));116            Assert.True(await page.EvaluateAsync<bool?>("() => matchMedia('(device-width: 750px)').matches"));117            await TestUtils.VerifyViewportAsync(page, 375, 667);118        }119        [PlaywrightTest("browsercontext-viewport.spec.ts", "should ignore screensize when viewport is null")]120        [Skip(SkipAttribute.Targets.Firefox)]121        public async Task ShouldIgnoreScreensizeWhenViewportIsNull()122        {123            await using var context = await Browser.NewContextAsync(new()124            {125                ScreenSize = new ScreenSize()126                {127                    Width = 750,128                    Height = 1334,129                },130                ViewportSize = ViewportSize.NoViewport131            });...

Full Screen

Full Screen

SelectorsRegisterTests.cs

Source:SelectorsRegisterTests.cs Github

copy

Full Screen

...42                queryAll(root, selector) {43                  return Array.from(root.querySelectorAll(selector));44                }45            })";46            await TestUtils.RegisterEngineAsync(Playwright, "tag", createTagSelector);47            var context = await Browser.NewContextAsync();48            await TestUtils.RegisterEngineAsync(Playwright, "tag2", createTagSelector);49            var page = await context.NewPageAsync();50            await page.SetContentAsync("<div><span></span></div><div></div>");51            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => page.QuerySelectorAsync("tAG=DIV"));52            StringAssert.Contains("Unknown engine \"tAG\" while parsing selector tAG=DIV", exception.Message);53        }54        [PlaywrightTest("selectors-register.spec.ts", "should work with path")]55        public async Task ShouldWorkWithPath()56        {57            await TestUtils.RegisterEngineWithPathAsync(Playwright, "foo", TestUtils.GetAsset("sectionselectorengine.js"));58            await Page.SetContentAsync("<section></section>");59            Assert.AreEqual("SECTION", await Page.EvalOnSelectorAsync<string>("foo=whatever", "e => e.nodeName"));60        }61        [PlaywrightTest("selectors-register.spec.ts", "should work in main and isolated world")]62        public async Task ShouldWorkInMainAndIsolatedWorld()63        {64            const string createTagSelector = @"({65                create(root, target) { },66                query(root, selector) {67                  return window['__answer'];68                },69                queryAll(root, selector) {70                  return window['__answer'] ? [window['__answer'], document.body, document.documentElement] : [];71                }72            })";73            await TestUtils.RegisterEngineAsync(Playwright, "main", createTagSelector);74            await TestUtils.RegisterEngineAsync(Playwright, "isolated", createTagSelector, true);75            await Page.SetContentAsync("<div><span><section></section></span></div>");76            await Page.EvaluateAsync("() => window['__answer'] = document.querySelector('span')");77            Assert.AreEqual("SPAN", await Page.EvalOnSelectorAsync<string>("main=ignored", "e => e.nodeName"));78            Assert.AreEqual("SPAN", await Page.EvalOnSelectorAsync<string>("css=div >> main=ignored", "e => e.nodeName"));79            Assert.True(await Page.EvalOnSelectorAllAsync<bool>("main=ignored", "es => window['__answer'] !== undefined"));80            Assert.AreEqual(3, await Page.EvalOnSelectorAllAsync<int>("main=ignored", "es => es.filter(e => e).length"));81            Assert.Null(await Page.QuerySelectorAsync("isolated=ignored"));82            Assert.Null(await Page.QuerySelectorAsync("css=div >> isolated=ignored"));83            Assert.True(await Page.EvalOnSelectorAllAsync<bool>("isolated=ignored", "es => window['__answer'] !== undefined"));84            Assert.AreEqual(3, await Page.EvalOnSelectorAllAsync<int>("isolated=ignored", "es => es.filter(e => e).length"));85            Assert.AreEqual("SPAN", await Page.EvalOnSelectorAsync<string>("main=ignored >> isolated=ignored", "e => e.nodeName"));86            Assert.AreEqual("SPAN", await Page.EvalOnSelectorAsync<string>("isolated=ignored >> main=ignored", "e => e.nodeName"));87            Assert.AreEqual("SECTION", await Page.EvalOnSelectorAsync<string>("main=ignored >> css=section", "e => e.nodeName"));88        }89        [PlaywrightTest("selectors-register.spec.ts", "should handle errors")]90        public async Task ShouldHandleErrors()91        {92            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.QuerySelectorAsync("neverregister=ignored"));93            StringAssert.Contains("Unknown engine \"neverregister\" while parsing selector neverregister=ignored", exception.Message);94            const string createDummySelector = @"({95                create(root, target) {96                    return target.nodeName;97                },98                query(root, selector) {99                    return root.querySelector('dummy');100                },101                queryAll(root, selector) {102                    return Array.from(root.querySelectorAll('dummy'));103                }104            })";105            exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Playwright.Selectors.RegisterAsync("$", new() { Script = createDummySelector }));106            StringAssert.Contains("Selector engine name may only contain [a-zA-Z0-9_] characters", exception.Message);107            await TestUtils.RegisterEngineAsync(Playwright, "dummy", createDummySelector);108            await TestUtils.RegisterEngineAsync(Playwright, "duMMy", createDummySelector);109            exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Playwright.Selectors.RegisterAsync("dummy", new() { Script = createDummySelector }));110            StringAssert.Contains("\"dummy\" selector engine has been already registered", exception.Message);111            exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Playwright.Selectors.RegisterAsync("css", new() { Script = createDummySelector }));112            StringAssert.Contains("\"css\" is a predefined selector engine", exception.Message);113        }114    }115}...

Full Screen

Full Screen

PageAddScriptTagTests.cs

Source:PageAddScriptTagTests.cs Github

copy

Full Screen

...46        [PlaywrightTest("page-add-script-tag.spec.ts", "should work with a path and type=module")]47        public async Task ShouldWorkWithAPathAndTypeModule()48        {49            await Page.GotoAsync(Server.EmptyPage);50            await Page.AddScriptTagAsync(new() { Path = TestUtils.GetAsset("es6/es6pathimport.js"), Type = "module" });51            await Page.WaitForFunctionAsync("window.__es6injected");52            Assert.AreEqual(42, await Page.EvaluateAsync<int>("() => __es6injected"));53        }54        [PlaywrightTest("page-add-script-tag.spec.ts", "should work with a content and type=module")]55        public async Task ShouldWorkWithAContentAndTypeModule()56        {57            await Page.GotoAsync(Server.EmptyPage);58            await Page.AddScriptTagAsync(new() { Content = "import num from '/es6/es6module.js'; window.__es6injected = num;", Type = "module" });59            await Page.WaitForFunctionAsync("window.__es6injected");60            Assert.AreEqual(42, await Page.EvaluateAsync<int>("() => __es6injected"));61        }62        [PlaywrightTest("page-add-script-tag.spec.ts", "should throw an error if loading from url fail")]63        public async Task ShouldThrowAnErrorIfLoadingFromUrlFail()64        {65            await Page.GotoAsync(Server.EmptyPage);66            await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.AddScriptTagAsync(new() { Url = "/nonexistfile.js" }));67        }68        [PlaywrightTest("page-add-script-tag.spec.ts", "should work with a path")]69        public async Task ShouldWorkWithAPath()70        {71            await Page.GotoAsync(Server.EmptyPage);72            var scriptHandle = await Page.AddScriptTagAsync(new() { Path = TestUtils.GetAsset("injectedfile.js") });73            Assert.NotNull(scriptHandle);74            Assert.AreEqual(42, await Page.EvaluateAsync<int>("() => __injected"));75        }76        [PlaywrightTest("page-add-script-tag.spec.ts", "should include sourceURL when path is provided")]77        [Skip(SkipAttribute.Targets.Webkit)]78        public async Task ShouldIncludeSourceURLWhenPathIsProvided()79        {80            await Page.GotoAsync(Server.EmptyPage);81            await Page.AddScriptTagAsync(new() { Path = TestUtils.GetAsset("injectedfile.js") });82            string result = await Page.EvaluateAsync<string>("() => __injectedError.stack");83            StringAssert.Contains(TestUtils.GetAsset("injectedfile.js"), result);84        }85        [PlaywrightTest("page-add-script-tag.spec.ts", "should work with content")]86        public async Task ShouldWorkWithContent()87        {88            await Page.GotoAsync(Server.EmptyPage);89            var scriptHandle = await Page.AddScriptTagAsync(new() { Content = "window.__injected = 35;" });90            Assert.NotNull(scriptHandle);91            Assert.AreEqual(35, await Page.EvaluateAsync<int>("() => __injected"));92        }93        [PlaywrightTest("page-add-script-tag.spec.ts", "should throw when added with content to the CSP page")]94        [Skip(SkipAttribute.Targets.Firefox)]95        public async Task ShouldThrowWhenAddedWithContentToTheCSPPage()96        {97            await Page.GotoAsync(Server.Prefix + "/csp.html");...

Full Screen

Full Screen

PageAddInitScriptTests.cs

Source:PageAddInitScriptTests.cs Github

copy

Full Screen

...38        }39        [PlaywrightTest("page-add-init-script.spec.ts", "should work with a path")]40        public async Task ShouldWorkWithAPath()41        {42            await Page.AddInitScriptAsync(scriptPath: TestUtils.GetAsset("injectedfile.js"));43            await Page.GotoAsync(Server.Prefix + "/tamperable.html");44            Assert.AreEqual(123, await Page.EvaluateAsync<int>("() => window.result"));45        }46        [PlaywrightTest("page-add-init-script.spec.ts", "should work with a path")]47        public async Task ShouldWorkWithContents()48        {49            await Page.AddInitScriptAsync("window.injected = 123;");50            await Page.GotoAsync(Server.Prefix + "/tamperable.html");51            Assert.AreEqual(123, await Page.EvaluateAsync<int>("() => window.result"));52        }53        [PlaywrightTest("page-add-init-script.spec.ts", "should throw without path and content")]54        public Task ShouldThrowWithoutPathAndContent()55        {56            return PlaywrightAssert.ThrowsAsync<ArgumentException>(() => Page.AddInitScriptAsync());57        }58        [PlaywrightTest("page-add-init-script.spec.ts", "should work with browser context scripts")]59        public async Task ShouldWorkWithBrowserContextScripts()60        {61            await using var context = await Browser.NewContextAsync();62            await context.AddInitScriptAsync("window.temp = 123;");63            var page = await context.NewPageAsync();64            await page.AddInitScriptAsync("window.injected = window.temp;");65            await page.GotoAsync(Server.Prefix + "/tamperable.html");66            Assert.AreEqual(123, await page.EvaluateAsync<int>("() => window.result"));67        }68        [PlaywrightTest("page-add-init-script.spec.ts", "should work with browser context scripts with path")]69        public async Task ShouldWorkWithBrowserContextScriptsWithPath()70        {71            await using var context = await Browser.NewContextAsync();72            await context.AddInitScriptAsync(scriptPath: TestUtils.GetAsset("injectedfile.js"));73            var page = await context.NewPageAsync();74            await page.GotoAsync(Server.Prefix + "/tamperable.html");75            Assert.AreEqual(123, await page.EvaluateAsync<int>("() => window.result"));76        }77        [PlaywrightTest("page-add-init-script.spec.ts", "should work with browser context scripts for already created pages")]78        public async Task ShouldWorkWithBrowserContextScriptsForAlreadyCreatedPages()79        {80            await using var context = await Browser.NewContextAsync();81            var page = await context.NewPageAsync();82            await context.AddInitScriptAsync("window.temp = 123;");83            await page.AddInitScriptAsync(script: "window.injected = window.temp;");84            await page.GotoAsync(Server.Prefix + "/tamperable.html");85            Assert.AreEqual(123, await page.EvaluateAsync<int>("() => window.result"));86        }...

Full Screen

Full Screen

BrowserContextCSPTests.cs

Source:BrowserContextCSPTests.cs Github

copy

Full Screen

...36            {37                var page = await context.NewPageAsync();38                await page.GotoAsync(Server.Prefix + "/csp.html");39                var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => page.AddScriptTagAsync(new() { Content = "window.__injected = 42;" }));40                TestUtils.AssertCSPError(exception.Message);41                Assert.Null(await page.EvaluateAsync("window.__injected"));42            }43            // By-pass CSP and try one more time.44            await using (var context = await Browser.NewContextAsync(new() { BypassCSP = true }))45            {46                var page = await context.NewPageAsync();47                await page.GotoAsync(Server.Prefix + "/csp.html");48                await page.AddScriptTagAsync(new() { Content = "window.__injected = 42;" });49                Assert.AreEqual(42, await page.EvaluateAsync<int>("window.__injected"));50            }51        }52        [PlaywrightTest("browsercontext-csp.spec.ts", "should bypass CSP header")]53        public async Task ShouldBypassCSPHeader()54        {55            // Make sure CSP prohibits addScriptTag.56            Server.SetCSP("/empty.html", "default-src 'self'");57            await using (var context = await Browser.NewContextAsync())58            {59                var page = await context.NewPageAsync();60                await page.GotoAsync(Server.EmptyPage);61                var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => page.AddScriptTagAsync(new() { Content = "window.__injected = 42;" }));62                TestUtils.AssertCSPError(exception.Message);63                Assert.Null(await page.EvaluateAsync("window.__injected"));64            }65            // By-pass CSP and try one more time.66            await using (var context = await Browser.NewContextAsync(new() { BypassCSP = true }))67            {68                var page = await context.NewPageAsync();69                await page.GotoAsync(Server.EmptyPage);70                await page.AddScriptTagAsync(new() { Content = "window.__injected = 42;" });71                Assert.AreEqual(42, await page.EvaluateAsync<int>("window.__injected"));72            }73        }74        [PlaywrightTest("browsercontext-csp.spec.ts", "should bypass after cross-process navigation")]75        public async Task ShouldBypassAfterCrossProcessNavigation()76        {77            await using var context = await Browser.NewContextAsync(new() { BypassCSP = true });78            var page = await context.NewPageAsync();79            await page.GotoAsync(Server.Prefix + "/csp.html");80            await page.AddScriptTagAsync(new() { Content = "window.__injected = 42;" });81            Assert.AreEqual(42, await page.EvaluateAsync<int>("window.__injected"));82            await page.GotoAsync(Server.CrossProcessPrefix + "/csp.html");83            await page.AddScriptTagAsync(new() { Content = "window.__injected = 42;" });84            Assert.AreEqual(42, await page.EvaluateAsync<int>("window.__injected"));85        }86        [PlaywrightTest("browsercontext-csp.spec.ts", "should bypass CSP in iframes as well")]87        public async Task ShouldBypassCSPInIframesAsWell()88        {89            await using (var context = await Browser.NewContextAsync())90            {91                var page = await context.NewPageAsync();92                await page.GotoAsync(Server.EmptyPage);93                // Make sure CSP prohibits addScriptTag in an iframe.94                var frame = await FrameUtils.AttachFrameAsync(page, "frame1", Server.Prefix + "/csp.html");95                var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => frame.AddScriptTagAsync(new() { Content = "window.__injected = 42;" }));96                TestUtils.AssertCSPError(exception.Message);97                Assert.Null(await frame.EvaluateAsync<int?>("() => window.__injected"));98            }99            // By-pass CSP and try one more time.100            await using (var context = await Browser.NewContextAsync(new() { BypassCSP = true }))101            {102                var page = await context.NewPageAsync();103                await page.GotoAsync(Server.EmptyPage);104                // Make sure CSP prohibits addScriptTag in an iframe.105                var frame = await FrameUtils.AttachFrameAsync(page, "frame1", Server.Prefix + "/csp.html");106                await frame.AddScriptTagAsync(new() { Content = "window.__injected = 42;" }).ContinueWith(_ => Task.CompletedTask);107                Assert.AreEqual(42, await frame.EvaluateAsync<int?>("() => window.__injected"));108            }109        }110    }...

Full Screen

Full Screen

PageAddStyleTagTests.cs

Source:PageAddStyleTagTests.cs Github

copy

Full Screen

...46        [PlaywrightTest("page-add-style-tag.spec.ts", "should work with a path")]47        public async Task ShouldWorkWithAPath()48        {49            await Page.GotoAsync(Server.EmptyPage);50            var styleHandle = await Page.AddStyleTagAsync(new() { Path = TestUtils.GetAsset("injectedstyle.css") });51            Assert.NotNull(styleHandle);52            Assert.AreEqual("rgb(255, 0, 0)", await Page.EvaluateAsync<string>("window.getComputedStyle(document.querySelector('body')).getPropertyValue('background-color')"));53        }54        [PlaywrightTest("page-add-style-tag.spec.ts", "should include sourceURL when path is provided")]55        public async Task ShouldIncludeSourceURLWhenPathIsProvided()56        {57            await Page.GotoAsync(Server.EmptyPage);58            await Page.AddStyleTagAsync(new() { Path = TestUtils.GetAsset("injectedstyle.css") });59            var styleHandle = await Page.QuerySelectorAsync("style");60            string styleContent = await Page.EvaluateAsync<string>("style => style.innerHTML", styleHandle);61            StringAssert.Contains(TestUtils.GetAsset("injectedstyle.css"), styleContent);62        }63        [PlaywrightTest("page-add-style-tag.spec.ts", "should work with content")]64        public async Task ShouldWorkWithContent()65        {66            await Page.GotoAsync(Server.EmptyPage);67            var styleHandle = await Page.AddStyleTagAsync(new() { Content = "body { background-color: green; }" });68            Assert.NotNull(styleHandle);69            Assert.AreEqual("rgb(0, 128, 0)", await Page.EvaluateAsync<string>("window.getComputedStyle(document.querySelector('body')).getPropertyValue('background-color')"));70        }71        [PlaywrightTest("page-add-style-tag.spec.ts", "should throw when added with content to the CSP page")]72        public async Task ShouldThrowWhenAddedWithContentToTheCSPPage()73        {74            await Page.GotoAsync(Server.Prefix + "/csp.html");75            await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() =>...

Full Screen

Full Screen

HttpService.cs

Source:HttpService.cs Github

copy

Full Screen

...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        }53        public Task DisposeAsync()54        {55            return Task.WhenAll(Server.StopAsync(), HttpsServer.StopAsync());...

Full Screen

Full Screen

E2ETests.cs

Source:E2ETests.cs Github

copy

Full Screen

...47		public async Task EnsureAppRuns()48		{49			using var factory = Create(new Dictionary<string, string>());50			using var playwright = await Playwright.CreateAsync();51			await using var browser = await playwright.Chromium.LaunchAsync(TestUtils.InCi52				? new BrowserTypeLaunchOptions()53				: new BrowserTypeLaunchOptions54				{55					Headless = false,56					SlowMo = 10057				});58			var page = await browser.NewPageAsync();59			60			await TestUtils.EventuallyAsync(async () =>61			{62				await page.GotoAsync(factory.RootUri.ToString());63			});64			65			TestUtils.Eventually(() =>66			{67				//ensure that the data dir has been created68				var datadir = factory.Host.Services.GetRequiredService<IDataDirProvider>().Get();69				Assert.True(Directory.Exists(datadir));70			});71			72			//fresh run = landing page default73			Assert.EndsWith("/landing", page.Url);74		}75	}76}...

Full Screen

Full Screen

TestUtils

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright.Tests;2using Microsoft.Playwright.Tests.Helpers;3using System;4using System.Collections.Generic;5using System.Linq;6using System.Text;7using System.Threading.Tasks;8{9    {10        static async Task Main(string[] args)11        {12            var utils = new TestUtils();13            var browser = await utils.LaunchAsync();14            var page = await browser.NewPageAsync();15            await page.ScreenshotAsync(new PageScreenshotOptions { Path = "google.png" });16            await browser.CloseAsync();17        }18    }19}

Full Screen

Full Screen

TestUtils

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright.Tests;2using Microsoft.Playwright;3using System.Threading.Tasks;4using Xunit;5{6    {7        public async Task Test()8        {9            using var playwright = await Playwright.CreateAsync();10            await using var browser = await playwright.Chromium.LaunchAsync();11            var page = await browser.NewPageAsync();12            await page.ScreenshotAsync(path: "google.png");13        }14    }15}

Full Screen

Full Screen

TestUtils

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright.Tests;2using NUnit.Framework;3{4    {5        private TestUtils _testUtils;6        public void SetUp()7        {8            _testUtils = new TestUtils();9        }10        public void TestMethod()11        {12            var result = _testUtils.DoSomething();13            Assert.AreEqual(result, "Hello World");14        }15    }16}

Full Screen

Full Screen

TestUtils

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright.Tests;2using Microsoft.Playwright;3using Microsoft.Playwright.NUnit;4using NUnit.Framework;5using System;6using System.Threading.Tasks;7{8    {9        private IPlaywright playwright;10        private IBrowser browser;11        private IBrowserContext context;12        private IPage page;13        private ITestUtils testUtils;14        public async Task OneTimeSetupAsync()15        {16            playwright = await Playwright.CreateAsync();17            browser = await playwright.Chromium.LaunchAsync();18            context = await browser.NewContextAsync();19            page = await context.NewPageAsync();20            testUtils = new TestUtils(page);21        }22        public async Task OneTimeTearDownAsync()23        {24            await browser.CloseAsync();25            await playwright.StopAsync();26        }27        public async Task Test1()28        {29            await testUtils.AttachFrameAsync("frame1", "./empty.html");30            await page.EvaluateAsync("() => { window.frame = document.querySelector('#frame1').contentWindow; }");31            await page.EvaluateAsync("() => { window.frame.document.body.innerHTML = '<div>Text</div>'; }");32            var frame = page.Frames[1];33            var div = await frame.QuerySelectorAsync("div");34            Assert.AreEqual("Text", await div.EvaluateAsync("node => node.textContent"));35        }36    }37}

Full Screen

Full Screen

TestUtils

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright.Tests;2using Microsoft.Playwright;3using NUnit.Framework;4using System.Threading.Tasks;5{6    {7        private IPage page;8        private IBrowser browser;9        public async Task Setup()10        {11            browser = await TestUtils.CreateBrowser();12            page = await browser.NewPageAsync();13        }14        public async Task Teardown()15        {16            await browser.CloseAsync();17        }18        public async Task ShouldWork()19        {20            Assert.AreEqual("Google", await page.TitleAsync());21        }22    }23}

Full Screen

Full Screen

TestUtils

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright;2using Microsoft.Playwright.Core;3using Microsoft.Playwright.Transport;4using Microsoft.Playwright.Transport.Channels;5using Microsoft.Playwright.Transport.Protocol;6{7    {8        public async Task Test()9        {10            var playwright = await Playwright.CreateAsync();11            var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Headless = false });12            var context = await browser.NewContextAsync();

Full Screen

Full Screen

Playwright tutorial

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.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful