How to use ShouldBeAbleToReconnect method of PuppeteerSharp.Tests.LauncherTests.PuppeteerConnectTests class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Tests.LauncherTests.PuppeteerConnectTests.ShouldBeAbleToReconnect

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

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

PuppeteerConnectTests.cs

Source: PuppeteerConnectTests.cs Github

copy
1using System;
2using System.Linq;
3using System.Threading.Tasks;
4using Microsoft.AspNetCore.Connections.Features;
5using PuppeteerSharp.Transport;
6using Xunit;
7using Xunit.Abstractions;
8using PuppeteerSharp.Helpers;
9using PuppeteerSharp.Tests.Attributes;
10using PuppeteerSharp.Xunit;
11
12namespace PuppeteerSharp.Tests.LauncherTests
13{
14    [Collection(TestConstants.TestFixtureCollectionName)]
15    public class PuppeteerConnectTests : PuppeteerBrowserBaseTest
16    {
17        public PuppeteerConnectTests(ITestOutputHelper output) : base(output)
18        {
19        }
20
21        [PuppeteerTest("launcher.spec.ts", "Puppeteer.connect", "should be able to connect multiple times to the same browser")]
22        [PuppeteerFact]
23        public async Task ShouldBeAbleToConnectMultipleTimesToSameBrowser()
24        {
25            var options = new ConnectOptions()
26            {
27                BrowserWSEndpoint = Browser.WebSocketEndpoint
28            };
29            var browser = await Puppeteer.ConnectAsync(options, TestConstants.LoggerFactory);
30            await using (var page = await browser.NewPageAsync())
31            {
32                var response = await page.EvaluateExpressionAsync<int>("7 * 8");
33                Assert.Equal(56, response);
34            }
35
36            await using (var originalPage = await Browser.NewPageAsync())
37            {
38                var response = await originalPage.EvaluateExpressionAsync<int>("7 * 6");
39                Assert.Equal(42, response);
40            }
41        }
42
43        [PuppeteerTest("launcher.spec.ts", "Puppeteer.connect", "should be able to close remote browser")]
44        [PuppeteerFact]
45        public async Task ShouldBeAbleToCloseRemoteBrowser()
46        {
47            var originalBrowser = await Puppeteer.LaunchAsync(TestConstants.DefaultBrowserOptions());
48            var remoteBrowser = await Puppeteer.ConnectAsync(new ConnectOptions
49            {
50                BrowserWSEndpoint = originalBrowser.WebSocketEndpoint
51            });
52            var tcsDisconnected = new TaskCompletionSource<bool>();
53
54            originalBrowser.Disconnected += (_, _) => tcsDisconnected.TrySetResult(true);
55            await Task.WhenAll(
56              tcsDisconnected.Task,
57              remoteBrowser.CloseAsync());
58        }
59
60        [PuppeteerTest("launcher.spec.ts", "Puppeteer.connect", "should support ignoreHTTPSErrors option")]
61        [PuppeteerFact]
62        public async Task ShouldSupportIgnoreHTTPSErrorsOption()
63        {
64            await using (var originalBrowser = await Puppeteer.LaunchAsync(TestConstants.DefaultBrowserOptions()))
65            await using (var browser = await Puppeteer.ConnectAsync(new ConnectOptions
66            {
67                BrowserWSEndpoint = originalBrowser.WebSocketEndpoint,
68                IgnoreHTTPSErrors = true
69            }))
70            await using (var page = await browser.NewPageAsync())
71            {
72                var requestTask = HttpsServer.WaitForRequest(
73                    "/empty.html",
74                    request => request?.HttpContext?.Features?.Get<ITlsHandshakeFeature>()?.Protocol);
75                var responseTask = page.GoToAsync(TestConstants.HttpsPrefix + "/empty.html");
76
77                await Task.WhenAll(
78                    requestTask,
79                    responseTask).WithTimeout(Puppeteer.DefaultTimeout);
80
81                var response = responseTask.Result;
82                Assert.True(response.Ok);
83                Assert.NotNull(response.SecurityDetails);
84                Assert.Equal(
85                    TestUtils.CurateProtocol(requestTask.Result.ToString()),
86                    TestUtils.CurateProtocol(response.SecurityDetails.Protocol));
87            }
88        }
89
90        [PuppeteerTest("launcher.spec.ts", "Puppeteer.connect", "should support targetFilter option")]
91        [SkipBrowserFact(skipFirefox: true)]
92        public async Task ShouldSupportTargetFilter()
93        {
94            await using (var originalBrowser = await Puppeteer.LaunchAsync(TestConstants.DefaultBrowserOptions()))
95            {
96                var page1 = await originalBrowser.NewPageAsync();
97                await page1.GoToAsync(TestConstants.EmptyPage);
98
99                var page2 = await originalBrowser.NewPageAsync();
100                await page2.GoToAsync(TestConstants.EmptyPage + "?should-be-ignored");
101
102                var browser = await Puppeteer.ConnectAsync(new ConnectOptions {
103                    BrowserWSEndpoint = originalBrowser.WebSocketEndpoint,
104                    TargetFilter = (TargetInfo targetInfo) => !targetInfo.Url.Contains("should-be-ignored"),
105                });
106
107                var pages = await browser.PagesAsync();
108
109                await page2.CloseAsync();
110                await page1.CloseAsync();
111                await browser.CloseAsync();
112
113                Assert.Equal(
114                    new string[]
115                    {
116                        "about:blank",
117                        TestConstants.EmptyPage
118                    },
119                    pages.Select((Page p) => p.Url).OrderBy(t => t));
120            }
121        }
122
123        [PuppeteerFact]
124        public async Task ShouldBeAbleToSetBrowserPropertiesUsingConnectOptions()
125        {
126            var initActionExecuted = false;
127            var options = new ConnectOptions
128            {
129                BrowserWSEndpoint = Browser.WebSocketEndpoint,
130                InitAction = brw =>
131                {
132                    initActionExecuted = true;
133                }
134            };
135            var browser = await Puppeteer.ConnectAsync(options, TestConstants.LoggerFactory);
136
137            Assert.True(initActionExecuted);
138
139            await browser.CloseAsync();
140        }
141
142        [PuppeteerTest("launcher.spec.ts", "Puppeteer.connect", "should be able to reconnect to a disconnected browser")]
143        [SkipBrowserFact(skipFirefox: true)]
144        public async Task ShouldBeAbleToReconnectToADisconnectedBrowser()
145        {
146            var options = new ConnectOptions()
147            {
148                BrowserWSEndpoint = Browser.WebSocketEndpoint
149            };
150
151            var url = TestConstants.ServerUrl + "/frames/nested-frames.html";
152            var page = await Browser.NewPageAsync();
153            await page.GoToAsync(url);
154
155            Browser.Disconnect();
156
157            await using (var browser = await Puppeteer.ConnectAsync(options, TestConstants.LoggerFactory))
158            {
159                var pages = (await browser.PagesAsync()).ToList();
160                var restoredPage = pages.FirstOrDefault(x => x.Url == url);
161                Assert.NotNull(restoredPage);
162                var frameDump = FrameUtils.DumpFrames(restoredPage.MainFrame);
163                Assert.Equal(TestConstants.NestedFramesDumpResult, frameDump);
164                var response = await restoredPage.EvaluateExpressionAsync<int>("7 * 8");
165                Assert.Equal(56, response);
166            }
167        }
168
169        [PuppeteerTest("launcher.spec.ts", "Puppeteer.connect", "should be able to connect to the same page simultaneously")]
170        [SkipBrowserFact(skipFirefox: true)]
171        public async Task ShouldBeAbleToConnectToTheSamePageSimultaneously()
172        {
173            var browserOne = await Puppeteer.LaunchAsync(new LaunchOptions());
174            var browserTwo = await Puppeteer.ConnectAsync(new ConnectOptions
175            {
176                BrowserWSEndpoint = browserOne.WebSocketEndpoint
177            });
178            var tcs = new TaskCompletionSource<Page>();
179            async void TargetCreated(object sender, TargetChangedArgs e)
180            {
181                tcs.TrySetResult(await e.Target.PageAsync());
182                browserOne.TargetCreated -= TargetCreated;
183            }
184            browserOne.TargetCreated += TargetCreated;
185            var page2Task = browserTwo.NewPageAsync();
186
187            await Task.WhenAll(tcs.Task, page2Task);
188            var page1 = tcs.Task.Result;
189            var page2 = page2Task.Result;
190
191            Assert.Equal(56, await page1.EvaluateExpressionAsync<int>("7 * 8"));
192            Assert.Equal(42, await page2.EvaluateExpressionAsync<int>("7 * 6"));
193            await browserOne.CloseAsync();
194        }
195
196        [PuppeteerTest("launcher.spec.ts", "Puppeteer.connect", "should be able to reconnect")]
197        [SkipBrowserFact(skipFirefox: true)]
198        public async Task ShouldBeAbleToReconnect()
199        {
200            var browserOne = await Puppeteer.LaunchAsync(new LaunchOptions());
201            var browserWSEndpoint = browserOne.WebSocketEndpoint;
202            var page1 = await browserOne.NewPageAsync();
203            await page1.GoToAsync(TestConstants.EmptyPage);
204            browserOne.Disconnect();
205
206            var browserTwo = await Puppeteer.ConnectAsync(new ConnectOptions
207            {
208                BrowserWSEndpoint = browserWSEndpoint
209            });
210
211            var pages = await browserTwo.PagesAsync();
212            var pageTwo = pages.First(page => page.Url == TestConstants.EmptyPage);
213            await pageTwo.ReloadAsync();
214            var bodyHandle = await pageTwo.WaitForSelectorAsync("body", new WaitForSelectorOptions { Timeout = 10000 });
215            await bodyHandle.DisposeAsync();
216            await browserTwo.CloseAsync();
217        }
218
219        [PuppeteerFact]
220        public async Task ShouldSupportCustomWebSocket()
221        {
222            var customSocketCreated = false;
223            var options = new ConnectOptions()
224            {
225                BrowserWSEndpoint = Browser.WebSocketEndpoint,
226                WebSocketFactory = (uri, socketOptions, cancellationToken) =>
227                {
228                    customSocketCreated = true;
229                    return WebSocketTransport.DefaultWebSocketFactory(uri, socketOptions, cancellationToken);
230                }
231            };
232
233            await using (await Puppeteer.ConnectAsync(options, TestConstants.LoggerFactory))
234            {
235                Assert.True(customSocketCreated);
236            }
237        }
238
239        [PuppeteerFact]
240        public async Task ShouldSupportCustomTransport()
241        {
242            var customTransportCreated = false;
243            var options = new ConnectOptions()
244            {
245                BrowserWSEndpoint = Browser.WebSocketEndpoint,
246                TransportFactory = (url, opt, cancellationToken) =>
247                {
248                    customTransportCreated = true;
249                    return WebSocketTransport.DefaultTransportFactory(url, opt, cancellationToken);
250                }
251            };
252
253            await using (await Puppeteer.ConnectAsync(options, TestConstants.LoggerFactory))
254            {
255                Assert.True(customTransportCreated);
256            }
257        }
258    }
259}
260
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
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)