How to use PageWaitForLoadStateOptions class of Microsoft.Playwright package

Best Playwright-dotnet code snippet using Microsoft.Playwright.PageWaitForLoadStateOptions

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

PlayWrightHtmlLoaderService.cs

Source: PlayWrightHtmlLoaderService.cs Github

copy
1using Microsoft.Playwright;
2using System;
3using System.Collections.Generic;
4using System.Linq;
5using System.Text;
6using System.Threading.Tasks;
7
8namespace HtmlParser.HtmlLoaderService
9{
10    public class PlayWrightHtmlLoaderService : IHtmlLoaderServiceAsync, IDisposable
11    {
12        private readonly IPlaywright _playwright;
13        private readonly IBrowser _browser;
14
15        public PlayWrightHtmlLoaderService() 
16        {
17            _playwright = Playwright.CreateAsync().GetAwaiter().GetResult();
18            _browser = _playwright.Chromium.LaunchAsync().GetAwaiter().GetResult();
19            
20        }
21
22        public void Dispose()
23        {
24            _browser.DisposeAsync().GetAwaiter().GetResult();
25            _playwright.Dispose();
26        }
27
28        public string GetHtmlBody(string uri)
29        {
30            return GetHtmlBodyAsync(uri).GetAwaiter().GetResult();
31        }
32
33        public async Task<string> GetHtmlBodyAsync(string uri)
34        {
35            var page = await _browser.NewPageAsync();
36            await page.GotoAsync(uri, new PageGotoOptions() { Timeout = 60000 });
37            await page.WaitForLoadStateAsync(LoadState.NetworkIdle, new PageWaitForLoadStateOptions() { Timeout = 60000 });
38            var htmlContent = await page.ContentAsync();
39            await page.CloseAsync();
40
41            return htmlContent;
42        }
43    }
44}
45
Full Screen

PlaywrightTest.cs

Source: PlaywrightTest.cs Github

copy
1using ActualChat.Testing.Host;
2using Microsoft.Playwright;
3
4namespace ActualChat.UI.Blazor.IntegrationTests;
5
6public class PlaywrightTest : AppHostTestBase
7{
8    public PlaywrightTest(ITestOutputHelper @out) : base(@out) { }
9
10    [Fact]
11    public async Task CloseBrowserTest()
12    {
13        using var appHost = await TestHostFactory.NewAppHost();
14        using var tester = appHost.NewPlaywrightTester();
15        var browser = await tester.NewContext();
16        await browser.CloseAsync();
17    }
18
19    [Fact]
20    public async Task AddMessageTest()
21    {
22        const float timeout = 20_000f;
23        using var appHost = await TestHostFactory.NewAppHost().ConfigureAwait(false);
24        using var tester = appHost.NewPlaywrightTester();
25        var user = await tester.SignIn(new User("", "it-works")).ConfigureAwait(false);
26        var page = await tester.NewPage("chat/the-actual-one").ConfigureAwait(false);
27        await page.WaitForLoadStateAsync(LoadState.Load,
28            new PageWaitForLoadStateOptions() { Timeout = timeout }).ConfigureAwait(false);
29        // TODO: wait for server-side blazor loading, something like page.WaitForWebSocketAsync
30
31        await Task.Delay(2000).ConfigureAwait(false);
32
33        var chatPage = await page.QuerySelectorAsync(".chat-page").ConfigureAwait(false);
34        chatPage.Should().NotBeNull();
35        var input = await page.QuerySelectorAsync("[role='textbox']").ConfigureAwait(false);
36        input.Should().NotBeNull();
37        var button = await page.QuerySelectorAsync("button.message-submit").ConfigureAwait(false);
38        button.Should().NotBeNull();
39
40        var messages = await GetMessages(page).ConfigureAwait(false);
41        var lastMessage = await GetLastMessage(messages).ConfigureAwait(false);
42        lastMessage.Should().NotBe("Test-123");
43
44        await input!.TypeAsync("Test-123").ConfigureAwait(false);
45        await button!.ClickAsync().ConfigureAwait(false);
46
47        var count = messages.Count;
48        messages = await WaitNewMessages(TimeSpan.FromSeconds(5), page, count).ConfigureAwait(false);
49        lastMessage = await GetLastMessage(messages).ConfigureAwait(false);
50        lastMessage.Should().Be("Test-123");
51
52        static async Task<IReadOnlyList<IElementHandle>> WaitNewMessages(TimeSpan timeout, IPage page, int oldMessagesCount)
53        {
54            var stopTime = DateTime.Now + timeout;
55            var newMessages = await GetMessages(page).ConfigureAwait(false);
56            while (newMessages.Count == oldMessagesCount) {
57                await Task.Delay(500).ConfigureAwait(false);
58                newMessages = await GetMessages(page).ConfigureAwait(false);
59                if (DateTime.Now >= stopTime) {
60                    throw new Exception($"Chat state has not changed in {timeout.TotalSeconds} seconds.");
61                }
62            }
63            return newMessages;
64        }
65
66        static async Task<IReadOnlyList<IElementHandle>> GetMessages(IPage page)
67            => await page.QuerySelectorAllAsync(".chat-page .content");
68
69        static async Task<string?> GetLastMessage(IEnumerable<IElementHandle> messages)
70            => await messages.Last().TextContentAsync().ConfigureAwait(false);
71    }
72
73    [Fact]
74    public async Task ChatPageTest()
75    {
76        using var appHost = await TestHostFactory.NewAppHost();
77        using var tester = appHost.NewPlaywrightTester();
78        var user = await tester.SignIn(new User("", "ChatPageTester"));
79        var page = await tester.NewPage("chat/the-actual-one");
80        await Task.Delay(1000);
81        user.Id.Value.Should().NotBeNullOrEmpty();
82        user.Name.Should().Be("ChatPageTester");
83        var messages = await page.QuerySelectorAllAsync(".chat-page .content");
84        messages.Count.Should().BeGreaterThan(0);
85        await Task.Delay(200);
86    }
87}
88
Full Screen

