How to use PageWaitForFunctionTests class of Microsoft.Playwright.Tests package

Best Playwright-dotnet code snippet using Microsoft.Playwright.Tests.PageWaitForFunctionTests

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

PageWaitForFunctionTests.cs

Source: PageWaitForFunctionTests.cs Github

copy
1/*
2 * MIT License
3 *
4 * Copyright (c) 2020 Darío Kondratiuk
5 * Modifications copyright (c) Microsoft Corporation.
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in all
15 * copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 * SOFTWARE.
24 */
25
26using System;
27using System.Threading.Tasks;
28using Microsoft.Playwright.NUnit;
29using NUnit.Framework;
30
31namespace Microsoft.Playwright.Tests
32{
33    public class PageWaitForFunctionTests : PageTestEx
34    {
35        [PlaywrightTest("page-wait-for-function.spec.ts", "should timeout")]
36        public async Task ShouldTimeout()
37        {
38            var startTime = DateTime.Now;
39            int timeout = 42;
40            await Page.WaitForTimeoutAsync(timeout);
41            Assert.True((DateTime.Now - startTime).TotalMilliseconds > timeout / 2);
42        }
43
44        [PlaywrightTest("page-wait-for-function.spec.ts", "should accept a string")]
45        [Ignore("We don't this test")]
46        public void ShouldAcceptAString()
47        {
48        }
49
50        [PlaywrightTest("page-wait-for-function.spec.tsPageWaitForFunctionTests", "should work when resolved right before execution context disposal")]
51        public async Task ShouldWorkWhenResolvedRightBeforeExecutionContextDisposal()
52        {
53            await Page.AddInitScriptAsync("window.__RELOADED = true");
54            await Page.WaitForFunctionAsync(@"() =>
55            {
56                if (!window.__RELOADED)
57                    window.location.reload();
58                return true;
59            }");
60        }
61
62        [PlaywrightTest("page-wait-for-function.spec.ts", "should poll on interval")]
63        public async Task ShouldPollOnInterval()
64        {
65            int polling = 100;
66            var timeDelta = await Page.WaitForFunctionAsync(@"() => {
67                if (!window.__startTime) {
68                    window.__startTime = Date.now();
69                    return false;
70                }
71                return Date.now() - window.__startTime;
72            }", null, new() { PollingInterval = polling });
73            int value = (await timeDelta.JsonValueAsync<int>());
74
75            Assert.True(value >= polling);
76        }
77
78        [PlaywrightTest("page-wait-for-function.spec.ts", "should avoid side effects after timeout")]
79        public async Task ShouldAvoidSideEffectsAfterTimeout()
80        {
81            int counter = 0;
82            Page.Console += (_, _) => ++counter;
83
84            var exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(() => Page.WaitForFunctionAsync(
85                @"() => {
86                  window.counter = (window.counter || 0) + 1;
87                  console.log(window.counter);
88                }",
89                null, new() { PollingInterval = 1, Timeout = 1000 }));
90
91            int savedCounter = counter;
92            await Page.WaitForTimeoutAsync(2000);
93
94            StringAssert.Contains("Timeout 1000ms exceeded", exception.Message);
95            Assert.AreEqual(savedCounter, counter);
96        }
97
98        [PlaywrightTest("page-wait-for-function.spec.ts", "should throw on polling:mutation")]
99        [Ignore("We don't need to test this")]
100        public void ShouldThrowOnPollingMutation()
101        {
102        }
103
104        [PlaywrightTest("page-wait-for-function.spec.ts", "should poll on raf")]
105        [Ignore("We don't support raf")]
106        public void ShouldPollOnRaf()
107        {
108            /*
109            var watchdog = Page.WaitForFunctionAsync(
110                "() => window.__FOO === 'hit'",
111                polling: Polling.Raf);
112            await Page.EvaluateAsync("window.__FOO = 'hit'");
113            await watchdog;
114            */
115        }
116
117        [PlaywrightTest("page-wait-for-function.spec.ts", "should fail with predicate throwing on first call")]
118        public async Task ShouldFailWithPredicateThrowingOnFirstCall()
119        {
120            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.WaitForFunctionAsync("() => { throw new Error('oh my'); }"));
121            StringAssert.Contains("oh my", exception.Message);
122        }
123
124        [PlaywrightTest("page-wait-for-function.spec.ts", "should fail with predicate throwing sometimes")]
125        public async Task ShouldFailWithPredicateThrowingSometimes()
126        {
127            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.WaitForFunctionAsync(@"() => {
128              window.counter = (window.counter || 0) + 1;
129              if (window.counter === 3)
130                throw new Error('Bad counter!');
131              return window.counter === 5 ? 'result' : false;
132            }"));
133            StringAssert.Contains("Bad counter!", exception.Message);
134        }
135
136        [PlaywrightTest("page-wait-for-function.spec.ts", "should fail with ReferenceError on wrong page")]
137        public async Task ShouldFailWithReferenceErrorOnWrongPage()
138        {
139            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.WaitForFunctionAsync("() => globalVar === 123"));
140            StringAssert.Contains("globalVar", exception.Message);
141        }
142
143        [PlaywrightTest("page-wait-for-function.spec.ts", "should work with strict CSP policy")]
144        [Ignore("We don't support raf")]
145        public void ShouldWorkWithStrictCSPPolicy()
146        {
147            /*
148            Server.SetCSP("/empty.html", "script-src " + Server.Prefix);
149            await Page.GotoAsync(Server.EmptyPage);
150            await TaskUtils.WhenAll(
151                Page.WaitForFunctionAsync(
152                    "() => window.__FOO === 'hit'",
153                    polling: Polling.Raf),
154                Page.EvaluateAsync("window.__FOO = 'hit'"));
155            */
156        }
157
158        [PlaywrightTest("page-wait-for-function.spec.ts", "should throw on bad polling value")]
159        [Ignore("We don't this test")]
160        public void ShouldThrowOnBadPollingValue()
161        {
162        }
163
164        [PlaywrightTest("page-wait-for-function.spec.ts", "should throw negative polling interval")]
165        public async Task ShouldThrowNegativePollingInterval()
166        {
167            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(()
168                => Page.WaitForFunctionAsync("() => !!document.body", null, new() { PollingInterval = -10 }));
169
170            StringAssert.Contains("Cannot poll with non-positive interval", exception.Message);
171        }
172
173        [PlaywrightTest("page-wait-for-function.spec.ts", "should return the success value as a JSHandle")]
174        public async Task ShouldReturnTheSuccessValueAsAJSHandle()
175            => Assert.AreEqual(5, await (await Page.WaitForFunctionAsync("() => 5")).JsonValueAsync<int>());
176
177        [PlaywrightTest("page-wait-for-function.spec.ts", "should return the window as a success value")]
178        public async Task ShouldReturnTheWindowAsASuccessValue()
179            => Assert.NotNull(await Page.WaitForFunctionAsync("() => window"));
180
181        [PlaywrightTest("page-wait-for-function.spec.ts", "should accept ElementHandle arguments")]
182        public async Task ShouldAcceptElementHandleArguments()
183        {
184            await Page.SetContentAsync("<div></div>");
185            var div = await Page.QuerySelectorAsync("div");
186            bool resolved = false;
187            var waitForFunction = Page.WaitForFunctionAsync("element => !element.parentElement", div)
188                .ContinueWith(_ => resolved = true);
189            Assert.False(resolved);
190            await Page.EvaluateAsync("element => element.remove()", div);
191            await waitForFunction;
192        }
193
194        [PlaywrightTest("page-wait-for-function.spec.ts", "should respect timeout")]
195        public async Task ShouldRespectTimeout()
196        {
197            var exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(()
198                => Page.WaitForFunctionAsync("false", null, new() { Timeout = 10 }));
199
200            StringAssert.Contains("Timeout 10ms exceeded", exception.Message);
201        }
202
203        [PlaywrightTest("page-wait-for-function.spec.ts", "should respect default timeout")]
204        public async Task ShouldRespectDefaultTimeout()
205        {
206            Page.SetDefaultTimeout(1);
207            var exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(()
208                => Page.WaitForFunctionAsync("false"));
209
210            StringAssert.Contains("Timeout 1ms exceeded", exception.Message);
211        }
212
213        [PlaywrightTest("page-wait-for-function.spec.ts", "should disable timeout when its set to 0")]
214        public async Task ShouldDisableTimeoutWhenItsSetTo0()
215        {
216            var watchdog = Page.WaitForFunctionAsync(
217                @"() => {
218                    window.__counter = (window.__counter || 0) + 1;
219                    return window.__injected;
220                }",
221                null,
222                new()
223                {
224                    PollingInterval = 10,
225                    Timeout = 0
226                });
227            await Page.WaitForFunctionAsync("() => window.__counter > 10");
228            await Page.EvaluateAsync("window.__injected = true");
229            await watchdog;
230        }
231
232        [PlaywrightTest("page-wait-for-function.spec.ts", "should survive cross-process navigation")]
233        public async Task ShouldSurviveCrossProcessNavigation()
234        {
235            bool fooFound = false;
236            var waitForFunction = Page.WaitForFunctionAsync("window.__FOO === 1")
237                .ContinueWith(_ => fooFound = true);
238            await Page.GotoAsync(Server.EmptyPage);
239            Assert.False(fooFound);
240            await Page.ReloadAsync();
241            Assert.False(fooFound);
242            await Page.GotoAsync(Server.CrossProcessPrefix + "/grid.html");
243            Assert.False(fooFound);
244            await Page.EvaluateAsync("window.__FOO = 1");
245            await waitForFunction;
246            Assert.True(fooFound);
247        }
248
249        [PlaywrightTest("page-wait-for-function.spec.ts", "should survive navigations")]
250        public async Task ShouldSurviveNavigations()
251        {
252            var watchdog = Page.WaitForFunctionAsync("() => window.__done");
253            await Page.GotoAsync(Server.EmptyPage);
254            await Page.GotoAsync(Server.Prefix + "/consolelog.html");
255            await Page.EvaluateAsync("() => window.__done = true");
256            await watchdog;
257        }
258
259        [PlaywrightTest("page-wait-for-function.spec.ts", "should work with multiline body")]
260        public async Task ShouldWorkWithMultilineBody()
261        {
262            var result = await Page.WaitForFunctionAsync(@"
263                (() => true)()
264            ");
265
266            Assert.True(await result.JsonValueAsync<bool>());
267        }
268
269        [PlaywrightTest("page-wait-for-function.spec.ts", "should wait for predicate with arguments")]
270        public Task ShouldWaitForPredicateWithArguments()
271            => Page.WaitForFunctionAsync(@"({arg1, arg2}) => arg1 + arg2 === 3", new { arg1 = 1, arg2 = 2 });
272    }
273}
274
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
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)