How to use PageEventsConsoleTests method of PuppeteerSharp.Tests.PageTests.Events.PageEventsConsoleTests class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Tests.PageTests.Events.PageEventsConsoleTests.PageEventsConsoleTests

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

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

PageEventsConsoleTests.cs

Source: PageEventsConsoleTests.cs Github

copy
1using System.Linq;
2using System.Collections.Generic;
3using System.Threading.Tasks;
4using Xunit;
5using Xunit.Abstractions;
6using PuppeteerSharp.Tests.Attributes;
7using PuppeteerSharp.Xunit;
8
9namespace PuppeteerSharp.Tests.PageTests.Events
10{
11    [Collection(TestConstants.TestFixtureCollectionName)]
12    public class PageEventsConsoleTests : PuppeteerPageBaseTest
13    {
14        public PageEventsConsoleTests(ITestOutputHelper output) : base(output)
15        {
16        }
17
18        [PuppeteerTest("page.spec.ts", "Page.Events.Console", "should work")]
19        [SkipBrowserFact(skipFirefox: true)]
20        public async Task ShouldWork()
21        {
22            ConsoleMessage message = null;
23
24            void EventHandler(object sender, ConsoleEventArgs e)
25            {
26                message = e.Message;
27                Page.Console -= EventHandler;
28            }
29
30            Page.Console += EventHandler;
31
32            await Page.EvaluateExpressionAsync("console.log('hello', 5, {foo: 'bar'})");
33
34            var obj = new Dictionary<string, object> { { "foo", "bar" } };
35
36            Assert.Equal("hello 5 [email protected]", message.Text);
37            Assert.Equal(ConsoleType.Log, message.Type);
38
39            Assert.Equal("hello", await message.Args[0].JsonValueAsync());
40            Assert.Equal(5, await message.Args[1].JsonValueAsync<float>());
41            Assert.Equal(obj, await message.Args[2].JsonValueAsync<Dictionary<string, object>>());
42            Assert.Equal("bar", (await message.Args[2].JsonValueAsync<dynamic>()).foo.ToString());
43        }
44
45        [PuppeteerTest("page.spec.ts", "Page.Events.Console", "should work for different console API calls")]
46        [SkipBrowserFact(skipFirefox: true)]
47        public async Task ShouldWorkForDifferentConsoleApiCalls()
48        {
49            var messages = new List<ConsoleMessage>();
50
51            Page.Console += (_, e) => messages.Add(e.Message);
52
53            await Page.EvaluateFunctionAsync(@"() => {
54              // A pair of time/timeEnd generates only one Console API call.
55              console.time('calling console.time');
56              console.timeEnd('calling console.time');
57              console.trace('calling console.trace');
58              console.dir('calling console.dir');
59              console.warn('calling console.warn');
60              console.error('calling console.error');
61              console.log(Promise.resolve('should not wait until resolved!'));
62            }");
63
64            Assert.Equal(new[]
65            {
66                ConsoleType.TimeEnd,
67                ConsoleType.Trace,
68                ConsoleType.Dir,
69                ConsoleType.Warning,
70                ConsoleType.Error,
71                ConsoleType.Log
72            }, messages
73                .Select(_ => _.Type)
74                .ToArray());
75
76            Assert.Contains("calling console.time", messages[0].Text);
77
78            Assert.Equal(new[]
79            {
80                "calling console.trace",
81                "calling console.dir",
82                "calling console.warn",
83                "calling console.error",
84                "[email protected]"
85            }, messages
86                .Skip(1)
87                .Select(msg => msg.Text)
88                .ToArray());
89        }
90
91        [PuppeteerTest("page.spec.ts", "Page.Events.Console", "should not fail for window object")]
92        [SkipBrowserFact(skipFirefox: true)]
93        public async Task ShouldNotFailForWindowObject()
94        {
95            var consoleTcs = new TaskCompletionSource<string>();
96
97            void EventHandler(object sender, ConsoleEventArgs e)
98            {
99                consoleTcs.TrySetResult(e.Message.Text);
100                Page.Console -= EventHandler;
101            }
102
103            Page.Console += EventHandler;
104
105            await Task.WhenAll(
106                consoleTcs.Task,
107                Page.EvaluateExpressionAsync("console.error(window)")
108            );
109
110            Assert.Equal("[email protected]", await consoleTcs.Task);
111        }
112
113        [PuppeteerTest("page.spec.ts", "Page.Events.Console", "should trigger correct Log")]
114        [SkipBrowserFact(skipFirefox: true)]
115        public async Task ShouldTriggerCorrectLog()
116        {
117            await Page.GoToAsync(TestConstants.AboutBlank);
118            var messageTask = new TaskCompletionSource<ConsoleMessage>();
119
120            Page.Console += (_, e) => messageTask.TrySetResult(e.Message);
121
122            await Page.EvaluateFunctionAsync("async url => fetch(url).catch(e => {})", TestConstants.EmptyPage);
123            var message = await messageTask.Task;
124            Assert.Contains("No 'Access-Control-Allow-Origin'", message.Text);
125
126            if (TestConstants.IsChrome)
127            {
128                Assert.Equal(ConsoleType.Error, message.Type);
129            }
130            else
131            {
132                Assert.Equal(ConsoleType.Warning, message.Type);
133            }
134        }
135
136        [PuppeteerTest("page.spec.ts", "Page.Events.Console", "should have location when fetch fails")]
137        [SkipBrowserFact(skipFirefox: true)]
138        public async Task ShouldHaveLocationWhenFetchFails()
139        {
140            await Page.GoToAsync(TestConstants.EmptyPage);
141            var consoleTask = new TaskCompletionSource<ConsoleEventArgs>();
142            Page.Console += (_, e) => consoleTask.TrySetResult(e);
143
144            await Task.WhenAll(
145                consoleTask.Task,
146                Page.SetContentAsync("<script>fetch('http://wat');</script>"));
147
148            var args = await consoleTask.Task;
149            Assert.Contains("ERR_NAME", args.Message.Text);
150            Assert.Equal(ConsoleType.Error, args.Message.Type);
151            Assert.Equal(new ConsoleMessageLocation
152            {
153                URL = "http://wat/",
154            }, args.Message.Location);
155        }
156
157        [PuppeteerTest("page.spec.ts", "Page.Events.Console", "should have location and stack trace for console API calls")]
158        [SkipBrowserFact(skipFirefox: true)]
159        public async Task ShouldHaveLocationForConsoleAPICalls()
160        {
161            await Page.GoToAsync(TestConstants.EmptyPage);
162            var consoleTask = new TaskCompletionSource<ConsoleEventArgs>();
163            Page.Console += (_, e) => consoleTask.TrySetResult(e);
164
165            await Task.WhenAll(
166                consoleTask.Task,
167                Page.GoToAsync(TestConstants.ServerUrl + "/consolelog.html"));
168
169            var args = await consoleTask.Task;
170            Assert.Equal("yellow", args.Message.Text);
171            Assert.Equal(ConsoleType.Log, args.Message.Type);
172            Assert.Equal(new ConsoleMessageLocation
173            {
174                URL = TestConstants.ServerUrl + "/consolelog.html",
175                LineNumber = 7,
176                ColumnNumber = 14
177            }, args.Message.Location);
178        }
179
180        [PuppeteerTest("page.spec.ts", "Page.Events.Console", "should not throw when there are console messages in detached iframes")]
181        [SkipBrowserFact(skipFirefox: true)]
182        public async Task ShouldNotThrowWhenThereAreConsoleMessagesInDetachedIframes()
183        {
184            await Page.GoToAsync(TestConstants.EmptyPage);
185            await Page.EvaluateFunctionAsync(@"async () =>
186            {
187                // 1. Create a popup that Puppeteer is not connected to.
188                const win = window.open(window.location.href, 'Title', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top=0,left=0');
189                await new Promise(x => win.onload = x);
190                // 2. In this popup, create an iframe that console.logs a message.
191                win.document.body.innerHTML = `<iframe src='/consolelog.html'></iframe>`;
192                const frame = win.document.querySelector('iframe');
193                await new Promise(x => frame.onload = x);
194                // 3. After that, remove the iframe.
195                frame.remove();
196            }");
197            var popupTarget = Page.BrowserContext.Targets().First(target => target != Page.Target);
198            // 4. Connect to the popup and make sure it doesn't throw.
199            await popupTarget.PageAsync();
200        }
201    }
202}
203
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

Trigger PageEventsConsoleTests code on LambdaTest Cloud Grid

Execute automation tests with PageEventsConsoleTests on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

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)