Best Puppeteer-sharp code snippet using PuppeteerSharp.PageCoverage.CSSCoverage
CSSCoverageTests.cs
Source:CSSCoverageTests.cs
...5using Newtonsoft.Json;6using PuppeteerSharp.PageCoverage;7using Xunit;8using Xunit.Abstractions;9namespace PuppeteerSharp.Tests.CSSCoverageTests10{11 [Collection("PuppeteerLoaderFixture collection")]12 public class CSSCoverageTests : PuppeteerPageBaseTest13 {14 public CSSCoverageTests(ITestOutputHelper output) : base(output)15 {16 }17 [Fact]18 public async Task ShouldWork()19 {20 await Page.Coverage.StartCSSCoverageAsync();21 await Page.GoToAsync(TestConstants.ServerUrl + "/csscoverage/simple.html");22 var coverage = await Page.Coverage.StopCSSCoverageAsync();23 Assert.Single(coverage);24 Assert.Contains("/csscoverage/simple.html", coverage[0].Url);25 Assert.Equal(new CoverageEntryRange[]26 {27 new CoverageEntryRange28 {29 Start = 1,30 End = 2231 }32 }, coverage[0].Ranges);33 var range = coverage[0].Ranges[0];34 Assert.Equal("div { color: green; }", coverage[0].Text.Substring(range.Start, range.End - range.Start));35 }36 [Fact]37 public async Task ShouldReportSourceUrls()38 {39 await Page.Coverage.StartCSSCoverageAsync();40 await Page.GoToAsync(TestConstants.ServerUrl + "/csscoverage/sourceurl.html");41 var coverage = await Page.Coverage.StopCSSCoverageAsync();42 Assert.Single(coverage);43 Assert.Equal("nicename.css", coverage[0].Url);44 }45 [Fact]46 public async Task ShouldReportMultipleStylesheets()47 {48 await Page.Coverage.StartCSSCoverageAsync();49 await Page.GoToAsync(TestConstants.ServerUrl + "/csscoverage/multiple.html");50 var coverage = await Page.Coverage.StopCSSCoverageAsync();51 Assert.Equal(2, coverage.Length);52 var orderedList = coverage.OrderBy(c => c.Url);53 Assert.Contains("/csscoverage/stylesheet1.css", orderedList.ElementAt(0).Url);54 Assert.Contains("/csscoverage/stylesheet2.css", orderedList.ElementAt(1).Url);55 }56 [Fact]57 public async Task ShouldReportStylesheetsThatHaveNoCoverage()58 {59 await Page.Coverage.StartCSSCoverageAsync();60 await Page.GoToAsync(TestConstants.ServerUrl + "/csscoverage/unused.html");61 var coverage = await Page.Coverage.StopCSSCoverageAsync();62 Assert.Single(coverage);63 var entry = coverage[0];64 Assert.Contains("unused.css", entry.Url);65 Assert.Empty(entry.Ranges);66 }67 [Fact]68 public async Task ShouldWorkWithMediaQueries()69 {70 await Page.Coverage.StartCSSCoverageAsync();71 await Page.GoToAsync(TestConstants.ServerUrl + "/csscoverage/media.html");72 var coverage = await Page.Coverage.StopCSSCoverageAsync();73 Assert.Single(coverage);74 var entry = coverage[0];75 Assert.Contains("/csscoverage/media.html", entry.Url);76 Assert.Equal(new CoverageEntryRange[]77 {78 new CoverageEntryRange79 {80 Start = 17,81 End = 3882 }83 }, coverage[0].Ranges);84 }85 [Fact]86 public async Task ShouldWorkWithComplicatedUsecases()87 {88 const string involved = @"[89 {90 ""Url"": ""http://localhost:<PORT>/csscoverage/involved.html"",91 ""Ranges"": [92 {93 ""Start"": 149,94 ""End"": 29795 },96 {97 ""Start"": 327,98 ""End"": 43399 }100 ],101 ""Text"": ""\n @charset \""utf - 8\"";\n@namespace svg url(http://www.w3.org/2000/svg);\n@font-face {\n font-family: \""Example Font\"";\n src: url(\""./Dosis-Regular.ttf\"");\n}\n\n#fluffy {\n border: 1px solid black;\n z-index: 1;\n /* -webkit-disabled-property: rgb(1, 2, 3) */\n -lol-cats: \""dogs\"" /* non-existing property */\n}\n\n@media (min-width: 1px) {\n span {\n -webkit-border-radius: 10px;\n font-family: \""Example Font\"";\n animation: 1s identifier;\n }\n}\n""102 }103 ]";104 await Page.Coverage.StartCSSCoverageAsync();105 await Page.GoToAsync(TestConstants.ServerUrl + "/csscoverage/involved.html");106 var coverage = await Page.Coverage.StopCSSCoverageAsync();107 Assert.Equal(108 TestUtils.CompressText(involved),109 Regex.Replace(TestUtils.CompressText(JsonConvert.SerializeObject(coverage)), @":\d{4}\/", ":<PORT>/"));110 }111 [Fact]112 public async Task ShouldIgnoreInjectedStylesheets()113 {114 await Page.Coverage.StartCSSCoverageAsync();115 await Page.AddStyleTagAsync(new AddTagOptions116 {117 Content = "body { margin: 10px;}"118 });119 // trigger style recalc120 var margin = await Page.EvaluateExpressionAsync<string>("window.getComputedStyle(document.body).margin");121 Assert.Equal("10px", margin);122 var coverage = await Page.Coverage.StopCSSCoverageAsync();123 Assert.Empty(coverage);124 }125 }126}...
CSSCoverage.cs
Source:CSSCoverage.cs
...5using PuppeteerSharp.Helpers;6using PuppeteerSharp.Messaging;7namespace PuppeteerSharp.PageCoverage8{9 internal class CSSCoverage10 {11 private readonly CDPSession _client;12 private readonly Dictionary<string, string> _stylesheetURLs;13 private readonly Dictionary<string, string> _stylesheetSources;14 private readonly ILogger _logger;15 private bool _enabled;16 private bool _resetOnNavigation;17 public CSSCoverage(CDPSession client)18 {19 _client = client;20 _enabled = false;21 _stylesheetURLs = new Dictionary<string, string>();22 _stylesheetSources = new Dictionary<string, string>();23 _logger = _client.Connection.LoggerFactory.CreateLogger<CSSCoverage>();24 _resetOnNavigation = false;25 }26 internal Task StartAsync(CoverageStartOptions options)27 {28 if (_enabled)29 {30 throw new InvalidOperationException("CSSCoverage is already enabled");31 }32 _resetOnNavigation = options.ResetOnNavigation;33 _enabled = true;34 _stylesheetURLs.Clear();35 _stylesheetSources.Clear();36 _client.MessageReceived += client_MessageReceived;37 return Task.WhenAll(38 _client.SendAsync("DOM.enable"),39 _client.SendAsync("CSS.enable"),40 _client.SendAsync("CSS.startRuleUsageTracking")41 );42 }43 internal async Task<CoverageEntry[]> StopAsync()44 {45 if (!_enabled)46 {47 throw new InvalidOperationException("CSSCoverage is not enabled");48 }49 _enabled = false;50 var ruleTrackingResponseTask = _client.SendAsync<CSSStopRuleUsageTrackingResponse>("CSS.stopRuleUsageTracking");51 await Task.WhenAll(52 ruleTrackingResponseTask,53 _client.SendAsync("CSS.disable"),54 _client.SendAsync("DOM.disable")55 ).ConfigureAwait(false);56 _client.MessageReceived -= client_MessageReceived;57 var styleSheetIdToCoverage = new Dictionary<string, List<CoverageResponseRange>>();58 foreach (var entry in ruleTrackingResponseTask.Result.RuleUsage)59 {60 styleSheetIdToCoverage.TryGetValue(entry.StyleSheetId, out var ranges);61 if (ranges == null)...
Coverage.cs
Source:Coverage.cs
...9 /// </summary>10 public class Coverage11 {12 private readonly JSCoverage _jsCoverage;13 private readonly CSSCoverage _cssCoverage;14 internal Coverage(CDPSession client)15 {16 _jsCoverage = new JSCoverage(client);17 _cssCoverage = new CSSCoverage(client);18 }19 /// <summary>20 /// Starts JS coverage21 /// </summary>22 /// <param name="options">Set of configurable options for coverage</param>23 /// <returns>A task that resolves when coverage is started</returns>24 public Task StartJSCoverageAsync(CoverageStartOptions options = null)25 => _jsCoverage.StartAsync(options ?? new CoverageStartOptions());26 /// <summary>27 /// Stops JS coverage and returns coverage reports for all scripts28 /// </summary>29 /// <returns>Task that resolves to the array of coverage reports for all stylesheets</returns>30 /// <remarks>31 /// JavaScript Coverage doesn't include anonymous scripts by default; however, scripts with sourceURLs are reported.32 /// </remarks>33 public Task<CoverageEntry[]> StopJSCoverageAsync() => _jsCoverage.StopAsync();34 /// <summary>35 /// Starts CSS coverage36 /// </summary>37 /// <param name="options">Set of configurable options for coverage</param>38 /// <returns>A task that resolves when coverage is started</returns>39 public Task StartCSSCoverageAsync(CoverageStartOptions options = null)40 => _cssCoverage.StartAsync(options ?? new CoverageStartOptions());41 /// <summary>42 /// Stops JS coverage and returns coverage reports for all non-anonymous scripts43 /// </summary>44 /// <returns>Task that resolves to the array of coverage reports for all stylesheets</returns>45 /// <remarks>46 /// JavaScript Coverage doesn't include anonymous scripts; however, scripts with sourceURLs are reported.47 /// </remarks>48 public Task<CoverageEntry[]> StopCSSCoverageAsync() => _cssCoverage.StopAsync();49 internal static CoverageEntryRange[] ConvertToDisjointRanges(List<CoverageResponseRange> nestedRanges)50 {51 var points = new List<CoverageEntryPoint>();52 foreach (var range in nestedRanges)53 {54 points.Add(new CoverageEntryPoint55 {56 Offset = range.StartOffset,57 Type = 0,58 Range = range59 });60 points.Add(new CoverageEntryPoint61 {62 Offset = range.EndOffset,...
CSSResetOnNavigationTests.cs
Source:CSSResetOnNavigationTests.cs
...4using Newtonsoft.Json;5using PuppeteerSharp.PageCoverage;6using Xunit;7using Xunit.Abstractions;8namespace PuppeteerSharp.Tests.CSSCoverageTests9{10 [Collection("PuppeteerLoaderFixture collection")]11 public class CSSResetOnNavigationTests : PuppeteerPageBaseTest12 {13 public CSSResetOnNavigationTests(ITestOutputHelper output) : base(output)14 {15 }16 [Fact]17 public async Task ShouldReportStylesheetsAcrossNavigationsWhenDisabled()18 {19 await Page.Coverage.StartCSSCoverageAsync(new CoverageStartOptions20 {21 ResetOnNavigation = false22 });23 await Page.GoToAsync(TestConstants.ServerUrl + "/csscoverage/multiple.html");24 await Page.GoToAsync(TestConstants.EmptyPage);25 var coverage = await Page.Coverage.StopCSSCoverageAsync();26 Assert.Equal(2, coverage.Length);27 }28 [Fact]29 public async Task ShouldNotReportScriptsAcrossNavigationsWhenEnabled()30 {31 await Page.Coverage.StartCSSCoverageAsync();32 await Page.GoToAsync(TestConstants.ServerUrl + "/csscoverage/multiple.html");33 await Page.GoToAsync(TestConstants.EmptyPage);34 var coverage = await Page.Coverage.StopCSSCoverageAsync();35 Assert.Empty(coverage);36 }37 }38}...
CSSCoverage
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using PuppeteerSharp;7using PuppeteerSharp.PageCoverage;8using System.IO;9{10 {11 static void Main(string[] args)12 {13 MainAsync().Wait();14 }15 static async Task MainAsync()16 {17 var browser = await Puppeteer.LaunchAsync(new LaunchOptions18 {19 });20 var page = await browser.NewPageAsync();21 await page.EvaluateFunctionAsync(@"() => {22 const style = document.createElement('style');23 style.type = 'text/css';24 style.appendChild(document.createTextNode('body {background-color: #000;}'));25 document.head.appendChild(style);26 }");27 var coverage = await page.Coverage.StartCSSCoverageAsync();28 var cssCoverage = await page.Coverage.StopCSSCoverageAsync();29 var totalBytes = 0;30 var usedBytes = 0;31 foreach (var entry in cssCoverage)32 {33 totalBytes += entry.Text.Length;34 foreach (var range in entry.Ranges)35 {36 usedBytes += range.End - range.Start - 1;37 }38 }39 Console.WriteLine($"Bytes used: {usedBytes} / {totalBytes}");40 await browser.CloseAsync();41 }42 }43}44using System;45using System.Collections.Generic;46using System.Linq;47using System.Text;48using System.Threading.Tasks;49using PuppeteerSharp;50using PuppeteerSharp.PageCoverage;51using System.IO;52{53 {54 static void Main(string[] args)55 {56 MainAsync().Wait();57 }58 static async Task MainAsync()59 {60 var browser = await Puppeteer.LaunchAsync(new LaunchOptions61 {62 });63 var page = await browser.NewPageAsync();64 await page.EvaluateFunctionAsync(@"() => {65 const style = document.createElement('style');
CSSCoverage
Using AI Code Generation
1using PuppeteerSharp;2using PuppeteerSharp.PageCoverage;3using System;4using System.Collections.Generic;5using System.IO;6using System.Linq;7using System.Text;8using System.Threading.Tasks;9{10 {11 static void Main(string[] args)12 {13 MainAsync().Wait();14 }15 static async Task MainAsync()16 {17 var options = new LaunchOptions { Headless = true };18 using (var browser = await Puppeteer.LaunchAsync(options))19 using (var page = await browser.NewPageAsync())20 {21 var coverage = await page.Coverage.StartCSSCoverageAsync();22 var entries = await page.Coverage.StopCSSCoverageAsync();23 foreach (var entry in entries)24 {25 Console.WriteLine($"{entry.Url} {entry.Ranges.Length} {entry.Text}");26 }27 }28 }29 }30}
CSSCoverage
Using AI Code Generation
1var cssCoverage = await page.Coverage.StartCSSCoverageAsync();2var cssCoverageResult = await page.Coverage.StopCSSCoverageAsync();3var cssCoverageData = cssCoverageResult.SelectMany(x => x.Ranges).ToList();4var cssCoverage = await page.Coverage.StartCSSCoverageAsync();5var cssCoverageResult = await page.Coverage.StopCSSCoverageAsync();6var cssCoverageData = cssCoverageResult.SelectMany(x => x.Ranges).ToList();7var cssCoverage = await page.Coverage.StartCSSCoverageAsync();8var cssCoverageResult = await page.Coverage.StopCSSCoverageAsync();9var cssCoverageData = cssCoverageResult.SelectMany(x => x.Ranges).ToList();10var cssCoverage = await page.Coverage.StartCSSCoverageAsync();11var cssCoverageResult = await page.Coverage.StopCSSCoverageAsync();12var cssCoverageData = cssCoverageResult.SelectMany(x => x.Ranges).ToList();13var cssCoverage = await page.Coverage.StartCSSCoverageAsync();14var cssCoverageResult = await page.Coverage.StopCSSCoverageAsync();15var cssCoverageData = cssCoverageResult.SelectMany(x => x.Ranges).ToList();16var cssCoverage = await page.Coverage.StartCSSCoverageAsync();17var cssCoverageResult = await page.Coverage.StopCSSCoverageAsync();18var cssCoverageData = cssCoverageResult.SelectMany(x => x.Ranges).ToList();
CSSCoverage
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true, Args = new string[] { "--no-sandbox" } });9 var page = await browser.NewPageAsync();10 var coverage = await CSSCoverage.StartJSCoverageAsync(page);11 var cssCoverage = await CSSCoverage.StopJSCoverageAsync(coverage);12 foreach (var entry in cssCoverage)13 {14 Console.WriteLine(entry.Url);15 foreach (var range in entry.Ranges)16 {17 Console.WriteLine(range.Start);18 Console.WriteLine(range.End);19 }20 }21 await browser.CloseAsync();22 }23 }24}25using System;26using System.Threading.Tasks;27using PuppeteerSharp;28{29 {30 static async Task Main(string[] args)31 {32 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true, Args = new string[] { "--no-sandbox" } });33 var page = await browser.NewPageAsync();34 await CSSCoverage.StartJSCoverageAsync(page);35 var cssCoverage = await CSSCoverage.StopJSCoverageAsync(page);36 foreach (var entry in cssCoverage)37 {38 Console.WriteLine(entry.Url);39 foreach (var range in entry.Ranges)40 {41 Console.WriteLine(range.Start);42 Console.WriteLine(range.End);43 }44 }45 await browser.CloseAsync();46 }47 }48}49using System;50using System.Threading.Tasks;51using PuppeteerSharp;52{
CSSCoverage
Using AI Code Generation
1{2 public async Task GetCSSCoverageDetails(string url)3 {4 var browser = await Puppeteer.LaunchAsync(new LaunchOptions5 {6 Args = new string[] { "--disable-gpu", "--no-sandbox" }7 });8 var page = await browser.NewPageAsync();9 await page.Coverage.StartCSSCoverageAsync();10 await page.GoToAsync(url);11 var cssCoverage = await page.Coverage.StopCSSCoverageAsync();12 await browser.CloseAsync();13 foreach (var entry in cssCoverage)14 {15 Console.WriteLine(entry.Url);16 Console.WriteLine(entry.Ranges);17 Console.WriteLine(entry.Text);18 }19 }20}21{22 public async Task CallCSSCoverageMethods()23 {24 CSSCoverage cssCoverage = new CSSCoverage();25 }26}27{28 public static async Task Main(string[] args)29 {30 CallCSSCoverage callCSSCoverage = new CallCSSCoverage();31 await callCSSCoverage.CallCSSCoverageMethods();32 }33}34[{"start":0,"end":3022}]35.css-1dbjc4n.r-1awozwy.r-18u37iz.r-1wtj0ep{display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-webkit-flex-direction:
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!