How to use ShouldWorkFromInsideAnExposedFunction method of Microsoft.Playwright.Tests.PageEvaluateTests class

Best Playwright-dotnet code snippet using Microsoft.Playwright.Tests.PageEvaluateTests.ShouldWorkFromInsideAnExposedFunction

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

PageEvaluateTests.cs

Source: PageEvaluateTests.cs Github

copy
1/*
2 * MIT License
3 *
4 * Copyright (c) Microsoft Corporation.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25using System;
26using System.Collections.Generic;
27using System.ComponentModel;
28using System.Dynamic;
29using System.Text.Json;
30using System.Text.RegularExpressions;
31using System.Threading.Tasks;
32using Microsoft.Playwright.Helpers;
33using Microsoft.Playwright.NUnit;
34using NUnit.Framework;
35
36namespace Microsoft.Playwright.Tests
37{
38    public class PageEvaluateTests : PageTestEx
39    {
40        [PlaywrightTest("page-evaluate.spec.ts", "should work")]
41        public async Task ShouldWork()
42        {
43            int result = await Page.EvaluateAsync<int>("() => 7 * 3");
44            Assert.AreEqual(21, result);
45        }
46
47        public async Task ShouldSerializeArguments()
48        {
49            int result = await Page.EvaluateAsync<int>("a => a.m * a.n", new { m = 7, n = 3 });
50            Assert.AreEqual(21, result);
51        }
52
53        [PlaywrightTest("page-evaluate.spec.ts", "should transfer NaN")]
54        public async Task ShouldTransferNaN()
55        {
56            double result = await Page.EvaluateAsync<double>("a => a", double.NaN);
57            Assert.AreEqual(double.NaN, result);
58        }
59
60        [PlaywrightTest("page-evaluate.spec.ts", "should transfer -0")]
61        public async Task ShouldTransferNegative0()
62        {
63            double result = await Page.EvaluateAsync<double>("a => a", -0d);
64            Assert.AreEqual(-0, result);
65        }
66
67        [PlaywrightTest("page-evaluate.spec.ts", "should transfer Infinity")]
68        public async Task ShouldTransferInfinity()
69        {
70            double result = await Page.EvaluateAsync<double>("a => a", double.PositiveInfinity);
71            Assert.AreEqual(double.PositiveInfinity, result);
72        }
73
74        [PlaywrightTest("page-evaluate.spec.ts", "should transfer -Infinity")]
75        public async Task ShouldTransferNegativeInfinity()
76        {
77            double result = await Page.EvaluateAsync<double>("a => a", double.NegativeInfinity);
78            Assert.AreEqual(double.NegativeInfinity, result);
79        }
80
81        [PlaywrightTest("page-evaluate.spec.ts", "should roundtrip unserializable values")]
82        public async Task ShouldRoundtripUnserializableValues()
83        {
84            dynamic value = new
85            {
86                infinity = double.PositiveInfinity,
87                nInfinity = double.NegativeInfinity,
88                nZero = -0d,
89                nan = double.NaN,
90            };
91
92            dynamic result = await Page.EvaluateAsync<dynamic>("value => value", value);
93            Assert.AreEqual(value.infinity, result.infinity);
94            Assert.AreEqual(value.nInfinity, result.nInfinity);
95            Assert.AreEqual(value.nZero, result.nZero);
96            Assert.AreEqual(value.nan, result.nan);
97        }
98
99        [PlaywrightTest("page-evaluate.spec.ts", "should roundtrip promise to value")]
100        public async Task ShouldRoundtripPromiseToValue()
101        {
102            object result = await Page.EvaluateAsync<object>("value => Promise.resolve(value)", null);
103            Assert.Null(result);
104
105            double infitinity = await Page.EvaluateAsync<double>("value => Promise.resolve(value)", double.PositiveInfinity);
106            Assert.AreEqual(double.PositiveInfinity, infitinity);
107
108            double ninfitinity = await Page.EvaluateAsync<double>("value => Promise.resolve(value)", double.NegativeInfinity);
109            Assert.AreEqual(double.NegativeInfinity, ninfitinity);
110
111            double nzero = await Page.EvaluateAsync<double>("value => Promise.resolve(value)", -0d);
112            Assert.AreEqual(-0, nzero);
113        }
114
115        [PlaywrightTest("page-evaluate.spec.ts", "should roundtrip promise to unserializable values")]
116        public async Task ShouldRoundtripPromiseToUnserializableValues()
117        {
118            dynamic value = new
119            {
120                infinity = double.PositiveInfinity,
121                nInfinity = double.NegativeInfinity,
122                nZero = -0d,
123                nan = double.NaN,
124            };
125
126            dynamic result = await Page.EvaluateAsync<ExpandoObject>("value => Promise.resolve(value)", value);
127            Assert.AreEqual(value.infinity, result.infinity);
128            Assert.AreEqual(value.nInfinity, result.nInfinity);
129            Assert.AreEqual(value.nZero, result.nZero);
130            Assert.AreEqual(value.nan, result.nan);
131        }
132
133        [PlaywrightTest("page-evaluate.spec.ts", "should transfer arrays")]
134        public async Task ShouldTransferArrays()
135        {
136            int[] result = await Page.EvaluateAsync<int[]>("a => a", new[] { 1, 2, 3 });
137            Assert.AreEqual(new[] { 1, 2, 3 }, result);
138        }
139
140        [PlaywrightTest("page-evaluate.spec.ts", "should transfer arrays as arrays, not objects")]
141        public async Task ShouldTransferArraysAsArraysNotObjects()
142        {
143            bool result = await Page.EvaluateAsync<bool>("a => Array.isArray(a)", new[] { 1, 2, 3 });
144            Assert.True(result);
145        }
146
147        [PlaywrightTest("page-evaluate.spec.ts", "should transfer maps as empty objects")]
148        public async Task ShouldTransferMapsAsEmptyObjects()
149        {
150            dynamic result = await Page.EvaluateAsync<ExpandoObject>("a => a.x.constructor.name + ' ' + JSON.stringify(a.x), {x: new Map([[1, 2]])}");
151            Assert.IsEmpty(TypeDescriptor.GetProperties(result));
152        }
153
154        [PlaywrightTest("page-evaluate.spec.ts", "should modify global environment")]
155        public async Task ShouldModifyGlobalEnvironment()
156        {
157            await Page.EvaluateAsync("() => window.globalVar = 123");
158            Assert.AreEqual(123, await Page.EvaluateAsync<int>("globalVar"));
159        }
160
161        [PlaywrightTest("page-evaluate.spec.ts", "should evaluate in the page context")]
162        public async Task ShouldEvaluateInThePageContext()
163        {
164            await Page.GotoAsync(Server.Prefix + "/global-var.html");
165            Assert.AreEqual(123, await Page.EvaluateAsync<int>("globalVar"));
166        }
167
168        [PlaywrightTest("page-evaluate.spec.ts", "should return undefined for objects with symbols")]
169        public async Task ShouldReturnUndefinedForObjectsWithSymbols()
170        {
171            Assert.AreEqual(new object[] { null }, await Page.EvaluateAsync<object>("() => [Symbol('foo4')]"));
172            Assert.AreEqual("{}", (await Page.EvaluateAsync<JsonElement>(@"() => {
173                var a = { };
174                a[Symbol('foo4')] = 42;
175                return a;
176            }")).GetRawText());
177            dynamic element = await Page.EvaluateAsync<ExpandoObject>(@"() => {
178                return { foo: [{ a: Symbol('foo4') }] };
179            }");
180
181            Assert.Null(element.foo[0].a);
182        }
183
184        [PlaywrightTest("page-evaluate.spec.ts", "should work with unicode chars")]
185        public async Task ShouldWorkWithUnicodeChars()
186        {
187            int result = await Page.EvaluateAsync<int>("a => a['中文字符']", new Dictionary<string, int> { ["中文字符"] = 42 });
188            Assert.AreEqual(42, result);
189        }
190
191        [PlaywrightTest("page-evaluate.spec.ts", "should throw when evaluation triggers reload")]
192        public async Task ShouldThrowWhenEvaluationTriggersReload()
193        {
194            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.EvaluateAsync<object>(@"() => {
195                location.reload();
196                return new Promise(() => { });
197            }"));
198            StringAssert.Contains("navigation", exception.Message);
199        }
200
201        [PlaywrightTest("page-evaluate.spec.ts", "should await promise")]
202        public async Task ShouldAwaitPromise()
203        {
204            int result = await Page.EvaluateAsync<int>("() => Promise.resolve(8 * 7)");
205            Assert.AreEqual(56, result);
206        }
207
208        [PlaywrightTest("page-evaluate.spec.ts", "should work right after framenavigated")]
209        public async Task ShouldWorkRightAfterFrameNavigated()
210        {
211            Task<int> frameEvaluation = null;
212            Page.FrameNavigated += (_, e) =>
213            {
214                frameEvaluation = e.EvaluateAsync<int>("() => 6 * 7");
215            };
216            await Page.GotoAsync(Server.EmptyPage);
217            Assert.AreEqual(42, await frameEvaluation);
218        }
219
220        [PlaywrightTest("page-evaluate.spec.ts", "should work right after a cross-origin navigation")]
221        public async Task ShouldWorkRightAfterACrossOriginNavigation()
222        {
223            await Page.GotoAsync(Server.EmptyPage);
224            Task<int> frameEvaluation = null;
225            Page.FrameNavigated += (_, e) =>
226            {
227                frameEvaluation = e.EvaluateAsync<int>("() => 6 * 7");
228            };
229            await Page.GotoAsync(Server.CrossProcessPrefix + "/empty.html");
230            Assert.AreEqual(42, await frameEvaluation);
231        }
232
233        [PlaywrightTest("page-evaluate.spec.ts", "should work from-inside an exposed function")]
234        public async Task ShouldWorkFromInsideAnExposedFunction()
235        {
236            // Setup inpage callback, which calls Page.evaluate
237            await Page.ExposeFunctionAsync("callController", async (int a, int b) => await Page.EvaluateAsync<int>("({a, b}) => a * b", new { a, b }));
238            int result = await Page.EvaluateAsync<int>(@"async function() {
239                return await callController(9, 3);
240            }");
241            Assert.AreEqual(27, result);
242        }
243
244        [PlaywrightTest("page-evaluate.spec.ts", "should reject promise with exception")]
245        public async Task ShouldRejectPromiseWithException()
246        {
247            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.EvaluateAsync("() => not_existing_object.property"));
248            StringAssert.Contains("not_existing_object", exception.Message);
249        }
250
251        [PlaywrightTest("page-evaluate.spec.ts", "should support thrown strings as error messages")]
252        public async Task ShouldSupportThrownStringsAsErrorMessages()
253        {
254            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.EvaluateAsync("() => { throw 'qwerty'; }"));
255            StringAssert.Contains("qwerty", exception.Message);
256        }
257
258        [PlaywrightTest("page-evaluate.spec.ts", "should support thrown numbers as error messages")]
259        public async Task ShouldSupportThrownNumbersAsErrorMessages()
260        {
261            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.EvaluateAsync("() => { throw 100500; }"));
262            StringAssert.Contains("100500", exception.Message);
263        }
264
265        [PlaywrightTest("page-evaluate.spec.ts", "should return complex objects")]
266        public async Task ShouldReturnComplexObjects()
267        {
268            var obj = new { foo = "bar!" };
269            var result = await Page.EvaluateAsync<JsonElement>("a => a", obj);
270            Assert.AreEqual("bar!", result.GetProperty("foo").GetString());
271        }
272
273        [PlaywrightTest("page-evaluate.spec.ts", "should return NaN")]
274        public async Task ShouldReturnNaN()
275        {
276            double result = await Page.EvaluateAsync<double>("() => NaN");
277            Assert.AreEqual(double.NaN, result);
278        }
279
280        [PlaywrightTest("page-evaluate.spec.ts", "should return -0")]
281        public async Task ShouldReturnNegative0()
282        {
283            Assert.AreEqual(-0, (await Page.EvaluateAsync<double>("() => -0")));
284        }
285
286        [PlaywrightTest("page-evaluate.spec.ts", "should return Infinity")]
287        public async Task ShouldReturnInfinity()
288        {
289            double result = await Page.EvaluateAsync<double>("() => Infinity");
290            Assert.AreEqual(double.PositiveInfinity, result);
291        }
292
293        [PlaywrightTest("page-evaluate.spec.ts", "should return -Infinity")]
294        public async Task ShouldReturnNegativeInfinity()
295        {
296            double result = await Page.EvaluateAsync<double>("() => -Infinity");
297            Assert.AreEqual(double.NegativeInfinity, result);
298        }
299
300        [PlaywrightTest("page-evaluate.spec.ts", "should work with overwritten Promise")]
301        public async Task ShouldWorkWithOverwrittenPromise()
302        {
303            await Page.EvaluateAsync(@"() => {
304              const originalPromise = window.Promise;
305              class Promise2 {
306                static all(...arg) {
307                  return wrap(originalPromise.all(...arg));
308                }
309                static race(...arg) {
310                  return wrap(originalPromise.race(...arg));
311                }
312                static resolve(...arg) {
313                  return wrap(originalPromise.resolve(...arg));
314                }
315                constructor(f, r) {
316                  this._promise = new originalPromise(f, r);
317                }
318                then(f, r) {
319                  return wrap(this._promise.then(f, r));
320                }
321                catch(f) {
322                  return wrap(this._promise.catch(f));
323                }
324                finally(f) {
325                  return wrap(this._promise.finally(f));
326                }
327              };
328              const wrap = p => {
329                const result = new Promise2(() => {}, () => {});
330                result._promise = p;
331                return result;
332              };
333              window.Promise = Promise2;
334              window.__Promise2 = Promise2;
335            }");
336
337            Assert.True(await Page.EvaluateAsync<bool>(@"() => {
338              const p = Promise.all([Promise.race([]), new Promise(() => {}).then(() => {})]);
339              return p instanceof window.__Promise2;
340            }"));
341            Assert.AreEqual(42, await Page.EvaluateAsync<int>("() => Promise.resolve(42)"));
342        }
343
344        [PlaywrightTest("page-evaluate.spec.ts", @"should accept ""undefined"" as one of multiple parameters")]
345        public async Task ShouldAcceptUndefinedAsOneOfMultipleParameters()
346        {
347            //C# will send nulls
348            bool result = await Page.EvaluateAsync<bool>(@"({a, b}) => {
349                console.log(a);
350                console.log(b);
351                return Object.is (a, null) && Object.is (b, 'foo')
352            }", new { a = (object)null, b = "foo" });
353            Assert.True(result);
354        }
355
356        [PlaywrightTest("page-evaluate.spec.ts", "should properly serialize undefined fields")]
357        public async Task ShouldProperlySerializeUndefinedFields()
358        {
359            dynamic result = await Page.EvaluateAsync<ExpandoObject>("() => ({a: undefined})");
360            Assert.Null(result.a);
361        }
362
363        [PlaywrightTest("page-evaluate.spec.ts", "should properly serialize null arguments")]
364        public async Task ShouldProperlySerializeNullArguments()
365                => Assert.Null(await Page.EvaluateAsync<JsonDocument>("x => x", null));
366
367        [PlaywrightTest("page-evaluate.spec.ts", "should properly serialize null fields")]
368        public async Task ShouldProperlySerializeNullFields()
369        {
370            dynamic result = await Page.EvaluateAsync<ExpandoObject>("() => ({ a: null})");
371            Assert.Null(result.a);
372        }
373
374        [PlaywrightTest("page-evaluate.spec.ts", "should return undefined for non-serializable objects")]
375        public async Task ShouldReturnUndefinedForNonSerializableObjects()
376            => Assert.Null(await Page.EvaluateAsync<object>("() => window"));
377
378        [PlaywrightTest("page-evaluate.spec.ts", "should fail for circular object")]
379        public async Task ShouldFailForCircularObject()
380        {
381            object result = await Page.EvaluateAsync<object>(@"() => {
382                var a = { };
383                var b = { a };
384                a.b = b;
385                return a;
386            }");
387            Assert.Null(result);
388        }
389
390        [PlaywrightTest("page-evaluate.spec.ts", "should be able to throw a tricky error")]
391        public async Task ShouldBeAbleToThrowATrickyError()
392        {
393            var windowHandle = await Page.EvaluateHandleAsync("() => window");
394            var exceptionText = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => windowHandle.JsonValueAsync<object>());
395            var error = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.EvaluateAsync<JsonElement>(@"errorText => {
396                throw new Error(errorText);
397            }", exceptionText.Message));
398            StringAssert.Contains(exceptionText.Message, error.Message);
399        }
400
401        [PlaywrightTest("page-evaluate.spec.ts", "should accept a string with comments")]
402        public async Task ShouldAcceptAStringWithComments()
403        {
404            int result = await Page.EvaluateAsync<int>("2 + 5;\n// do some math!");
405            Assert.AreEqual(7, result);
406        }
407
408        [PlaywrightTest("page-evaluate.spec.ts", "should accept element handle as an argument")]
409        public async Task ShouldAcceptElementHandleAsAnArgument()
410        {
411            await Page.SetContentAsync("<section>42</section>");
412            var element = await Page.QuerySelectorAsync("section");
413            string text = await Page.EvaluateAsync<string>("e => e.textContent", element);
414            Assert.AreEqual("42", text);
415        }
416
417        [PlaywrightTest("page-evaluate.spec.ts", "should throw if underlying element was disposed")]
418        public async Task ShouldThrowIfUnderlyingElementWasDisposed()
419        {
420            await Page.SetContentAsync("<section>39</section>");
421            var element = await Page.QuerySelectorAsync("section");
422            Assert.NotNull(element);
423            await element.DisposeAsync();
424
425            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.EvaluateAsync("e => e.textContent", element));
426            StringAssert.Contains("JSHandle is disposed", exception.Message);
427        }
428
429        [PlaywrightTest("page-evaluate.spec.ts", "should simulate a user gesture")]
430        public async Task ShouldSimulateAUserGesture()
431        {
432            bool result = await Page.EvaluateAsync<bool>(@"() => {
433                document.body.appendChild(document.createTextNode('test'));
434                document.execCommand('selectAll');
435                return document.execCommand('copy');
436            }");
437            Assert.True(result);
438        }
439
440        [PlaywrightTest("page-evaluate.spec.ts", "should throw a nice error after a navigation")]
441        public async Task ShouldThrowANiceErrorAfterANavigation()
442        {
443            var evaluateTask = Page.EvaluateAsync("() => new Promise(f => window.__resolve = f)");
444            await TaskUtils.WhenAll(
445                Page.WaitForNavigationAsync(),
446                Page.EvaluateAsync(@"() => {
447                    window.location.reload();
448                    setTimeout(() => window.__resolve(42), 1000);
449                }")
450            );
451            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => evaluateTask);
452            StringAssert.Contains("navigation", exception.Message);
453        }
454
455        [PlaywrightTest("page-evaluate.spec.ts", "should not throw an error when evaluation does a navigation")]
456        public async Task ShouldNotThrowAnErrorWhenEvaluationDoesANavigation()
457        {
458            await Page.GotoAsync(Server.Prefix + "/one-style.html");
459            int[] result = await Page.EvaluateAsync<int[]>(@"() => {
460                window.location = '/empty.html';
461                return [42];
462            }");
463            Assert.AreEqual(new[] { 42 }, result);
464        }
465
466        [PlaywrightTest("page-evaluate.spec.ts", "should not throw an error when evaluation does a synchronous navigation and returns an object")]
467        [Skip(SkipAttribute.Targets.Webkit)]
468        public async Task ShouldNotThrowAnErrorWhenEvaluationDoesASynchronousNavigationAndReturnsAnObject()
469        {
470            var result = await Page.EvaluateAsync<JsonElement>(@"() => {
471                window.location.reload();
472                return {a: 42};
473            }");
474            Assert.AreEqual(42, result.GetProperty("a").GetInt32());
475        }
476
477        [PlaywrightTest("page-evaluate.spec.ts", "should not throw an error when evaluation does a synchronous navigation and returns an undefined")]
478        [Skip(SkipAttribute.Targets.Webkit)]
479        public async Task ShouldNotThrowAnErrorWhenEvaluationDoesASynchronousNavigationAndReturnsUndefined()
480        {
481            var result = await Page.EvaluateAsync<JsonElement?>(@"() => {
482                window.location.reload();
483                return undefined;
484            }");
485            Assert.Null(result);
486        }
487
488        [PlaywrightTest("page-evaluate.spec.ts", "should transfer 100Mb of data from page to node.js")]
489        public async Task ShouldTransfer100MbOfDataFromPageToNodeJs()
490        {
491            string a = await Page.EvaluateAsync<string>("() => Array(100 * 1024 * 1024 + 1).join('a')");
492            Assert.AreEqual(100 * 1024 * 1024, a.Length);
493        }
494
495        [PlaywrightTest("page-evaluate.spec.ts", "should throw error with detailed information on exception inside promise ")]
496        public async Task ShouldThrowErrorWithDetailedInformationOnExceptionInsidePromise()
497        {
498            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.EvaluateAsync<object>(@"() => new Promise(() => {
499                throw new Error('Error in promise');
500            })"));
501            StringAssert.Contains("Error in promise", exception.Message);
502        }
503
504        [PlaywrightTest("page-evaluate.spec.ts", "should work even when JSON is set to null")]
505        public async Task ShouldWorkEvenWhenJSONIsSetToNull()
506        {
507            await Page.EvaluateAsync<object>("() => { window.JSON.stringify = null; window.JSON = null; }");
508            var result = await Page.EvaluateAsync<JsonElement>("() => ({ abc: 123})");
509            Assert.AreEqual(123, result.GetProperty("abc").GetInt32());
510        }
511
512        [PlaywrightTest("page-evaluate.spec.ts", "should await promise from popup")]
513        [Skip(SkipAttribute.Targets.Firefox)]
514        public async Task ShouldAwaitPromiseFromPopup()
515        {
516            await Page.GotoAsync(Server.EmptyPage);
517
518            int result = await Page.EvaluateAsync<int>(@"() => {
519                const win = window.open('about:blank');
520                return new win.Promise(f => f(42));
521            }");
522            Assert.AreEqual(42, result);
523        }
524
525        [PlaywrightTest("page-evaluate.spec.ts", "should work with non-strict expressions")]
526        public async Task ShouldWorkWithNonStrictExpressions()
527        {
528            Assert.AreEqual(3.14m, await Page.EvaluateAsync<decimal>(@"() => {
529              y = 3.14;
530              return y;
531            }"));
532        }
533
534        [PlaywrightTest("page-evaluate.spec.ts", "should respect use strict expression")]
535        public async Task ShouldRespectUseStrictExpression()
536        {
537            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.EvaluateAsync<object>(@"() => {
538                ""use strict"";
539                variableY = 3.14;
540               return variableY;
541            }"));
542            StringAssert.Contains("variableY", exception.Message);
543        }
544
545        [PlaywrightTest("page-evaluate.spec.ts", "should not leak utility script")]
546        public async Task ShouldNotLeakUtilityScript()
547        {
548            Assert.True(await Page.EvaluateAsync<bool>(@"() => this === window"));
549        }
550
551        [PlaywrightTest("page-evaluate.spec.ts", "should not leak handles")]
552        public async Task ShouldNotLeakHandles()
553        {
554            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.EvaluateAsync<object>(@"() => handles.length"));
555            StringAssert.Contains("handles", exception.Message);
556        }
557
558        [PlaywrightTest("page-evaluate.spec.ts", "should evaluate exception")]
559        public async Task ShouldEvaluateException()
560        {
561            string exception = await Page.EvaluateAsync<string>(@"() => {
562                return (function functionOnStack() {
563                    return new Error('error message');
564                })();
565            }");
566            StringAssert.Contains("Error: error message", exception);
567            StringAssert.Contains("functionOnStack", exception);
568        }
569
570        [PlaywrightTest("page-evaluate.spec.ts", "should evaluate exception")]
571        public async Task ShouldEvaluateException2()
572        {
573            string exception = await Page.EvaluateAsync<string>(@"() => new Error('error message')");
574            StringAssert.Contains("Error: error message", exception);
575        }
576
577        [PlaywrightTest("page-evaluate.spec.ts", "should evaluate date")]
578        public async Task ShouldEvaluateDate()
579        {
580            dynamic result = await Page.EvaluateAsync<ExpandoObject>(@"() => ({ date: new Date('2020-05-27T01:31:38.506Z') })");
581            Assert.AreEqual(new DateTime(2020, 05, 27, 1, 31, 38, 506), result.date);
582        }
583
584        [PlaywrightTest("page-evaluate.spec.ts", "should roundtrip date")]
585        public async Task ShouldRoundtripDate()
586        {
587            var date = new DateTime(2020, 05, 27, 1, 31, 38, 506, DateTimeKind.Utc);
588            var result = await Page.EvaluateAsync<DateTime>(@"date => date", date);
589            Assert.AreEqual(date, result);
590        }
591
592        [PlaywrightTest()]
593        public async Task ShouldTreatEcma2020AsFunctions()
594             => Assert.AreEqual("dario", await Page.EvaluateAsync<string>(
595                 @"() => {
596                    const person = { name: 'dario' };
597                    return person?.name;
598                }"));
599
600        [PlaywrightTest("page-evaluate.spec.ts", "should roundtrip regex")]
601        public async Task ShouldRoundtripRegex()
602        {
603            var regex = new Regex("hello", RegexOptions.IgnoreCase | RegexOptions.Multiline);
604            var result = await Page.EvaluateAsync<Regex>("regex => regex", regex);
605            Assert.AreEqual(regex.ToString(), result.ToString());
606            Assert.AreEqual(regex.Options, result.Options);
607        }
608
609        [PlaywrightTest("page-evaluate.spec.ts", "should jsonValue() date")]
610        public async Task ShouldJsonValueDate()
611        {
612            var resultHandle = await Page.EvaluateHandleAsync(@"() => ({ date: new Date('2020-05-27T01:31:38.506Z') })");
613            dynamic result = await resultHandle.JsonValueAsync<ExpandoObject>();
614            Assert.AreEqual(new DateTime(2020, 05, 27, 1, 31, 38, 506), result.date);
615        }
616
617        public async Task ShouldSerializeEnumProperty()
618        {
619            int result = await Page.EvaluateAsync<int>("a => a.TestEnum", new ClassWithEnumProperty());
620            Assert.AreEqual(1, result);
621        }
622
623        private class ClassWithEnumProperty
624        {
625            public TestEnum TestEnum { get; set; } = TestEnum.Test;
626        }
627
628        private enum TestEnum
629        {
630            Test = 1
631        }
632
633        [PlaywrightTest(Description = "https://github.com/microsoft/playwright-dotnet/issues/1706")]
634        public async Task ShouldNotReturnDisposedJsonElement()
635        {
636            var result = await Page.EvaluateAsync<JsonElement?>("()=> [{a:1,b:2},{a:1,b:2}]");
637            Assert.AreEqual("[{\"o\":[{\"k\":\"a\",\"v\":{\"n\":1}},{\"k\":\"b\",\"v\":{\"n\":2}}]},{\"o\":[{\"k\":\"a\",\"v\":{\"n\":1}},{\"k\":\"b\",\"v\":{\"n\":2}}]}]", result.ToString());
638        }
639    }
640}
641
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

Most used method in PageEvaluateTests

Trigger ShouldWorkFromInsideAnExposedFunction code on LambdaTest Cloud Grid

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