Examples.cs

Source: Examples.cs Github

copy
1using System;
2using System.Threading.Tasks;
3using Microsoft.Playwright;
4using NUnit.Framework;
5
6namespace PlaywrightContrib.Sample.NUnit
7{
8    public class Examples
9    {
10        async Task<IBrowser> Browser()
11        {
12            var playwright = await Playwright.CreateAsync();
13            var browser = await playwright.Chromium.LaunchAsync();
14
15            // IBrowserType
16            _ = new[] { playwright.Chromium, playwright.Firefox, playwright.Webkit };
17
18            return browser;
19        }
20
21        [Test]
22        public async Task close_Browser()
23        {
24            var browser = await Browser();
25
26            await browser.CloseAsync();
27        }
28
29        [Test]
30        public async Task using_Browser()
31        {
32            using var playwright = await Playwright.CreateAsync();
33            await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Headless = true });
34
35            // ...
36        }
37
38        async Task<IPage> Page()
39        {
40            var browser = await Browser();
41            var page = await browser.NewPageAsync();
42
43            return page;
44        }
45
46        [Test]
47        public async Task close_Page()
48        {
49            var page = await Page();
50
51            await page.CloseAsync();
52        }
53
54        [Test]
55        public async Task navigation()
56        {
57            var page = await Page();
58
59            await page.GotoAsync("https://github.com/microsoft/playwright-dotnet");
60            await page.GoBackAsync();
61            await page.GoForwardAsync();
62            await page.ReloadAsync();
63        }
64
65        [Test]
66        public async Task timeout()
67        {
68            var page = await Page();
69
70            var timeout = (int)TimeSpan.FromSeconds(30).TotalMilliseconds; // default value
71            page.SetDefaultNavigationTimeout(timeout);
72            page.SetDefaultTimeout(timeout);
73
74            await page.GotoAsync("https://github.com/microsoft/playwright-dotnet", new PageGotoOptions { Timeout = timeout });
75            await page.GoBackAsync(new PageGoBackOptions { Timeout = timeout });
76            await page.GoForwardAsync(new PageGoForwardOptions { Timeout = timeout });
77            await page.ReloadAsync(new PageReloadOptions { Timeout = timeout });
78
79        }
80
81        [Test]
82        public async Task wait()
83        {
84            var page = await Page();
85            var timeout = (int)TimeSpan.FromSeconds(3).TotalMilliseconds;
86
87            var requestTask = page.WaitForRequestAsync("https://github.com/microsoft/playwright-dotnet", new PageWaitForRequestOptions { Timeout = timeout });
88            var responseTask = page.WaitForResponseAsync("https://github.com/microsoft/playwright-dotnet", new PageWaitForResponseOptions { Timeout = timeout });
89            await page.GotoAsync("https://github.com/microsoft/playwright-dotnet");
90            await Task.WhenAll(requestTask, responseTask);
91
92            var eventTask = page.WaitForResponseAsync("https://github.com/microsoft/playwright-dotnet");
93            var loadStateTask = page.WaitForLoadStateAsync(options: new PageWaitForLoadStateOptions { Timeout = timeout });
94            await page.GotoAsync("https://github.com/microsoft/playwright-dotnet");
95            await Task.WhenAll(eventTask, loadStateTask);
96
97            await page.ClickAsync("h1 > strong > a");
98            await page.WaitForNavigationAsync(new PageWaitForNavigationOptions { Timeout = timeout });
99
100            await page.WaitForFunctionAsync("() => window.location.href === 'https://github.com/microsoft/playwright-dotnet'", timeout);
101            await page.WaitForSelectorAsync("#readme", new PageWaitForSelectorOptions { Timeout = timeout });
102            await page.WaitForTimeoutAsync(timeout);
103
104            // LoadState
105            _ = new[] { LoadState.Load, LoadState.DOMContentLoaded, LoadState.NetworkIdle };
106
107            // WaitForSelectorState
108            _ = new[] { WaitForSelectorState.Attached, WaitForSelectorState.Detached, WaitForSelectorState.Visible, WaitForSelectorState.Hidden };
109        }
110
111        [Test]
112        public async Task values_from_Page()
113        {
114            var page = await Page();
115            await page.GotoAsync("https://github.com/microsoft/playwright-dotnet");
116
117            var url = page.Url;
118            var title = await page.TitleAsync();
119            var content = await page.ContentAsync();
120            var textContent = await page.TextContentAsync("#readme h1:nth-child(1)");
121            var innerText = await page.InnerTextAsync("#readme h1:nth-child(1)");
122            var innerHtml = await page.InnerHTMLAsync("#readme h1:nth-child(1)");
123            var attribute = await page.GetAttributeAsync("#readme h1:nth-child(1) a", "href");
124        }
125
126        [Test]
127        public async Task form()
128        {
129            var page = await Page();
130            await page.GotoAsync("https://www.techlistic.com/p/selenium-practice-form.html");
131
132            await page.SetViewportSizeAsync(1024, 1024); // fix
133
134            // input / text
135            await page.TypeAsync("input[name='firstname']", "Playwright");
136
137            // input / radio
138            await page.ClickAsync("#exp-6");
139
140            // input / checkbox
141            await page.CheckAsync("#profession-1");
142
143            // select / option
144            await page.SelectOptionAsync("#continents", "Europe");
145
146            // input / file
147            var file = await page.QuerySelectorAsync("#photo");
148            await file.SetInputFilesAsync(@"c:\temp\test.png");
149
150            // button
151            await page.ClickAsync("#submit");
152        }
153
154        [Test]
155        public async Task query()
156        {
157            var page = await Page();
158            await page.GotoAsync("https://github.com/microsoft/playwright-dotnet");
159
160            var element = await page.QuerySelectorAsync("div#readme");
161            var elements = await page.QuerySelectorAllAsync("div");
162            Assert.NotNull(element);
163            Assert.IsNotEmpty(elements);
164
165            var missingElement = await page.QuerySelectorAsync("div#missing");
166            var missingElements = await page.QuerySelectorAllAsync("div.missing");
167            Assert.Null(missingElement);
168            Assert.IsEmpty(missingElements);
169
170            var elementInElement = await element.QuerySelectorAsync("h1");
171            var elementsInElement = await element.QuerySelectorAllAsync("h1");
172            Assert.NotNull(elementInElement);
173            Assert.IsNotEmpty(elementsInElement);
174        }
175
176        [Test]
177        public async Task evaluate()
178        {
179            var page = await Page();
180            await page.GotoAsync("https://github.com/microsoft/playwright-dotnet");
181            var element = await page.QuerySelectorAsync("h1 > strong > a");
182
183            var outerHtml = await element.EvaluateAsync<string>("e => e.outerHTML");
184            var innerText = await element.EvaluateAsync<string>("e => e.innerText");
185            var url = await element.EvaluateAsync<string>("e => e.getAttribute('href')");
186            var hasContent = await element.EvaluateAsync<bool>("(e, value) => e.textContent.includes(value)", "playwright-dotnet");
187            Assert.AreEqual("<a data-pjax=\"#js-repo-pjax-container\" href=\"/microsoft/playwright-dotnet\">playwright-dotnet</a>", outerHtml);
188            Assert.AreEqual("playwright-dotnet", innerText);
189            Assert.AreEqual("/microsoft/playwright-dotnet", url);
190            Assert.True(hasContent);
191
192            outerHtml = await page.EvalOnSelectorAsync<string>("h1 > strong > a", "e => e.outerHTML");
193            innerText = await page.EvalOnSelectorAsync<string>("h1 > strong > a", "e => e.innerText");
194            url = await page.EvalOnSelectorAsync<string>("h1 > strong > a", "e => e.getAttribute('href')");
195            hasContent = await page.EvalOnSelectorAsync<bool>("h1 > strong > a", "(e, value) => e.textContent.includes(value)", "playwright-dotnet");
196            Assert.AreEqual("<a data-pjax=\"#js-repo-pjax-container\" href=\"/microsoft/playwright-dotnet\">playwright-dotnet</a>", outerHtml);
197            Assert.AreEqual("playwright-dotnet", innerText);
198            Assert.AreEqual("/microsoft/playwright-dotnet", url);
199            Assert.True(hasContent);
200
201            outerHtml = await page.EvaluateAsync<string>("e => e.outerHTML", element);
202            innerText = await page.EvaluateAsync<string>("e => e.innerText", element);
203            url = await page.EvaluateAsync<string>("e => e.getAttribute('href')", element);
204            hasContent = await page.EvaluateAsync<bool>($"e => e.textContent.includes({"'playwright-dotnet'"})", element);
205            Assert.AreEqual("<a data-pjax=\"#js-repo-pjax-container\" href=\"/microsoft/playwright-dotnet\">playwright-dotnet</a>", outerHtml);
206            Assert.AreEqual("playwright-dotnet", innerText);
207            Assert.AreEqual("/microsoft/playwright-dotnet", url);
208            Assert.True(hasContent);
209
210            outerHtml = await (await element.GetPropertyAsync("outerHTML")).JsonValueAsync<string>();
211            innerText = await (await element.GetPropertyAsync("innerText")).JsonValueAsync<string>();
212            url = await (await element.GetPropertyAsync("href")).JsonValueAsync<string>();
213            Assert.AreEqual("<a data-pjax=\"#js-repo-pjax-container\" href=\"/microsoft/playwright-dotnet\">playwright-dotnet</a>", outerHtml);
214            Assert.AreEqual("playwright-dotnet", innerText);
215            Assert.AreEqual("https://github.com/microsoft/playwright-dotnet", url);
216        }
217
218        [Test]
219        public async Task is_()
220        {
221            var page = await Page();
222            await page.GotoAsync("https://github.com/microsoft/playwright-dotnet");
223            Assert.ThrowsAsync<PlaywrightException>(async () => await page.IsCheckedAsync("input[name='q']")); // Not a checkbox or radio button
224            Assert.False(await page.IsDisabledAsync("input[name='q']"));
225            Assert.True(await page.IsEditableAsync("input[name='q']"));
226            Assert.True(await page.IsEnabledAsync("input[name='q']"));
227            Assert.False(await page.IsHiddenAsync("input[name='q']"));
228            Assert.True(await page.IsVisibleAsync("input[name='q']"));
229
230            var element = await page.QuerySelectorAsync("input[name='q']");
231            Assert.ThrowsAsync<PlaywrightException>(async () => await element.IsCheckedAsync()); // Not a checkbox or radio button
232            Assert.False(await element.IsDisabledAsync());
233            Assert.True(await element.IsEditableAsync());
234            Assert.True(await element.IsEnabledAsync());
235            Assert.False(await element.IsHiddenAsync());
236            Assert.True(await element.IsVisibleAsync());
237        }
238    }
239}
240
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

Most used methods in PageWaitForLoadStateOptions

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)