Best Puppeteer-sharp code snippet using PuppeteerSharp.EvaluationFailedException.EvaluationFailedException
PageEvaluateTests.cs
Source:PageEvaluateTests.cs
...86 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should throw when evaluation triggers reload")]87 [SkipBrowserFact(skipFirefox: true)]88 public async Task ShouldThrowWhenEvaluationTriggersReload()89 {90 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(() =>91 {92 return Page.EvaluateFunctionAsync(@"() => {93 location.reload();94 return new Promise(() => {});95 }");96 });97 Assert.Contains("Protocol error", exception.Message);98 }99 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should work right after framenavigated")]100 [PuppeteerFact]101 public async Task ShouldWorkRightAfterFrameNavigated()102 {103 Task<int> frameEvaluation = null;104 Page.FrameNavigated += (_, e) =>105 {106 frameEvaluation = e.Frame.EvaluateFunctionAsync<int>("() => 6 * 7");107 };108 await Page.GoToAsync(TestConstants.EmptyPage);109 Assert.Equal(42, await frameEvaluation);110 }111 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should work from-inside an exposed function")]112 [SkipBrowserFact(skipFirefox: true)]113 public async Task ShouldWorkFromInsideAnExposedFunction()114 {115 await Page.ExposeFunctionAsync("callController", async (int a, int b) =>116 {117 return await Page.EvaluateFunctionAsync<int>("(a, b) => a * b", a, b);118 });119 var result = await Page.EvaluateFunctionAsync<int>(@"async function() {120 return await callController(9, 3);121 }");122 Assert.Equal(27, result);123 }124 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should reject promise with exception")]125 [PuppeteerFact]126 public async Task ShouldRejectPromiseWithExeption()127 {128 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(() =>129 {130 return Page.EvaluateFunctionAsync("() => not_existing_object.property");131 });132 Assert.Contains("not_existing_object", exception.Message);133 }134 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should support thrown strings as error messages")]135 [PuppeteerFact]136 public async Task ShouldSupportThrownStringsAsErrorMessages()137 {138 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(139 () => Page.EvaluateExpressionAsync("throw 'qwerty'"));140 Assert.Contains("qwerty", exception.Message);141 }142 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should support thrown numbers as error messages")]143 [PuppeteerFact]144 public async Task ShouldSupportThrownNumbersAsErrorMessages()145 {146 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(147 () => Page.EvaluateExpressionAsync("throw 100500"));148 Assert.Contains("100500", exception.Message);149 }150 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should return complex objects")]151 [PuppeteerFact]152 public async Task SouldReturnComplexObjects()153 {154 dynamic obj = new155 {156 foo = "bar!"157 };158 var result = await Page.EvaluateFunctionAsync("a => a", obj);159 Assert.Equal("bar!", result.foo.ToString());160 }161 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should return BigInt")]162 [PuppeteerFact]163 public async Task ShouldReturnBigInt()164 {165 var result = await Page.EvaluateFunctionAsync<object>("() => BigInt(42)");166 Assert.Equal(new BigInteger(42), result);167 }168 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should return NaN")]169 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should return -0")]170 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should return Infinity")]171 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should return -Infinity")]172 [Theory]173 [InlineData("() => NaN", double.NaN)] //ShouldReturnNaN174 [InlineData("() => -0", -0)] //ShouldReturnNegative0175 [InlineData("() => Infinity", double.PositiveInfinity)] //ShouldReturnInfinity176 [InlineData("() => -Infinity", double.NegativeInfinity)] //ShouldReturnNegativeInfinty177 public async Task BasicEvaluationTest(string script, object expected)178 {179 var result = await Page.EvaluateFunctionAsync<object>(script);180 Assert.Equal(expected, result);181 }182 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should accept \"undefined\" as one of multiple parameters")]183 [PuppeteerFact]184 public async Task ShouldAcceptNullAsOneOfMultipleParameters()185 {186 var result = await Page.EvaluateFunctionAsync<bool>(187 "(a, b) => Object.is(a, null) && Object.is(b, 'foo')",188 null,189 "foo");190 Assert.True(result);191 }192 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should return undefined for non-serializable objects")]193 [SkipBrowserFact(skipFirefox: true)]194 public async Task ShouldReturnNullForNonSerializableObjects()195 => Assert.Null(await Page.EvaluateFunctionAsync("() => window"));196 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should fail for circular object")]197 [SkipBrowserFact(skipFirefox: true)]198 public async Task ShouldFailForCircularObject()199 {200 var result = await Page.EvaluateFunctionAsync(@"() => {201 const a = {};202 const b = {a};203 a.b = b;204 return a;205 }");206 Assert.Null(result);207 }208 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should be able to throw a tricky error")]209 [SkipBrowserFact(skipFirefox: true)]210 public async Task ShouldBeAbleToThrowATrickyError()211 {212 var windowHandle = await Page.EvaluateFunctionHandleAsync("() => window");213 PuppeteerException exception = await Assert.ThrowsAsync<MessageException>(() => windowHandle.JsonValueAsync());214 var errorText = exception.Message;215 exception = await Assert.ThrowsAsync<EvaluationFailedException>(() => Page.EvaluateFunctionAsync(@"errorText =>216 {217 throw new Error(errorText);218 }", errorText));219 Assert.Contains(errorText, exception.Message);220 }221 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should accept a string")]222 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should accept a string with semi colons")]223 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should accept a string with comments")]224 [Theory]225 [InlineData("1 + 2;", 3)]226 [InlineData("1 + 5;", 6)]227 [InlineData("2 + 5\n// do some math!'", 7)]228 public async Task BasicIntExressionEvaluationTest(string script, object expected)229 {230 var result = await Page.EvaluateExpressionAsync<int>(script);231 Assert.Equal(expected, result);232 }233 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should accept element handle as an argument")]234 [PuppeteerFact]235 public async Task ShouldAcceptElementHandleAsAnArgument()236 {237 await Page.SetContentAsync("<section>42</section>");238 var element = await Page.QuerySelectorAsync("section");239 var text = await Page.EvaluateFunctionAsync<string>("e => e.textContent", element);240 Assert.Equal("42", text);241 }242 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should throw if underlying element was disposed")]243 [PuppeteerFact]244 public async Task ShouldThrowIfUnderlyingElementWasDisposed()245 {246 await Page.SetContentAsync("<section>39</section>");247 var element = await Page.QuerySelectorAsync("section");248 Assert.NotNull(element);249 await element.DisposeAsync();250 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(()251 => Page.EvaluateFunctionAsync<string>("e => e.textContent", element));252 Assert.Contains("JSHandle is disposed", exception.Message);253 }254 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should throw if elementHandles are from other frames")]255 [SkipBrowserFact(skipFirefox: true)]256 public async Task ShouldThrowIfElementHandlesAreFromOtherFrames()257 {258 await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);259 var bodyHandle = await Page.FirstChildFrame().QuerySelectorAsync("body");260 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(()261 => Page.EvaluateFunctionAsync<string>("body => body.innerHTML", bodyHandle));262 Assert.Contains("JSHandles can be evaluated only in the context they were created", exception.Message);263 }264 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should simulate a user gesture")]265 [SkipBrowserFact(skipFirefox: true)]266 public async Task ShouldSimulateAUserGesture()267 => Assert.True(await Page.EvaluateFunctionAsync<bool>(@"() => {268 document.body.appendChild(document.createTextNode('test'));269 document.execCommand('selectAll');270 return document.execCommand('copy');271 }"));272 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should throw a nice error after a navigation")]273 [SkipBrowserFact(skipFirefox: true)]274 public async Task ShouldThrowANiceErrorAfterANavigation()275 {276 var executionContext = await Page.MainFrame.GetExecutionContextAsync();277 await Task.WhenAll(278 Page.WaitForNavigationAsync(),279 executionContext.EvaluateFunctionAsync("() => window.location.reload()")280 );281 var ex = await Assert.ThrowsAsync<EvaluationFailedException>(() =>282 {283 return executionContext.EvaluateFunctionAsync("() => null");284 });285 Assert.Contains("navigation", ex.Message);286 }287 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should not throw an error when evaluation does a navigation")]288 [SkipBrowserFact(skipFirefox: true)]289 public async Task ShouldNotThrowAnErrorWhenEvaluationDoesANavigation()290 {291 await Page.GoToAsync(TestConstants.ServerUrl + "/one-style.html");292 var result = await Page.EvaluateFunctionAsync<int[]>(@"() =>293 {294 window.location = '/empty.html';295 return [42];296 }");297 Assert.Equal(new[] { 42 }, result);298 }299 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should transfer 100Mb of data from page to node.js")]300 [PuppeteerFact]301 public async Task ShouldTransfer100MbOfDataFromPage()302 {303 var a = await Page.EvaluateFunctionAsync<string>("() => Array(100 * 1024 * 1024 + 1).join('a')");304 Assert.Equal(100 * 1024 * 1024, a.Length);305 }306 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should throw error with detailed information on exception inside promise ")]307 [PuppeteerFact]308 public async Task ShouldThrowErrorWithDetailedInformationOnExceptionInsidePromise()309 {310 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(() =>311 Page.EvaluateFunctionAsync(312 @"() => new Promise(() => {313 throw new Error('Error in promise');314 })"));315 Assert.Contains("Error in promise", exception.Message);316 }317 [PuppeteerFact]318 public async Task ShouldWorkWithDifferentSerializerSettings()319 {320 var result = await Page.EvaluateFunctionAsync<ComplexObjectTestClass>("() => { return { foo: 'bar' }}");321 Assert.Equal("bar", result.Foo);322 result = (await Page.EvaluateFunctionAsync<JToken>("() => { return { Foo: 'bar' }}"))323 .ToObject<ComplexObjectTestClass>(new JsonSerializerSettings());324 Assert.Equal("bar", result.Foo);...
EvaluateTests.cs
Source:EvaluateTests.cs
...70 => Assert.Equal(42, await Page.EvaluateFunctionAsync<int>("a => a['ä¸æå符']", new Dictionary<string, int> { ["ä¸æå符"] = 42 }));71 [Fact]72 public async Task ShouldThrowWhenEvaluationTriggersReload()73 {74 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(() =>75 {76 return Page.EvaluateFunctionAsync(@"() => {77 location.reload();78 return new Promise(() => {});79 }");80 });81 Assert.Contains("Protocol error", exception.Message);82 }83 [Fact]84 public async Task ShouldWorkRightAfterFrameNavigated()85 {86 Task<int> frameEvaluation = null;87 Page.FrameNavigated += (sender, e) =>88 {89 frameEvaluation = e.Frame.EvaluateFunctionAsync<int>("() => 6 * 7");90 };91 await Page.GoToAsync(TestConstants.EmptyPage);92 Assert.Equal(42, await frameEvaluation);93 }94 [Fact]95 public async Task ShouldWorkFromInsideAnExposedFunction()96 {97 await Page.ExposeFunctionAsync("callController", async (int a, int b) =>98 {99 return await Page.EvaluateFunctionAsync<int>("(a, b) => a * b", a, b);100 });101 var result = await Page.EvaluateFunctionAsync<int>(@"async function() {102 return await callController(9, 3);103 }");104 Assert.Equal(27, result);105 }106 [Fact]107 public async Task ShouldRejectPromiseWithExeption()108 {109 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(() =>110 {111 return Page.EvaluateFunctionAsync("() => not_existing_object.property");112 });113 Assert.Contains("not_existing_object", exception.Message);114 }115 [Fact]116 public async Task ShouldSupportThrownStringsAsErrorMessages()117 {118 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(119 () => Page.EvaluateExpressionAsync("throw 'qwerty'"));120 Assert.Contains("qwerty", exception.Message);121 }122 [Fact]123 public async Task ShouldSupportThrownNumbersAsErrorMessages()124 {125 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(126 () => Page.EvaluateExpressionAsync("throw 100500"));127 Assert.Contains("100500", exception.Message);128 }129 [Fact]130 public async Task SouldReturnComplexObjects()131 {132 dynamic obj = new133 {134 foo = "bar!"135 };136 var result = await Page.EvaluateFunctionAsync("a => a", obj);137 Assert.Equal("bar!", result.foo.ToString());138 }139 [Fact]140 public async Task ShouldReturnBigInt()141 {142 var result = await Page.EvaluateFunctionAsync<object>("() => BigInt(42)");143 Assert.Equal(new BigInteger(42), result);144 }145 [Theory]146 [InlineData("() => NaN", double.NaN)] //ShouldReturnNaN147 [InlineData("() => -0", -0)] //ShouldReturnNegative0148 [InlineData("() => Infinity", double.PositiveInfinity)] //ShouldReturnInfinity149 [InlineData("() => -Infinity", double.NegativeInfinity)] //ShouldReturnNegativeInfinty150 public async Task BasicEvaluationTest(string script, object expected)151 {152 var result = await Page.EvaluateFunctionAsync<object>(script);153 Assert.Equal(expected, result);154 }155 [Fact]156 public async Task ShouldAcceptNullAsOneOfMultipleParameters()157 {158 var result = await Page.EvaluateFunctionAsync<bool>(159 "(a, b) => Object.is(a, null) && Object.is(b, 'foo')",160 null,161 "foo");162 Assert.True(result);163 }164 [Fact]165 public async Task ShouldReturnNullForNonSerializableObjects()166 => Assert.Null(await Page.EvaluateFunctionAsync("() => window"));167 [Fact]168 public async Task ShouldFailForCircularObject()169 {170 var result = await Page.EvaluateFunctionAsync(@"() => {171 const a = {};172 const b = {a};173 a.b = b;174 return a;175 }");176 Assert.Null(result);177 }178 [Fact]179 public async Task ShouldBeAbleToThrowATrickyError()180 {181 var windowHandle = await Page.EvaluateFunctionHandleAsync("() => window");182 PuppeteerException exception = await Assert.ThrowsAsync<MessageException>(() => windowHandle.JsonValueAsync());183 var errorText = exception.Message;184 exception = await Assert.ThrowsAsync<EvaluationFailedException>(() => Page.EvaluateFunctionAsync(@"errorText =>185 {186 throw new Error(errorText);187 }", errorText));188 Assert.Contains(errorText, exception.Message);189 }190 [Theory]191 [InlineData("1 + 5;", 6)] //ShouldAcceptSemiColons192 [InlineData("2 + 5\n// do some math!'", 7)] //ShouldAceptStringComments193 public async Task BasicIntExressionEvaluationTest(string script, object expected)194 {195 var result = await Page.EvaluateExpressionAsync<int>(script);196 Assert.Equal(expected, result);197 }198 [Fact]199 public async Task ShouldAcceptElementHandleAsAnArgument()200 {201 await Page.SetContentAsync("<section>42</section>");202 var element = await Page.QuerySelectorAsync("section");203 var text = await Page.EvaluateFunctionAsync<string>("e => e.textContent", element);204 Assert.Equal("42", text);205 }206 [Fact]207 public async Task ShouldThrowIfUnderlyingElementWasDisposed()208 {209 await Page.SetContentAsync("<section>39</section>");210 var element = await Page.QuerySelectorAsync("section");211 Assert.NotNull(element);212 await element.DisposeAsync();213 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(()214 => Page.EvaluateFunctionAsync<string>("e => e.textContent", element));215 Assert.Contains("JSHandle is disposed", exception.Message);216 }217 [Fact]218 public async Task ShouldThrowIfElementHandlesAreFromOtherFrames()219 {220 await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);221 var bodyHandle = await Page.FirstChildFrame().QuerySelectorAsync("body");222 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(()223 => Page.EvaluateFunctionAsync<string>("body => body.innerHTML", bodyHandle));224 Assert.Contains("JSHandles can be evaluated only in the context they were created", exception.Message);225 }226 [Fact]227 public async Task ShouldSimulateAUserGesture()228 => Assert.True(await Page.EvaluateFunctionAsync<bool>(@"() => {229 document.body.appendChild(document.createTextNode('test'));230 document.execCommand('selectAll');231 return document.execCommand('copy'); 232 }"));233 [Fact]234 public async Task ShouldThrowANiceErrorAfterANavigation()235 {236 var executionContext = await Page.MainFrame.GetExecutionContextAsync();237 await Task.WhenAll(238 Page.WaitForNavigationAsync(),239 executionContext.EvaluateFunctionAsync("() => window.location.reload()")240 );241 var ex = await Assert.ThrowsAsync<EvaluationFailedException>(() =>242 {243 return executionContext.EvaluateFunctionAsync("() => null");244 });245 Assert.Contains("navigation", ex.Message);246 }247 [Fact]248 public async Task ShouldNotThrowAnErrorWhenEvaluationDoesANavigation()249 {250 await Page.GoToAsync(TestConstants.ServerUrl + "/one-style.html");251 var result = await Page.EvaluateFunctionAsync<int[]>(@"() =>252 {253 window.location = '/empty.html';254 return [42];255 }");256 Assert.Equal(new[] { 42 }, result);257 }258 /// <summary>259 /// Original Name "should transfer 100Mb of data from page to node.js"260 /// </summary>261 [Fact]262 public async Task ShouldTransfer100MbOfDataFromPage()263 {264 var a = await Page.EvaluateFunctionAsync<string>("() => Array(100 * 1024 * 1024 + 1).join('a')");265 Assert.Equal(100 * 1024 * 1024, a.Length);266 }267 [Fact]268 public async Task ShouldThrowErrorWithDetailedInformationOnExceptionInsidePromise()269 {270 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(() =>271 Page.EvaluateFunctionAsync(272 @"() => new Promise(() => {273 throw new Error('Error in promise');274 })"));275 Assert.Contains("Error in promise", exception.Message);276 }277 [Fact]278 public async Task ShouldWorkWithDifferentSerializerSettings()279 {280 var result = await Page.EvaluateFunctionAsync<ComplexObjectTestClass>("() => { return { foo: 'bar' }}");281 Assert.Equal("bar", result.Foo);282 result = (await Page.EvaluateFunctionAsync<JToken>("() => { return { Foo: 'bar' }}"))283 .ToObject<ComplexObjectTestClass>(new JsonSerializerSettings());284 Assert.Equal("bar", result.Foo);285 result = await Page.EvaluateExpressionAsync<ComplexObjectTestClass>("var obj = { foo: 'bar' }; obj;");286 Assert.Equal("bar", result.Foo);287 result = (await Page.EvaluateExpressionAsync<JToken>("var obj = { Foo: 'bar' }; obj;"))288 .ToObject<ComplexObjectTestClass>(new JsonSerializerSettings());289 Assert.Equal("bar", result.Foo);290 }291 [Fact]292 public async Task ShouldProperlyIgnoreUndefinedFields()293 {294 var result = await Page.EvaluateFunctionAsync<Dictionary<string, object>>("() => ({a: undefined})");295 Assert.Empty(result);296 }297 [Fact]298 public async Task ShouldProperlySerializeNullFields()299 {300 var result = await Page.EvaluateFunctionAsync<Dictionary<string, object>>("() => ({a: null})");301 Assert.True(result.ContainsKey("a"));302 Assert.Null(result["a"]);303 }304 [Fact]305 public async Task ShouldAcceptObjectHandleAsAnArgument()306 {307 var navigatorHandle = await Page.EvaluateExpressionHandleAsync("navigator");308 var text = await Page.EvaluateFunctionAsync<string>("e => e.userAgent", navigatorHandle);309 Assert.Contains("Mozilla", text);310 }311 [Fact]312 public async Task ShouldAcceptObjectHandleToPrimitiveTypes()313 {314 var aHandle = await Page.EvaluateExpressionHandleAsync("5");315 var isFive = await Page.EvaluateFunctionAsync<bool>("e => Object.is(e, 5)", aHandle);316 Assert.True(isFive);317 }318 [Fact]319 public async Task ShouldWarnOnNestedObjectHandles()320 {321 var handle = await Page.EvaluateFunctionHandleAsync("() => document.body");322 var elementHandle = handle as ElementHandle;323 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(()324 => Page.EvaluateFunctionHandleAsync(325 "opts => opts.elem.querySelector('p')",326 new { elem = handle }));327 Assert.Contains("Are you passing a nested JSHandle?", exception.Message);328 //Check with ElementHandle329 exception = await Assert.ThrowsAsync<EvaluationFailedException>(()330 => Page.EvaluateFunctionHandleAsync(331 "opts => opts.elem.querySelector('p')",332 new { elem = elementHandle }));333 Assert.Contains("Are you passing a nested JSHandle?", exception.Message);334 }335 [Fact]336 public async Task ShouldWorkWithoutGenerics()337 {338 Assert.NotNull(await Page.EvaluateExpressionAsync("var obj = {}; obj;"));339 Assert.NotNull(await Page.EvaluateExpressionAsync("[]"));340 Assert.NotNull(await Page.EvaluateExpressionAsync("''"));341 var objectPopulated = await Page.EvaluateExpressionAsync("var obj = {a:1}; obj;");342 Assert.NotNull(objectPopulated);343 Assert.Equal(1, objectPopulated["a"]);...
ExecutionContext.cs
Source:ExecutionContext.cs
...128 }).ConfigureAwait(false);129 }130 catch (Exception ex)131 {132 throw new EvaluationFailedException(ex.Message, ex);133 }134 }135 internal async Task<JSHandle> EvaluateFunctionHandleAsync(string script, params object[] args)136 {137 if (string.IsNullOrEmpty(script))138 {139 return null;140 }141 try142 {143 return await EvaluateHandleAsync("Runtime.callFunctionOn", new Dictionary<string, object>144 {145 ["functionDeclaration"] = $"{script}\n{EvaluationScriptSuffix}\n",146 [MessageKeys.ExecutionContextId] = _contextId,147 ["arguments"] = args.Select(FormatArgument),148 ["returnByValue"] = false,149 ["awaitPromise"] = true,150 ["userGesture"] = true151 }).ConfigureAwait(false);152 }153 catch (Exception ex)154 {155 throw new EvaluationFailedException(ex.Message, ex);156 }157 }158 internal JSHandle CreateJSHandle(dynamic remoteObject)159 => (remoteObject.subtype == "node" && Frame != null)160 ? new ElementHandle(this, _client, remoteObject, Frame.FrameManager.Page, Frame.FrameManager)161 : new JSHandle(this, _client, remoteObject);162 private async Task<T> EvaluateAsync<T>(Task<JSHandle> handleEvaluator)163 {164 var handle = await handleEvaluator.ConfigureAwait(false);165 var result = default(T);166 try167 {168 result = await handle.JsonValueAsync<T>()169 .ContinueWith(jsonTask => jsonTask.Exception != null ? default : jsonTask.Result).ConfigureAwait(false);170 }171 catch (Exception ex)172 {173 if (ex.Message.Contains("Object reference chain is too long") ||174 ex.Message.Contains("Object couldn't be returned by value"))175 {176 return default;177 }178 throw new EvaluationFailedException(ex.Message, ex);179 }180 await handle.DisposeAsync().ConfigureAwait(false);181 return result is JToken token && token.Type == JTokenType.Null ? default : result;182 }183 private async Task<JSHandle> EvaluateHandleAsync(string method, dynamic args)184 {185 var response = await _client.SendAsync(method, args).ConfigureAwait(false);186 var exceptionDetails = response[MessageKeys.ExceptionDetails];187 if (exceptionDetails != null)188 {189 throw new EvaluationFailedException("Evaluation failed: " +190 GetExceptionMessage(exceptionDetails.ToObject<EvaluateExceptionDetails>()));191 }192 return CreateJSHandle(response.result);193 }194 private object FormatArgument(object arg)195 {196 switch (arg)197 {198 case double d:199 if (double.IsPositiveInfinity(d))200 {201 return new { unserializableValue = "Infinity" };202 }203 if (double.IsNegativeInfinity(d))...
BrowserActor.cs
Source:BrowserActor.cs
...92 {93 if (exception is ProcessException)94 {95 }96 else if (exception is EvaluationFailedException)97 {98 }99 else if (exception is MessageException)100 {101 }102 else if (exception is NavigationException) // Couldn't Navigate to url. Or Browser was disconnected //Target.detachedFromTarget103 {104 return Directive.Restart;105 }106 else if (exception is SelectorException)107 {108 }109 else if (exception is TargetClosedException) // Page was closed110 {...
RuntimeTest.cs
Source:RuntimeTest.cs
...37 private async Task AssertThrowsConnect(Page page, string error, params object[] args)38 {39 var start =40 "Evaluation failed: TypeError: Error in invocation of runtime.connect(optional string extensionId, optional object connectInfo): ";41 var ex = await Assert.ThrowsAsync<EvaluationFailedException>(async () =>42 await page.EvaluateFunctionAsync("(...args) => chrome.runtime.connect.call(...args)", args));43 var currentError = start + error;44 Assert.StartsWith(currentError, ex.Message);45 }46 }47}...
ChromeAppTest.cs
Source:ChromeAppTest.cs
...32 var details = await page.EvaluateExpressionAsync<object>("chrome.app.getDetails()");33 Assert.Null(details);34 var runningStateFunc = await page.EvaluateExpressionAsync<string>("chrome.app.runningState()");35 Assert.Equal("cannot_run", runningStateFunc);36 await Assert.ThrowsAsync<EvaluationFailedException>(async () => await page.EvaluateExpressionAsync("chrome.app.getDetails('foo')"));37 }38 }39}...
EvaluationFailedException.cs
Source:EvaluationFailedException.cs
...5 /// <summary>6 /// Exception thrown by <see cref="ExecutionContext.EvaluateHandleAsync(string, dynamic)"/>.7 /// </summary>8 [Serializable]9 public class EvaluationFailedException : PuppeteerException10 {11 /// <summary>12 /// Initializes a new instance of the <see cref="EvaluationFailedException"/> class.13 /// </summary>14 public EvaluationFailedException()15 {16 }17 /// <summary>18 /// Initializes a new instance of the <see cref="EvaluationFailedException"/> class.19 /// </summary>20 /// <param name="message">Message.</param>21 public EvaluationFailedException(string message) : base(RewriteErrorMeesage(message))22 {23 }24 /// <summary>25 /// Initializes a new instance of the <see cref="EvaluationFailedException"/> class.26 /// </summary>27 /// <param name="message">Message.</param>28 /// <param name="innerException">Inner exception.</param>29 public EvaluationFailedException(string message, Exception innerException)30 : base(RewriteErrorMeesage(message), innerException)31 {32 }33 /// <summary>34 /// Initializes a new instance of the <see cref="EvaluationFailedException"/> class.35 /// </summary>36 /// <param name="info">Info.</param>37 /// <param name="context">Context.</param>38 protected EvaluationFailedException(SerializationInfo info, StreamingContext context) : base(info, context)39 {40 }41 }42}...
JSHandleMethodConverter.cs
Source:JSHandleMethodConverter.cs
...10 public override bool CanConvert(Type objectType) => false;11 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)12 => null;13 public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)14 => throw new EvaluationFailedException("Unable to make function call. Are you passing a nested JSHandle?");15 }16}...
EvaluationFailedException
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 var options = new LaunchOptions { Headless = true };9 using (var browser = await Puppeteer.LaunchAsync(options))10 using (var page = await browser.NewPageAsync())11 {12 await page.WaitForSelectorAsync("input[name=q]");13 await page.TypeAsync("input[name=q]", "PuppeteerSharp");14 await page.ClickAsync("input[value='Google Search']");15 {16 await page.WaitForSelectorAsync("a[href='
EvaluationFailedException
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))9 {10 var page = await browser.NewPageAsync();11 {12 await page.EvaluateFunctionAsync("() => { throw new Error('Evaluation failed'); }");13 }14 catch (EvaluationFailedException e)15 {16 Console.WriteLine(e.Message);17 }18 }19 }20 }21}22using System;23using System.Threading.Tasks;24using PuppeteerSharp;25{26 {27 static async Task Main(string[] args)28 {29 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))30 {31 var page = await browser.NewPageAsync();32 {33 await page.EvaluateFunctionAsync("() => { throw new Error('Evaluation failed'); }");34 }35 catch (EvaluationFailedException e)36 {37 Console.WriteLine(e.Message);38 }39 }40 }41 }42}43using System;44using System.Threading.Tasks;45using PuppeteerSharp;46{47 {48 static async Task Main(string[] args)49 {50 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))51 {52 var page = await browser.NewPageAsync();53 {54 await page.EvaluateFunctionAsync("() => { throw new Error('Evaluation failed'); }");55 }56 catch (EvaluationFailedException e)57 {58 Console.WriteLine(e.Message);59 }60 }61 }62 }63}64using System;
EvaluationFailedException
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 static void Main(string[] args)7 {8 MainAsync().Wait();9 }10 static async Task MainAsync()11 {12 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))13 using (var page = await browser.NewPageAsync())14 {15 {16 await page.EvaluateExpressionAsync("not.existing.object.property");17 }18 catch (EvaluationFailedException e)19 {20 Console.WriteLine(e.Message);21 }22 }23 }24 }25}26{ "message": "Evaluation failed: TypeError: Cannot read property 'property' of undefined27at ExecutionContext._evaluateInternal (/home/kali/Downloads/puppeteer-sharp-master/lib/PuppeteerSharp/ExecutionContext.cs:178:13)28at ExecutionContext.EvaluateFunctionHandleAsync (/home/kali/Downloads/puppeteer-sharp-master/lib/PuppeteerSharp/ExecutionContext.cs:101:12)29at ExecutionContext.EvaluateFunctionAsync (/home/kali/Downloads/puppeteer-sharp-master/lib/PuppeteerSharp/ExecutionContext.cs:45:12)30at Page.EvaluateExpressionAsync (/home/kali/Downloads/puppeteer-sharp-master/lib/PuppeteerSharp/Page.cs:1219:12)31at Program.MainAsync (/home/kali/Downloads/puppeteer-sharp-master/samples/2.cs:25:33)", "data": { "stack": "Evaluation failed: TypeError: Cannot read property 'property' of undefined32at ExecutionContext._evaluateInternal (/home/kali/Downloads/puppeteer-sharp-master/lib/PuppeteerSharp/ExecutionContext.cs:178:13)33at ExecutionContext.EvaluateFunctionHandleAsync (/home/kali/Downloads/puppeteer-sharp-master/lib/PuppeteerSharp/ExecutionContext.cs:101:12)34at ExecutionContext.EvaluateFunctionAsync (/home/kali/Downloads/puppeteer-sharp-master/lib/PuppeteerSharp/ExecutionContext.cs:45:12)35at Page.EvaluateExpressionAsync (/home/kali/Downloads/puppeteer-sharp-master/lib/PuppeteerSharp/Page.cs:1219:12)36at Program.MainAsync (/home/kali/Downloads/puppeteer-sharp-master/s
EvaluationFailedException
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 static void Main(string[] args)7 {8 MainAsync().GetAwaiter().GetResult();9 }10 static async Task MainAsync()11 {12 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });13 var page = await browser.NewPageAsync();14 {15 var result = await page.EvaluateExpressionAsync<int>("5 + 5");16 Console.WriteLine(result);17 }18 catch (EvaluationFailedException e)19 {20 Console.WriteLine(e.Message);21 }22 }23 }24}25var result = await page.EvaluateExpressionAsync<int>("5 + 5", "my custom error message");
EvaluationFailedException
Using AI Code Generation
1using System.Threading.Tasks;2using PuppeteerSharp;3{4 {5 static async Task Main(string[] args)6 {7 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);8 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions9 {10 }))11 using (var page = await browser.NewPageAsync())12 {13 {14 await page.EvaluateExpressionAsync("not.existing.object.property");15 }16 catch (EvaluationFailedException e)17 {18 Console.WriteLine(e.Message);19 }20 }21 }22 }23}24 at ExecutionContext._evaluateInternal (/home/rohit/.nuget/packages/puppeteersharp/1.13.1/lib/netstandard2.0/PuppeteerSharp/ExecutionContext.cs:153:19)25 at ExecutionContext.EvaluateFunctionHandleAsync (/home/rohit/.nuget/packages/puppeteersharp/1.13.1/lib/netstandard2.0/PuppeteerSharp/ExecutionContext.cs:64:12)26 at ExecutionContext.EvaluateExpressionHandleAsync (/home/rohit/.nuget/packages/puppeteersharp/1.13.1/lib/netstandard2.0/PuppeteerSharp/ExecutionContext.cs:33:12)27 at ExecutionContext.EvaluateExpressionAsync (/home/rohit/.nuget/packages/puppeteersharp/1.13.1/lib/netstandard2.0/PuppeteerSharp/ExecutionContext.cs:22:12)28 at Page.EvaluateExpressionAsync (/home/rohit/.nuget/packages/puppeteersharp/1.13.1/lib/netstandard2.0/PuppeteerSharp/Page.cs:1106:12)29 at Program.Main (2.cs:28:24)
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!!