How to use ShouldEvaluateInThePageContext method of PuppeteerSharp.Tests.PageTests.EvaluateTests class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Tests.PageTests.EvaluateTests.ShouldEvaluateInThePageContext

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

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

EvaluateTests.cs

Source: EvaluateTests.cs Github

copy
1using System.Collections.Generic;
2using System.Threading.Tasks;
3using Newtonsoft.Json;
4using Newtonsoft.Json.Linq;
5using Xunit;
6using Xunit.Abstractions;
7using PuppeteerSharp.Helpers.Json;
8using System.Numerics;
9
10namespace PuppeteerSharp.Tests.PageTests
11{
12    [Collection("PuppeteerLoaderFixture collection")]
13    public class EvaluateTests : PuppeteerPageBaseTest
14    {
15        public EvaluateTests(ITestOutputHelper output) : base(output)
16        {
17        }
18
19        [Theory]
20        [InlineData("() => 7 * 3", 21)] //ShouldWork
21        [InlineData("() => Promise.resolve(8 * 7)", 56)] //ShouldAwaitPromise
22        public async Task BasicIntFunctionEvaluationTest(string script, object expected)
23        {
24            var result = await Page.EvaluateFunctionAsync<int>(script);
25            Assert.Equal(expected, result);
26        }
27
28        [Fact]
29        public async Task ShouldTransferBigInt()
30        {
31            var result = await Page.EvaluateFunctionAsync<BigInteger>("a => a", new BigInteger(42));
32            Assert.Equal(new BigInteger(42), result);
33        }
34
35        [Theory]
36        [InlineData(double.NaN)] //ShouldTransferNaN
37        [InlineData(-0)] //ShouldTransferNegative0
38        [InlineData(double.PositiveInfinity)] //ShouldTransferInfinity
39        [InlineData(double.NegativeInfinity)] //ShouldTransferNegativeInfinty
40        public async Task BasicTransferTest(object transferObject)
41        {
42            var result = await Page.EvaluateFunctionAsync<object>("a => a", transferObject);
43            Assert.Equal(transferObject, result);
44        }
45
46        [Fact]
47        public async Task ShouldTransferArrays()
48        {
49            var result = await Page.EvaluateFunctionAsync<int[]>("a => a", new int[] { 1, 2, 3 });
50            Assert.Equal(new int[] { 1, 2, 3 }, result);
51        }
52
53        [Fact]
54        public async Task ShouldTransferArraysAsArraysNotObjects()
55        {
56            var result = await Page.EvaluateFunctionAsync<bool>("a => Array.isArray(a)", new int[] { 1, 2, 3 });
57            Assert.True(result);
58        }
59
60        [Fact]
61        public async Task ShouldModifyGlobalEnvironment()
62        {
63            await Page.EvaluateFunctionAsync("() => window.globalVar = 123");
64            Assert.Equal(123, await Page.EvaluateFunctionAsync<int>("() => window.globalVar"));
65        }
66
67        [Fact]
68        public async Task ShouldEvaluateInThePageContext()
69        {
70            await Page.GoToAsync(TestConstants.ServerUrl + "/global-var.html");
71            Assert.Equal(123, await Page.EvaluateFunctionAsync<int>("() => window.globalVar"));
72        }
73
74        [Fact]
75        public async Task ShouldReturnUndefinedForObjectsWithSymbols()
76            => Assert.Null(await Page.EvaluateFunctionAsync<object>("() => [Symbol('foo4')]"));
77
78        [Fact]
79        public async Task ShouldWorkWithUnicodeChars()
80            => Assert.Equal(42, await Page.EvaluateFunctionAsync<int>("a => a['中文字符']", new Dictionary<string, int> { ["中文字符"] = 42 }));
81
82        [Fact]
83        public async Task ShouldThrowWhenEvaluationTriggersReload()
84        {
85            var exception = await Assert.ThrowsAsync<EvaluationFailedException>(() =>
86            {
87                return Page.EvaluateFunctionAsync(@"() => {
88                    location.reload();
89                    return new Promise(() => {});
90                }");
91            });
92
93            Assert.Contains("Protocol error", exception.Message);
94        }
95
96        [Fact]
97        public async Task ShouldWorkRightAfterFrameNavigated()
98        {
99            Task<int> frameEvaluation = null;
100
101            Page.FrameNavigated += (sender, e) =>
102            {
103                frameEvaluation = e.Frame.EvaluateFunctionAsync<int>("() => 6 * 7");
104            };
105
106            await Page.GoToAsync(TestConstants.EmptyPage);
107            Assert.Equal(42, await frameEvaluation);
108        }
109
110        [Fact]
111        public async Task ShouldWorkFromInsideAnExposedFunction()
112        {
113            await Page.ExposeFunctionAsync("callController", async (int a, int b) =>
114            {
115                return await Page.EvaluateFunctionAsync<int>("(a, b) => a * b", a, b);
116            });
117            var result = await Page.EvaluateFunctionAsync<int>(@"async function() {
118                return await callController(9, 3);
119            }");
120            Assert.Equal(27, result);
121        }
122
123        [Fact]
124        public async Task ShouldRejectPromiseWithExeption()
125        {
126            var exception = await Assert.ThrowsAsync<EvaluationFailedException>(() =>
127            {
128                return Page.EvaluateFunctionAsync("() => not.existing.object.property");
129            });
130
131            Assert.Contains("not is not defined", exception.Message);
132        }
133
134        [Fact]
135        public async Task ShouldSupportThrownStringsAsErrorMessages()
136        {
137            var exception = await Assert.ThrowsAsync<EvaluationFailedException>(
138                () => Page.EvaluateExpressionAsync("throw 'qwerty'"));
139            Assert.Contains("qwerty", exception.Message);
140        }
141
142        [Fact]
143        public async Task ShouldSupportThrownNumbersAsErrorMessages()
144        {
145            var exception = await Assert.ThrowsAsync<EvaluationFailedException>(
146                            () => Page.EvaluateExpressionAsync("throw 100500"));
147            Assert.Contains("100500", exception.Message);
148        }
149
150        [Fact]
151        public async Task SouldReturnComplexObjects()
152        {
153            dynamic obj = new
154            {
155                foo = "bar!"
156            };
157            var result = await Page.EvaluateFunctionAsync("a => a", obj);
158            Assert.Equal("bar!", result.foo.ToString());
159        }
160
161        [Fact]
162        public async Task ShouldReturnBigInt()
163        {
164            var result = await Page.EvaluateFunctionAsync<object>("() => BigInt(42)");
165            Assert.Equal(new BigInteger(42), result);
166        }
167
168        [Theory]
169        [InlineData("() => NaN", double.NaN)] //ShouldReturnNaN
170        [InlineData("() => -0", -0)] //ShouldReturnNegative0
171        [InlineData("() => Infinity", double.PositiveInfinity)] //ShouldReturnInfinity
172        [InlineData("() => -Infinity", double.NegativeInfinity)] //ShouldReturnNegativeInfinty
173        public async Task BasicEvaluationTest(string script, object expected)
174        {
175            var result = await Page.EvaluateFunctionAsync<object>(script);
176            Assert.Equal(expected, result);
177        }
178
179        [Fact]
180        public async Task ShouldAcceptNullAsOneOfMultipleParameters()
181        {
182            var result = await Page.EvaluateFunctionAsync<bool>(
183                "(a, b) => Object.is(a, null) && Object.is(b, 'foo')",
184                null,
185                "foo");
186            Assert.True(result);
187        }
188
189        [Fact]
190        public async Task ShouldReturnNullForNonSerializableObjects()
191            => Assert.Null(await Page.EvaluateFunctionAsync("() => window"));
192
193        [Fact]
194        public async Task ShouldFailForCircularObject()
195        {
196            var result = await Page.EvaluateFunctionAsync(@"() => {
197                const a = {};
198                const b = {a};
199                a.b = b;
200                return a;
201            }");
202
203            Assert.Null(result);
204        }
205
206        [Fact]
207        public async Task ShouldBeAbleToThrowATrickyError()
208        {
209            var windowHandle = await Page.EvaluateFunctionHandleAsync("() => window");
210            PuppeteerException exception = await Assert.ThrowsAsync<MessageException>(() => windowHandle.JsonValueAsync());
211            var errorText = exception.Message;
212
213            exception = await Assert.ThrowsAsync<EvaluationFailedException>(() => Page.EvaluateFunctionAsync(@"errorText =>
214            {
215                throw new Error(errorText);
216            }", errorText));
217            Assert.Contains(errorText, exception.Message);
218        }
219
220        [Theory]
221        [InlineData("1 + 5;", 6)] //ShouldAcceptSemiColons
222        [InlineData("2 + 5\n// do some math!'", 7)] //ShouldAceptStringComments
223        public async Task BasicIntExressionEvaluationTest(string script, object expected)
224        {
225            var result = await Page.EvaluateExpressionAsync<int>(script);
226            Assert.Equal(expected, result);
227        }
228
229        [Fact]
230        public async Task ShouldAcceptElementHandleAsAnArgument()
231        {
232            await Page.SetContentAsync("<section>42</section>");
233            var element = await Page.QuerySelectorAsync("section");
234            var text = await Page.EvaluateFunctionAsync<string>("e => e.textContent", element);
235            Assert.Equal("42", text);
236        }
237
238        [Fact]
239        public async Task ShouldThrowIfUnderlyingElementWasDisposed()
240        {
241            await Page.SetContentAsync("<section>39</section>");
242            var element = await Page.QuerySelectorAsync("section");
243            Assert.NotNull(element);
244            await element.DisposeAsync();
245            var exception = await Assert.ThrowsAsync<EvaluationFailedException>(()
246                => Page.EvaluateFunctionAsync<string>("e => e.textContent", element));
247            Assert.Contains("JSHandle is disposed", exception.Message);
248        }
249
250        [Fact]
251        public async Task ShouldThrowIfElementHandlesAreFromOtherFrames()
252        {
253            await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);
254            var bodyHandle = await Page.FirstChildFrame().QuerySelectorAsync("body");
255            var exception = await Assert.ThrowsAsync<EvaluationFailedException>(()
256                => Page.EvaluateFunctionAsync<string>("body => body.innerHTML", bodyHandle));
257            Assert.Contains("JSHandles can be evaluated only in the context they were created", exception.Message);
258        }
259
260        [Fact]
261        public async Task ShouldSimulateAUserGesture()
262            => Assert.True(await Page.EvaluateFunctionAsync<bool>("() => document.execCommand('copy')"));
263
264        [Fact]
265        public async Task ShouldThrowANiceErrorAfterANavigation()
266        {
267            var executionContext = await Page.MainFrame.GetExecutionContextAsync();
268
269            await Task.WhenAll(
270                Page.WaitForNavigationAsync(),
271                executionContext.EvaluateFunctionAsync("() => window.location.reload()")
272            );
273            var ex = await Assert.ThrowsAsync<EvaluationFailedException>(() =>
274            {
275                return executionContext.EvaluateFunctionAsync("() => null");
276            });
277            Assert.Contains("navigation", ex.Message);
278        }
279
280        [Fact]
281        public async Task ShouldNotThrowAnErrorWhenEvaluationDoesANavigation()
282        {
283            await Page.GoToAsync(TestConstants.ServerUrl + "/one-style.html");
284            var result = await Page.EvaluateFunctionAsync<int[]>(@"() =>
285            {
286                window.location = '/empty.html';
287                return [42];
288            }");
289            Assert.Equal(new[] { 42 }, result);
290        }
291
292        /// <summary>
293        /// Original Name "should transfer 100Mb of data from page to node.js"
294        /// </summary>
295        [Fact]
296        public async Task ShouldTransfer100MbOfDataFromPage()
297        {
298            var a = await Page.EvaluateFunctionAsync<string>("() => Array(100 * 1024 * 1024 + 1).join('a')");
299            Assert.Equal(100 * 1024 * 1024, a.Length);
300        }
301
302        [Fact]
303        public async Task ShouldWorkWithDifferentSerializerSettings()
304        {
305            var result = await Page.EvaluateFunctionAsync<ComplexObjectTestClass>("() => { return { foo: 'bar' }}");
306            Assert.Equal("bar", result.Foo);
307
308            result = (await Page.EvaluateFunctionAsync<JToken>("() => { return { Foo: 'bar' }}"))
309                .ToObject<ComplexObjectTestClass>(new JsonSerializerSettings());
310            Assert.Equal("bar", result.Foo);
311
312            result = await Page.EvaluateExpressionAsync<ComplexObjectTestClass>("var obj = { foo: 'bar' }; obj;");
313            Assert.Equal("bar", result.Foo);
314
315            result = (await Page.EvaluateExpressionAsync<JToken>("var obj = { Foo: 'bar' }; obj;"))
316                .ToObject<ComplexObjectTestClass>(new JsonSerializerSettings());
317            Assert.Equal("bar", result.Foo);
318        }
319
320        [Fact]
321        public async Task ShouldProperlyIgnoreUndefinedFields()
322        {
323            var result = await Page.EvaluateFunctionAsync<Dictionary<string, object>>("() => ({a: undefined})");
324            Assert.Empty(result);
325        }
326
327        [Fact]
328        public async Task ShouldProperlySerializeNullFields()
329        {
330            var result = await Page.EvaluateFunctionAsync<Dictionary<string, object>>("() => ({a: null})");
331            Assert.True(result.ContainsKey("a"));
332            Assert.Null(result["a"]);
333        }
334
335        [Fact]
336        public async Task ShouldAcceptObjectHandleAsAnArgument()
337        {
338            var navigatorHandle = await Page.EvaluateExpressionHandleAsync("navigator");
339            var text = await Page.EvaluateFunctionAsync<string>("e => e.userAgent", navigatorHandle);
340            Assert.Contains("Mozilla", text);
341        }
342
343        [Fact]
344        public async Task ShouldAcceptObjectHandleToPrimitiveTypes()
345        {
346            var aHandle = await Page.EvaluateExpressionHandleAsync("5");
347            var isFive = await Page.EvaluateFunctionAsync<bool>("e => Object.is(e, 5)", aHandle);
348            Assert.True(isFive);
349        }
350
351        [Fact]
352        public async Task ShouldWarnOnNestedObjectHandles()
353        {
354            var handle = await Page.EvaluateFunctionHandleAsync("() => document.body");
355            var elementHandle = handle as ElementHandle;
356
357            var exception = await Assert.ThrowsAsync<EvaluationFailedException>(()
358                => Page.EvaluateFunctionHandleAsync(
359                    "opts => opts.elem.querySelector('p')",
360                    new { elem = handle }));
361
362            Assert.Contains("Are you passing a nested JSHandle?", exception.Message);
363
364            //Check with ElementHandle
365            exception = await Assert.ThrowsAsync<EvaluationFailedException>(()
366                => Page.EvaluateFunctionHandleAsync(
367                    "opts => opts.elem.querySelector('p')",
368                    new { elem = elementHandle }));
369
370            Assert.Contains("Are you passing a nested JSHandle?", exception.Message);
371        }
372
373        [Fact]
374        public async Task ShouldWorkWithoutGenerics()
375        {
376            Assert.NotNull(await Page.EvaluateExpressionAsync("var obj = {}; obj;"));
377            Assert.NotNull(await Page.EvaluateExpressionAsync("[]"));
378            Assert.NotNull(await Page.EvaluateExpressionAsync("''"));
379
380            var objectPopulated = await Page.EvaluateExpressionAsync("var obj = {a:1}; obj;");
381            Assert.NotNull(objectPopulated);
382            Assert.Equal(1, objectPopulated["a"]);
383
384            var arrayPopulated = await Page.EvaluateExpressionAsync("[1]");
385            Assert.IsType<JArray>(arrayPopulated);
386            Assert.Equal(1, ((JArray)arrayPopulated)[0]);
387
388            Assert.Equal("1", await Page.EvaluateExpressionAsync("'1'"));
389            Assert.Equal(1, await Page.EvaluateExpressionAsync("1"));
390            Assert.Equal(11111111, await Page.EvaluateExpressionAsync("11111111"));
391            Assert.Equal(11111111111111, await Page.EvaluateExpressionAsync("11111111111111"));
392            Assert.Equal(1.1, await Page.EvaluateExpressionAsync("1.1"));
393        }
394
395        public class ComplexObjectTestClass
396        {
397            public string Foo { get; set; }
398        }
399    }
400}
401
Full Screen

PageEvaluateTests.cs

Source: PageEvaluateTests.cs Github

copy
1using System.Collections.Generic;
2using System.Threading.Tasks;
3using Newtonsoft.Json;
4using Newtonsoft.Json.Linq;
5using Xunit;
6using Xunit.Abstractions;
7using PuppeteerSharp.Helpers.Json;
8using System.Numerics;
9using PuppeteerSharp.Tests.Attributes;
10using PuppeteerSharp.Xunit;
11
12namespace PuppeteerSharp.Tests.PageTests
13{
14    [Collection(TestConstants.TestFixtureCollectionName)]
15    public class EvaluateTests : PuppeteerPageBaseTest
16    {
17        public EvaluateTests(ITestOutputHelper output) : base(output)
18        {
19        }
20
21        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should work")]
22        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should await promise")]
23        [Theory]
24        [InlineData("() => 7 * 3", 21)] //ShouldWork
25        [InlineData("() => Promise.resolve(8 * 7)", 56)] //ShouldAwaitPromise
26        public async Task BasicIntFunctionEvaluationTest(string script, object expected)
27        {
28            var result = await Page.EvaluateFunctionAsync<int>(script);
29            Assert.Equal(expected, result);
30        }
31
32        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should transfer BigInt")]
33        [PuppeteerFact]
34        public async Task ShouldTransferBigInt()
35        {
36            var result = await Page.EvaluateFunctionAsync<BigInteger>("a => a", new BigInteger(42));
37            Assert.Equal(new BigInteger(42), result);
38        }
39
40        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should transfer NaN")]
41        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should transfer -0")]
42        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should transfer Infinity")]
43        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should transfer -Infinity")]
44        [Theory]
45        [InlineData(double.NaN)] //ShouldTransferNaN
46        [InlineData(-0)] //ShouldTransferNegative0
47        [InlineData(double.PositiveInfinity)] //ShouldTransferInfinity
48        [InlineData(double.NegativeInfinity)] //ShouldTransferNegativeInfinty
49        public async Task BasicTransferTest(object transferObject)
50        {
51            var result = await Page.EvaluateFunctionAsync<object>("a => a", transferObject);
52            Assert.Equal(transferObject, result);
53        }
54
55        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should transfer arrays")]
56        [PuppeteerFact]
57        public async Task ShouldTransferArrays()
58        {
59            var result = await Page.EvaluateFunctionAsync<int[]>("a => a", new int[] { 1, 2, 3 });
60            Assert.Equal(new int[] { 1, 2, 3 }, result);
61        }
62
63        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should transfer arrays as arrays, not objects")]
64        [PuppeteerFact]
65        public async Task ShouldTransferArraysAsArraysNotObjects()
66        {
67            var result = await Page.EvaluateFunctionAsync<bool>("a => Array.isArray(a)", new int[] { 1, 2, 3 });
68            Assert.True(result);
69        }
70
71        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should modify global environment")]
72        [PuppeteerFact]
73        public async Task ShouldModifyGlobalEnvironment()
74        {
75            await Page.EvaluateFunctionAsync("() => window.globalVar = 123");
76            Assert.Equal(123, await Page.EvaluateFunctionAsync<int>("() => window.globalVar"));
77        }
78
79        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should evaluate in the page context")]
80        [PuppeteerFact]
81        public async Task ShouldEvaluateInThePageContext()
82        {
83            await Page.GoToAsync(TestConstants.ServerUrl + "/global-var.html");
84            Assert.Equal(123, await Page.EvaluateFunctionAsync<int>("() => window.globalVar"));
85        }
86
87        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should return undefined for objects with symbols")]
88        [SkipBrowserFact(skipFirefox: true)]
89        public async Task ShouldReturnUndefinedForObjectsWithSymbols()
90            => Assert.Null(await Page.EvaluateFunctionAsync<object>("() => [Symbol('foo4')]"));
91
92        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should work with unicode chars")]
93        [PuppeteerFact]
94        public async Task ShouldWorkWithUnicodeChars()
95            => Assert.Equal(42, await Page.EvaluateFunctionAsync<int>("a => a['中文字符']", new Dictionary<string, int> { ["中文字符"] = 42 }));
96
97        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should throw when evaluation triggers reload")]
98        [SkipBrowserFact(skipFirefox: true)]
99        public async Task ShouldThrowWhenEvaluationTriggersReload()
100        {
101            var exception = await Assert.ThrowsAsync<EvaluationFailedException>(() =>
102            {
103                return Page.EvaluateFunctionAsync(@"() => {
104                    location.reload();
105                    return new Promise(() => {});
106                }");
107            });
108
109            Assert.Contains("Protocol error", exception.Message);
110        }
111
112        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should work right after framenavigated")]
113        [PuppeteerFact]
114        public async Task ShouldWorkRightAfterFrameNavigated()
115        {
116            Task<int> frameEvaluation = null;
117
118            Page.FrameNavigated += (_, e) =>
119            {
120                frameEvaluation = e.Frame.EvaluateFunctionAsync<int>("() => 6 * 7");
121            };
122
123            await Page.GoToAsync(TestConstants.EmptyPage);
124            Assert.Equal(42, await frameEvaluation);
125        }
126
127        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should work from-inside an exposed function")]
128        [SkipBrowserFact(skipFirefox: true)]
129        public async Task ShouldWorkFromInsideAnExposedFunction()
130        {
131            await Page.ExposeFunctionAsync("callController", async (int a, int b) =>
132            {
133                return await Page.EvaluateFunctionAsync<int>("(a, b) => a * b", a, b);
134            });
135            var result = await Page.EvaluateFunctionAsync<int>(@"async function() {
136                return await callController(9, 3);
137            }");
138            Assert.Equal(27, result);
139        }
140
141        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should reject promise with exception")]
142        [PuppeteerFact]
143        public async Task ShouldRejectPromiseWithExeption()
144        {
145            var exception = await Assert.ThrowsAsync<EvaluationFailedException>(() =>
146            {
147                return Page.EvaluateFunctionAsync("() => not_existing_object.property");
148            });
149
150            Assert.Contains("not_existing_object", exception.Message);
151        }
152
153        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should support thrown strings as error messages")]
154        [PuppeteerFact]
155        public async Task ShouldSupportThrownStringsAsErrorMessages()
156        {
157            var exception = await Assert.ThrowsAsync<EvaluationFailedException>(
158                () => Page.EvaluateExpressionAsync("throw 'qwerty'"));
159            Assert.Contains("qwerty", exception.Message);
160        }
161
162        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should support thrown numbers as error messages")]
163        [PuppeteerFact]
164        public async Task ShouldSupportThrownNumbersAsErrorMessages()
165        {
166            var exception = await Assert.ThrowsAsync<EvaluationFailedException>(
167                            () => Page.EvaluateExpressionAsync("throw 100500"));
168            Assert.Contains("100500", exception.Message);
169        }
170
171        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should return complex objects")]
172        [PuppeteerFact]
173        public async Task SouldReturnComplexObjects()
174        {
175            dynamic obj = new
176            {
177                foo = "bar!"
178            };
179            var result = await Page.EvaluateFunctionAsync("a => a", obj);
180            Assert.Equal("bar!", result.foo.ToString());
181        }
182
183        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should return BigInt")]
184        [PuppeteerFact]
185        public async Task ShouldReturnBigInt()
186        {
187            var result = await Page.EvaluateFunctionAsync<object>("() => BigInt(42)");
188            Assert.Equal(new BigInteger(42), result);
189        }
190
191        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should return NaN")]
192        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should return -0")]
193        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should return Infinity")]
194        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should return -Infinity")]
195        [Theory]
196        [InlineData("() => NaN", double.NaN)] //ShouldReturnNaN
197        [InlineData("() => -0", -0)] //ShouldReturnNegative0
198        [InlineData("() => Infinity", double.PositiveInfinity)] //ShouldReturnInfinity
199        [InlineData("() => -Infinity", double.NegativeInfinity)] //ShouldReturnNegativeInfinty
200        public async Task BasicEvaluationTest(string script, object expected)
201        {
202            var result = await Page.EvaluateFunctionAsync<object>(script);
203            Assert.Equal(expected, result);
204        }
205
206        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should accept \"undefined\" as one of multiple parameters")]
207        [PuppeteerFact]
208        public async Task ShouldAcceptNullAsOneOfMultipleParameters()
209        {
210            var result = await Page.EvaluateFunctionAsync<bool>(
211                "(a, b) => Object.is(a, null) && Object.is(b, 'foo')",
212                null,
213                "foo");
214            Assert.True(result);
215        }
216
217        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should return undefined for non-serializable objects")]
218        [SkipBrowserFact(skipFirefox: true)]
219        public async Task ShouldReturnNullForNonSerializableObjects()
220            => Assert.Null(await Page.EvaluateFunctionAsync("() => window"));
221
222        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should fail for circular object")]
223        [SkipBrowserFact(skipFirefox: true)]
224        public async Task ShouldFailForCircularObject()
225        {
226            var result = await Page.EvaluateFunctionAsync(@"() => {
227                const a = {};
228                const b = {a};
229                a.b = b;
230                return a;
231            }");
232
233            Assert.Null(result);
234        }
235
236        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should be able to throw a tricky error")]
237        [SkipBrowserFact(skipFirefox: true)]
238        public async Task ShouldBeAbleToThrowATrickyError()
239        {
240            var windowHandle = await Page.EvaluateFunctionHandleAsync("() => window");
241            PuppeteerException exception = await Assert.ThrowsAsync<MessageException>(() => windowHandle.JsonValueAsync());
242            var errorText = exception.Message;
243
244            exception = await Assert.ThrowsAsync<EvaluationFailedException>(() => Page.EvaluateFunctionAsync(@"errorText =>
245            {
246                throw new Error(errorText);
247            }", errorText));
248            Assert.Contains(errorText, exception.Message);
249        }
250
251        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should accept a string")]
252        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should accept a string with semi colons")]
253        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should accept a string with comments")]
254        [Theory]
255        [InlineData("1 + 2;", 3)]
256        [InlineData("1 + 5;", 6)]
257        [InlineData("2 + 5\n// do some math!'", 7)]
258        public async Task BasicIntExressionEvaluationTest(string script, object expected)
259        {
260            var result = await Page.EvaluateExpressionAsync<int>(script);
261            Assert.Equal(expected, result);
262        }
263
264        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should accept element handle as an argument")]
265        [PuppeteerFact]
266        public async Task ShouldAcceptElementHandleAsAnArgument()
267        {
268            await Page.SetContentAsync("<section>42</section>");
269            var element = await Page.QuerySelectorAsync("section");
270            var text = await Page.EvaluateFunctionAsync<string>("e => e.textContent", element);
271            Assert.Equal("42", text);
272        }
273
274        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should throw if underlying element was disposed")]
275        [PuppeteerFact]
276        public async Task ShouldThrowIfUnderlyingElementWasDisposed()
277        {
278            await Page.SetContentAsync("<section>39</section>");
279            var element = await Page.QuerySelectorAsync("section");
280            Assert.NotNull(element);
281            await element.DisposeAsync();
282            var exception = await Assert.ThrowsAsync<EvaluationFailedException>(()
283                => Page.EvaluateFunctionAsync<string>("e => e.textContent", element));
284            Assert.Contains("JSHandle is disposed", exception.Message);
285        }
286
287        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should throw if elementHandles are from other frames")]
288        [SkipBrowserFact(skipFirefox: true)]
289        public async Task ShouldThrowIfElementHandlesAreFromOtherFrames()
290        {
291            await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);
292            var bodyHandle = await Page.FirstChildFrame().QuerySelectorAsync("body");
293            var exception = await Assert.ThrowsAsync<EvaluationFailedException>(()
294                => Page.EvaluateFunctionAsync<string>("body => body.innerHTML", bodyHandle));
295            Assert.Contains("JSHandles can be evaluated only in the context they were created", exception.Message);
296        }
297
298        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should simulate a user gesture")]
299        [SkipBrowserFact(skipFirefox: true)]
300        public async Task ShouldSimulateAUserGesture()
301            => Assert.True(await Page.EvaluateFunctionAsync<bool>(@"() => {
302                document.body.appendChild(document.createTextNode('test'));
303                document.execCommand('selectAll');
304                return document.execCommand('copy');
305            }"));
306
307        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should throw a nice error after a navigation")]
308        [SkipBrowserFact(skipFirefox: true)]
309        public async Task ShouldThrowANiceErrorAfterANavigation()
310        {
311            var executionContext = await Page.MainFrame.GetExecutionContextAsync();
312
313            await Task.WhenAll(
314                Page.WaitForNavigationAsync(),
315                executionContext.EvaluateFunctionAsync("() => window.location.reload()")
316            );
317            var ex = await Assert.ThrowsAsync<EvaluationFailedException>(() =>
318            {
319                return executionContext.EvaluateFunctionAsync("() => null");
320            });
321            Assert.Contains("navigation", ex.Message);
322        }
323
324        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should not throw an error when evaluation does a navigation")]
325        [SkipBrowserFact(skipFirefox: true)]
326        public async Task ShouldNotThrowAnErrorWhenEvaluationDoesANavigation()
327        {
328            await Page.GoToAsync(TestConstants.ServerUrl + "/one-style.html");
329            var result = await Page.EvaluateFunctionAsync<int[]>(@"() =>
330            {
331                window.location = '/empty.html';
332                return [42];
333            }");
334            Assert.Equal(new[] { 42 }, result);
335        }
336
337        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should transfer 100Mb of data from page to node.js")]
338        [PuppeteerFact]
339        public async Task ShouldTransfer100MbOfDataFromPage()
340        {
341            var a = await Page.EvaluateFunctionAsync<string>("() => Array(100 * 1024 * 1024 + 1).join('a')");
342            Assert.Equal(100 * 1024 * 1024, a.Length);
343        }
344
345        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should throw error with detailed information on exception inside promise ")]
346        [PuppeteerFact]
347        public async Task ShouldThrowErrorWithDetailedInformationOnExceptionInsidePromise()
348        {
349            var exception = await Assert.ThrowsAsync<EvaluationFailedException>(() =>
350                Page.EvaluateFunctionAsync(
351                    @"() => new Promise(() => {
352                        throw new Error('Error in promise');
353                    })"));
354            Assert.Contains("Error in promise", exception.Message);
355        }
356
357        [PuppeteerFact]
358        public async Task ShouldWorkWithDifferentSerializerSettings()
359        {
360            var result = await Page.EvaluateFunctionAsync<ComplexObjectTestClass>("() => { return { foo: 'bar' }}");
361            Assert.Equal("bar", result.Foo);
362
363            result = (await Page.EvaluateFunctionAsync<JToken>("() => { return { Foo: 'bar' }}"))
364                .ToObject<ComplexObjectTestClass>(new JsonSerializerSettings());
365            Assert.Equal("bar", result.Foo);
366
367            result = await Page.EvaluateExpressionAsync<ComplexObjectTestClass>("var obj = { foo: 'bar' }; obj;");
368            Assert.Equal("bar", result.Foo);
369
370            result = (await Page.EvaluateExpressionAsync<JToken>("var obj = { Foo: 'bar' }; obj;"))
371                .ToObject<ComplexObjectTestClass>(new JsonSerializerSettings());
372            Assert.Equal("bar", result.Foo);
373        }
374
375        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should properly serialize null fields")]
376        [PuppeteerFact]
377        public async Task ShouldProperlySerializeNullFields()
378        {
379            var result = await Page.EvaluateFunctionAsync<Dictionary<string, object>>("() => ({a: null})");
380            Assert.True(result.ContainsKey("a"));
381            Assert.Null(result["a"]);
382        }
383
384        [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should accept element handle as an argument")]
385        [PuppeteerFact]
386        public async Task ShouldAcceptObjectHandleAsAnArgument()
387        {
388            await Page.SetContentAsync("<section>42</section>");
389            var element = await Page.QuerySelectorAsync("section");
390            var text = await Page.EvaluateFunctionAsync<string>("(e) => e.textContent", element);
391            Assert.Equal("42", text);
392        }
393
394        [PuppeteerFact]
395        public async Task ShouldWorkWithoutGenerics()
396        {
397            Assert.NotNull(await Page.EvaluateExpressionAsync("var obj = {}; obj;"));
398            Assert.NotNull(await Page.EvaluateExpressionAsync("[]"));
399            Assert.NotNull(await Page.EvaluateExpressionAsync("''"));
400
401            var objectPopulated = await Page.EvaluateExpressionAsync("var obj = {a:1}; obj;");
402            Assert.NotNull(objectPopulated);
403            Assert.Equal(1, objectPopulated["a"]);
404
405            var arrayPopulated = await Page.EvaluateExpressionAsync("[1]");
406            Assert.IsType<JArray>(arrayPopulated);
407            Assert.Equal(1, ((JArray)arrayPopulated)[0]);
408
409            Assert.Equal("1", await Page.EvaluateExpressionAsync("'1'"));
410            Assert.Equal(1, await Page.EvaluateExpressionAsync("1"));
411            Assert.Equal(11111111, await Page.EvaluateExpressionAsync("11111111"));
412            Assert.Equal(11111111111111, await Page.EvaluateExpressionAsync("11111111111111"));
413            Assert.Equal(1.1, await Page.EvaluateExpressionAsync("1.1"));
414        }
415
416        public class ComplexObjectTestClass
417        {
418            public string Foo { get; set; }
419        }
420    }
421}
422
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 ShouldEvaluateInThePageContext code on LambdaTest Cloud Grid

Execute automation tests with ShouldEvaluateInThePageContext 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)