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

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

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

JSFacadeTests.cs

Source: JSFacadeTests.cs Github

copy
1// Copyright (c) Teroneko.
2// Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
4using System.Threading.Tasks;
5using Xunit;
6using System;
7using Teronis.AspNetCore.Components.NUnit;
8using System.Xml.Linq;
9using System.Linq;
10using Xunit.Abstractions;
11using Teronis.Microsoft.JSInterop.Infrastructure;
12
13namespace Teronis.Microsoft.JSInterop
14{
15    public class JSFacadeTests : IClassFixture<TestWebHostFixture<WebHostStartup>>, IClassFixture<PlaywrightFixture>
16    {
17        private readonly TestWebHostFixture<WebHostStartup> server;
18        private readonly PlaywrightFixture playwright;
19        private readonly ITestOutputHelper output;
20
21        public JSFacadeTests(TestWebHostFixture<WebHostStartup> server, PlaywrightFixture playwright, ITestOutputHelper output)
22        {
23            this.server = server ?? throw new ArgumentNullException(nameof(server));
24            this.playwright = playwright ?? throw new ArgumentNullException(nameof(playwright));
25            this.output = output ?? throw new ArgumentNullException(nameof(output));
26        }
27
28        [Fact]
29        public async Task Should_have_passed_nunit_report()
30        {
31            var applicationUrl = server.ApplicationUrl;
32            await using var browser = await playwright.Instance.Chromium.LaunchAsync();
33            var page = await browser.NewPageAsync();
34            var applicationUri = new Uri(applicationUrl);
35            var pageUri = new Uri(applicationUri, "/");
36            await page.GoToAsync(pageUri.AbsoluteUri);
37            await page.WaitForSelectorAsync(NUnitTestsReportDefaults.NUnitXmlReportRenderedAttributeSelector);
38            var nunitXmlReport = await page.GetTextContentAsync(NUnitTestsReportDefaults.NUnitXmlReportIdSelector);
39            output.WriteLine(nunitXmlReport);
40
41            Assert.True(
42                XDocument.Parse(nunitXmlReport)
43                    .Descendants("test-suite")
44                    .All(x => {
45                        var attribute = x.Attribute("result");
46
47                        if (attribute is null) {
48                            throw new ArgumentNullException(nameof(attribute));
49                        }
50
51                        return attribute.Value.ToLower() == "passed";
52                    }));
53        }
54    }
55}
56
Full Screen

PlayWrightUiTestsBase.cs

Source: PlayWrightUiTestsBase.cs Github

copy
1using System;
2using System.Threading.Tasks;
3using Microsoft.Playwright;
4using Xunit;
5
6namespace Playwright.Gherkin.XUnit
7{
8    [Trait("Category","UiTest")]
9#if DEBUG
10    [Collection("Stop parallell run")]
11#endif
12    
13    // Todo: Change or remove this class? It's not so useful
14    public abstract class PlayWrightUiTestsBase : IAsyncDisposable
15    {
16        protected readonly string BaseUrl = "https://localhost:5001";
17        protected readonly IPlaywright Playwright;
18        protected readonly IBrowser Browser;
19        protected readonly IPage Page;
20        protected readonly IBrowserContext Context;
21
22        protected PlayWrightUiTestsBase()
23        {
24            BaseUrl = Environment.GetEnvironmentVariable("BaseUrl") ?? BaseUrl;
25            Playwright = Microsoft.Playwright.Playwright.CreateAsync().GetAwaiter().GetResult();
26            Browser = Playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
27            {
28                Devtools = false,
29            }).GetAwaiter().GetResult();
30
31            Context = Browser.NewContextAsync(new BrowserNewContextOptions()
32            {
33                // RecordVideoDir = "./recordings",
34            }).GetAwaiter().GetResult();
35            Page = Context.NewPageAsync().GetAwaiter().GetResult();
36        }
37        
38        public async ValueTask  DisposeAsync()
39        {
40            await Context.CloseAsync();
41            await Browser.CloseAsync();
42            Playwright?.Dispose();
43        }
44    }
45}
Full Screen

WebServerTests.cs

Source: WebServerTests.cs Github

copy
1using AdvancedActions;
2using Microsoft.AspNetCore.Hosting;
3using Microsoft.Extensions.Hosting;
4using Microsoft.Playwright;
5using System;
6using System.Net;
7using System.Net.Sockets;
8using System.Threading.Tasks;
9using Xunit;
10
11namespace Tests
12{
13    public class WebServerDriver : IAsyncLifetime, IDisposable
14    {
15        private readonly IHost host;
16        private IPlaywright playwright { get; set; }
17        public IBrowser browser { get; private set; }
18        public string baseUrl { get; } = $"https://localhost:{GetRandomUnusedPort()}";
19
20        public WebServerDriver()
21        {
22            host = AdvancedActions.Program
23                .CreateHostBuilder(null)
24                .ConfigureWebHostDefaults(webBuilder =>
25                {
26                    webBuilder.UseStartup<Startup>();
27                    webBuilder.UseUrls(baseUrl);
28                })
29                .ConfigureServices(configure =>
30                { })
31                .Build();
32        }
33
34        public async Task InitializeAsync()
35        {
36            playwright = await Playwright.CreateAsync();
37            browser = await playwright.Chromium.LaunchAsync();
38                // Browser = await Playwright.Chromium.LaunchAsync(new LaunchOptions
39                // {
40                //     Headless = false
41                // });
42            await host.StartAsync();
43        }
44
45        public async Task DisposeAsync()
46        {
47            await host.StopAsync();
48            host?.Dispose();
49            playwright?.Dispose();
50        }
51
52        public void Dispose()
53        {
54            host?.Dispose();
55            playwright?.Dispose();
56        }
57
58        private static int GetRandomUnusedPort()
59        {
60            var listener = new TcpListener(IPAddress.Any, 0);
61            listener.Start();
62            var port = ((IPEndPoint)listener.LocalEndpoint).Port;
63            listener.Stop();
64            return port;
65        }
66    }
67
68    public class WebServerTests : IClassFixture<WebServerDriver>
69    {
70        private readonly WebServerDriver driver;
71
72        public WebServerTests(WebServerDriver driver)
73        {
74            this.driver = driver;
75        }
76
77        [Fact]
78        public async Task PageTitleIsIndex()
79        {
80            await using var context = await driver.browser.NewContextAsync(new() { IgnoreHTTPSErrors = true });
81            var page = await context.NewPageAsync();
82            await page.GotoAsync(driver.baseUrl);
83
84            var title = await page.TitleAsync();
85
86            Assert.Equal("Dogs", title);
87        }
88    }
89}
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)