How to use JavaScriptTests class of com.github.epadronu.balin.core package

Best Balin code snippet using com.github.epadronu.balin.core.JavaScriptTests

Run Balin automation tests on LambdaTest cloud grid

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

JavaScriptExecutor.kt

Source: JavaScriptExecutor.kt Github

copy
1/******************************************************************************
2 * Copyright 2016 Edinson E. Padrón Urdaneta
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *****************************************************************************/
16
17/* ***************************************************************************/
18package com.github.epadronu.balin.core
19/* ***************************************************************************/
20
21/* ***************************************************************************/
22/**
23 * Describes an easier way to interact with
24 * [JavascriptExecutor.executeScript][org.openqa.selenium.JavascriptExecutor.executeScript] &
25 * [JavascriptExecutor.executeAsyncScript][org.openqa.selenium.JavascriptExecutor.executeAsyncScript],
26 * allowing the execution of synchronous and asynchronous JavaScript code if
27 * such functionality is supported by the underlying driver.
28 *
29 * ### Synchronous code
30 * @sample com.github.epadronu.balin.core.JavaScriptTests.execute_javaScript_code_with_arguments_via_the_invoke_operator
31 *
32 * ### Asynchronous code
33 * @sample com.github.epadronu.balin.core.JavaScriptTests.execute_an_asynchronous_javascript_code
34 */
35interface JavaScriptExecutor {
36
37    /**
38     * Executes JavaScript in the context of the currently selected frame or
39     * window. The script fragment provided will be executed as the body of an
40     * anonymous function.
41     *
42     * Within the script, use document to refer to the current document. Note
43     * that local variables will not be available once the script has finished
44     * executing, though global variables will persist.
45     *
46     * If the script has a return value (i.e. if the script contains a return
47     * statement), then the following steps will be taken:
48     *
49     * - For an HTML element, this method returns a WebElement
50     * - For a decimal, a Double is returned
51     * - For a non-decimal number, a Long is returned
52     * - For a boolean, a Boolean is returned
53     * - For all other cases, a String is returned.
54     * - For an array, return a List<Object> with each object following the rules above. We support nested lists.
55     * - For a map, return a Map<String, Object> with values following the rules above.
56     * - Unless the value is null or there is no return value, in which null is returned
57     *
58     * Arguments must be a number, a boolean, a String, WebElement, or a List
59     * of any combination of the above. An exception will be thrown if the
60     * arguments do not meet these criteria. The arguments will be made
61     * available to the JavaScript via the "`arguments`" magic variable, as if
62     * the function were called via "`Function.apply`"
63     *
64     * In the case of `async = true`, unlike executing synchronous JavaScript,
65     * scripts executed with this method must explicitly signal they are
66     * finished by invoking the provided callback. This callback is always
67     * injected into the executed function as the last argument.
68     *
69     * The default timeout for a script to be executed is 0ms. In most cases,
70     * including the examples below, one must set the script timeout
71     * ([Timeouts.setScriptTimeout][org.openqa.selenium.WebDriver.Timeouts.setScriptTimeout])
72     * beforehand to a value sufficiently large enough.
73     *
74     * @sample com.github.epadronu.balin.core.JavaScriptTests.execute_javaScript_code_with_arguments_via_the_execute_method
75     * @see org.openqa.selenium.JavascriptExecutor.executeScript
76     * @see org.openqa.selenium.JavascriptExecutor.executeAsyncScript
77     *
78     * @param args optional arguments that can be passed to the JS code
79     * @param async indicates if the JS code should be executed asynchronously or not
80     * @param script provides the JS code to be executed
81     * @return One of Boolean, Long, Double, String, List, Map or WebElement. Or null.
82     */
83    fun execute(vararg args: Any, async: Boolean = false, script: () -> String): Any?
84
85    /**
86     * Executes JavaScript in the context of the currently selected frame or
87     * window. The script fragment provided will be executed as the body of an
88     * anonymous function.
89     *
90     * Within the script, use document to refer to the current document. Note
91     * that local variables will not be available once the script has finished
92     * executing, though global variables will persist.
93     *
94     * If the script has a return value (i.e. if the script contains a return
95     * statement), then the following steps will be taken:
96     *
97     * - For an HTML element, this method returns a WebElement
98     * - For a decimal, a Double is returned
99     * - For a non-decimal number, a Long is returned
100     * - For a boolean, a Boolean is returned
101     * - For all other cases, a String is returned.
102     * - For an array, return a List<Object> with each object following the rules above. We support nested lists.
103     * - For a map, return a Map<String, Object> with values following the rules above.
104     * - Unless the value is null or there is no return value, in which null is returned
105     *
106     * Arguments must be a number, a boolean, a String, WebElement, or a List
107     * of any combination of the above. An exception will be thrown if the
108     * arguments do not meet these criteria. The arguments will be made
109     * available to the JavaScript via the "`arguments`" magic variable, as if
110     * the function were called via "`Function.apply`"
111     *
112     * In the case of `async = true`, unlike executing synchronous JavaScript,
113     * scripts must explicitly signal they are finished by invoking the
114     * provided callback. This callback is always injected into the executed
115     * function as the last argument.
116     *
117     * The default timeout for a script to be executed is 0ms. In most cases,
118     * including the examples below, one must set the script timeout
119     * ([Timeouts.setScriptTimeout][org.openqa.selenium.WebDriver.Timeouts.setScriptTimeout])
120     * beforehand to a value sufficiently large enough.
121     *
122     * @sample com.github.epadronu.balin.core.JavaScriptTests.execute_javaScript_code_with_arguments_via_the_call_method
123     * @see org.openqa.selenium.JavascriptExecutor.executeScript
124     * @see org.openqa.selenium.JavascriptExecutor.executeAsyncScript
125     *
126     * @param args optional arguments that can be passed to the JS code
127     * @param async indicates if the JS code should be executed asynchronously or not
128     * @param script provides the JS code to be executed
129     * @return One of Boolean, Long, Double, String, List, Map or WebElement. Or null.
130     */
131    fun call(vararg args: Any, async: Boolean = false, script: () -> String): Any? = execute(
132        *args, async = async, script = script
133    )
134
135    /**
136     * Executes JavaScript in the context of the currently selected frame or
137     * window. The script fragment provided will be executed as the body of an
138     * anonymous function.
139     *
140     * Within the script, use document to refer to the current document. Note
141     * that local variables will not be available once the script has finished
142     * executing, though global variables will persist.
143     *
144     * If the script has a return value (i.e. if the script contains a return
145     * statement), then the following steps will be taken:
146     *
147     * - For an HTML element, this method returns a WebElement
148     * - For a decimal, a Double is returned
149     * - For a non-decimal number, a Long is returned
150     * - For a boolean, a Boolean is returned
151     * - For all other cases, a String is returned.
152     * - For an array, return a List<Object> with each object following the rules above. We support nested lists.
153     * - For a map, return a Map<String, Object> with values following the rules above.
154     * - Unless the value is null or there is no return value, in which null is returned
155     *
156     * Arguments must be a number, a boolean, a String, WebElement, or a List
157     * of any combination of the above. An exception will be thrown if the
158     * arguments do not meet these criteria. The arguments will be made
159     * available to the JavaScript via the "`arguments`" magic variable, as if
160     * the function were called via "`Function.apply`"
161     *
162     * In the case of `async = true`, unlike executing synchronous JavaScript,
163     * scripts executed with this method must explicitly signal they are
164     * finished by invoking the provided callback. This callback is always
165     * injected into the executed function as the last argument.
166     *
167     * The default timeout for a script to be executed is 0ms. In most cases,
168     * including the examples below, one must set the script timeout
169     * ([Timeouts.setScriptTimeout][org.openqa.selenium.WebDriver.Timeouts.setScriptTimeout])
170     * beforehand to a value sufficiently large enough.
171     *
172     * @sample com.github.epadronu.balin.core.JavaScriptTests.execute_javaScript_code_with_arguments_via_the_run_method
173     * @see org.openqa.selenium.JavascriptExecutor.executeScript
174     * @see org.openqa.selenium.JavascriptExecutor.executeAsyncScript
175     *
176     * @param args optional arguments that can be passed to the JS code
177     * @param async indicates if the JS code should be executed asynchronously or not
178     * @param script provides the JS code to be executed
179     * @return One of Boolean, Long, Double, String, List, Map or WebElement. Or null.
180     */
181    fun run(vararg args: Any, async: Boolean = false, script: () -> String): Any? = execute(
182        *args, async = async, script = script
183    )
184
185    /**
186     * Executes JavaScript in the context of the currently selected frame or
187     * window. The script fragment provided will be executed as the body of an
188     * anonymous function.
189     *
190     * Within the script, use document to refer to the current document. Note
191     * that local variables will not be available once the script has finished
192     * executing, though global variables will persist.
193     *
194     * If the script has a return value (i.e. if the script contains a return
195     * statement), then the following steps will be taken:
196     *
197     * - For an HTML element, this method returns a WebElement
198     * - For a decimal, a Double is returned
199     * - For a non-decimal number, a Long is returned
200     * - For a boolean, a Boolean is returned
201     * - For all other cases, a String is returned.
202     * - For an array, return a List<Object> with each object following the rules above. We support nested lists.
203     * - For a map, return a Map<String, Object> with values following the rules above.
204     * - Unless the value is null or there is no return value, in which null is returned
205     *
206     * Arguments must be a number, a boolean, a String, WebElement, or a List
207     * of any combination of the above. An exception will be thrown if the
208     * arguments do not meet these criteria. The arguments will be made
209     * available to the JavaScript via the "`arguments`" magic variable, as if
210     * the function were called via "`Function.apply`"
211     *
212     * In the case of `async = true`, unlike executing synchronous JavaScript,
213     * scripts executed with this method must explicitly signal they are
214     * finished by invoking the provided callback. This callback is always
215     * injected into the executed function as the last argument.
216     *
217     * The default timeout for a script to be executed is 0ms. In most cases,
218     * including the examples below, one must set the script timeout
219     * ([Timeouts.setScriptTimeout][org.openqa.selenium.WebDriver.Timeouts.setScriptTimeout])
220     * beforehand to a value sufficiently large enough.
221     *
222     * @sample com.github.epadronu.balin.core.JavaScriptTests.execute_javaScript_code_with_arguments_via_the_invoke_operator
223     * @see org.openqa.selenium.JavascriptExecutor.executeScript
224     * @see org.openqa.selenium.JavascriptExecutor.executeAsyncScript
225     *
226     * @param args optional arguments that can be passed to the JS code
227     * @param async indicates if the JS code should be executed asynchronously or not
228     * @param script provides the JS code to be executed
229     * @return One of Boolean, Long, Double, String, List, Map or WebElement. Or null.
230     */
231    operator fun invoke(vararg args: Any, async: Boolean = false, script: () -> String): Any? = execute(
232        *args, async = async, script = script
233    )
234
235    /**
236     * Get the value of a global-JavaScript variable.
237     *
238     * @sample com.github.epadronu.balin.core.JavaScriptTests.set_a_global_js_variable_and_retrieve_it_via_a_get
239     *
240     * @param value the name of the variable which value will be retrieved.
241     * @return One of Boolean, Long, Double, String, List, Map or WebElement. Or null.
242     */
243    operator fun get(value: String): Any? = execute { "return $value;" }
244
245    /**
246     * Set the value of a global-JavaScript variable.
247     *
248     * @sample com.github.epadronu.balin.core.JavaScriptTests.set_a_global_js_variable_and_retrieve_it_via_a_get
249     *
250     * @param name the name of the variable.
251     * @param value the value of the variable. (It can be null.)
252     */
253    operator fun set(name: String, value: Any?) {
254        when (value) {
255            null -> execute { "window.$name = null;" }
256            else -> execute(value) { "window.$name = arguments[0];" }
257        }
258    }
259}
260/* ***************************************************************************/
261
Full Screen

JavaScriptSupport.kt

Source: JavaScriptSupport.kt Github

copy
1/******************************************************************************
2 * Copyright 2016 Edinson E. Padrón Urdaneta
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *****************************************************************************/
16
17/* ***************************************************************************/
18package com.github.epadronu.balin.core
19/* ***************************************************************************/
20
21/* ***************************************************************************/
22/**
23 * Describes the `js` property support, which aims to ease the use of
24 * [JavascriptExecutor.executeScript][org.openqa.selenium.JavascriptExecutor.executeScript] &
25 * [JavascriptExecutor.executeAsyncScript][org.openqa.selenium.JavascriptExecutor.executeAsyncScript].
26 *
27 * @sample com.github.epadronu.balin.core.JavaScriptTests.execute_javaScript_code_with_arguments_via_the_invoke_operator
28 */
29interface JavaScriptSupport {
30
31    /**
32     * Allows the execution of synchronous and asynchronous JavaScript code if
33     * such functionality is supported by the underlying driver.
34     */
35    val js: JavaScriptExecutor
36}
37/* ***************************************************************************/
38
Full Screen

JavaScriptTests.kt

Source: JavaScriptTests.kt Github

copy
1/******************************************************************************
2 * Copyright 2016 Edinson E. Padrón Urdaneta
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *****************************************************************************/
16
17/* ***************************************************************************/
18package com.github.epadronu.balin.core
19/* ***************************************************************************/
20
21/* ***************************************************************************/
22import com.gargoylesoftware.htmlunit.ScriptException
23import com.github.epadronu.balin.extensions.`$`
24import org.openqa.selenium.WebDriver
25import org.openqa.selenium.htmlunit.HtmlUnitDriver
26import org.testng.Assert.assertEquals
27import org.testng.Assert.expectThrows
28import org.testng.Assert.fail
29import org.testng.annotations.DataProvider
30import org.testng.annotations.Test
31import java.util.concurrent.TimeUnit
32import com.gargoylesoftware.htmlunit.BrowserVersion.FIREFOX_60 as BROWSER_VERSION
33/* ***************************************************************************/
34
35/* ***************************************************************************/
36class JavaScriptTests {
37
38    @DataProvider(name = "JavaScript-incapable WebDriver factory", parallel = true)
39    fun `Create a JavaScript-incapable WebDriver factory`() = arrayOf(
40        arrayOf({ HtmlUnitDriver(BROWSER_VERSION) })
41    )
42
43    @DataProvider(name = "JavaScript-enabled WebDriver factory", parallel = true)
44    fun `Create a JavaScript-enabled WebDriver factory`() = arrayOf(
45        arrayOf({
46            HtmlUnitDriver(BROWSER_VERSION).apply {
47                isJavascriptEnabled = true
48
49                manage().timeouts().setScriptTimeout(2L, TimeUnit.SECONDS)
50            }
51        })
52    )
53
54    @Test(dataProvider = "JavaScript-incapable WebDriver factory")
55    fun `Execute valid JavaScript code in a JS-incapable browser`(driverFactory: () -> WebDriver) {
56        Browser.drive(driverFactory = driverFactory) {
57            // When I navigate to the Kotlin's page URL
58            to("https://kotlinlang.org/")
59
60            // And I execute valid JavaScript code
61            // Then such execution should be a failure
62            expectThrows(UnsupportedOperationException::class.java) {
63                js.call { "console.log(\"Hello, world!\")" }
64            }
65        }
66    }
67
68    @Test(dataProvider = "JavaScript-enabled WebDriver factory")
69    fun `Execute valid JavaScript code in the browser`(driverFactory: () -> WebDriver) {
70        Browser.drive(driverFactory = driverFactory) {
71            // When I navigate to the Kotlin's page URL
72            to("https://kotlinlang.org/")
73
74            try {
75                // And I execute a simple `console.log`
76                js.call { "console.log(\"Hello, world!\")" }
77            } catch (exception: ScriptException) {
78                // Then such execution should be successful
79                fail(exception.message)
80            }
81        }
82    }
83
84    @Test(dataProvider = "JavaScript-enabled WebDriver factory")
85    fun `Execute invalid JavaScript code in the browser`(driverFactory: () -> WebDriver) {
86        Browser.drive(driverFactory = driverFactory) {
87            // When I navigate to the Kotlin's page URL
88            to("https://kotlinlang.org/")
89
90            // And I execute an invalid JavaScript code
91            // Then such execution should be a failure
92            expectThrows(ScriptException::class.java) {
93                js.call { "an obvious bad JavaScript code" }
94            }
95        }
96    }
97
98    @Test(description = "Execute JavaScript code with arguments via the call method",
99        dataProvider = "JavaScript-enabled WebDriver factory")
100    fun execute_javaScript_code_with_arguments_via_the_call_method(driverFactory: () -> WebDriver) {
101        Browser.drive(driverFactory = driverFactory) {
102            // When I navigate to the Kotlin's page URL
103            to("https://kotlinlang.org/")
104
105            // And I execute JavaScript code with arguments via `call`
106            val arguments = js.call(1, 2) {
107                "return 'Arguments: ' + arguments[0] + ', ' + arguments[1];"
108            }
109
110            // Then I should get the arguments as is
111            assertEquals(arguments, "Arguments: 1, 2")
112        }
113    }
114
115    @Test(description = "Execute JavaScript code with arguments via the execute method",
116        dataProvider = "JavaScript-enabled WebDriver factory")
117    fun execute_javaScript_code_with_arguments_via_the_execute_method(driverFactory: () -> WebDriver) {
118        Browser.drive(driverFactory = driverFactory) {
119            // When I navigate to the Kotlin's page URL
120            to("https://kotlinlang.org/")
121
122            // And I execute JavaScript code with arguments via `execute`
123            val arguments = js.execute(true, false) {
124                "return 'Arguments: ' + arguments[0] + ', ' + arguments[1];"
125            }
126
127            // Then I should get the arguments as is
128            assertEquals(arguments, "Arguments: true, false")
129        }
130    }
131
132    @Test(description = "Execute JavaScript code with arguments via the run method",
133        dataProvider = "JavaScript-enabled WebDriver factory")
134    fun execute_javaScript_code_with_arguments_via_the_run_method(driverFactory: () -> WebDriver) {
135        Browser.drive(driverFactory = driverFactory) {
136            // When I navigate to the Kotlin's page URL
137            to("https://kotlinlang.org/")
138
139            // And I execute JavaScript code with arguments via `run`
140            val arguments = js.run("a", "b") {
141                "return 'Arguments: ' + arguments[0] + ', ' + arguments[1];"
142            }
143
144            // Then I should get the arguments as is
145            assertEquals(arguments, "Arguments: a, b")
146        }
147    }
148
149    @Test(description = "Execute JavaScript code with arguments via the invoke operator",
150        dataProvider = "JavaScript-enabled WebDriver factory")
151    fun execute_javaScript_code_with_arguments_via_the_invoke_operator(driverFactory: () -> WebDriver) {
152        Browser.drive(driverFactory = driverFactory) {
153            // When I navigate to the Kotlin's page URL
154            to("https://kotlinlang.org/")
155
156            // And I execute JavaScript code with arguments via `invoke`
157            val arguments = js(1.5, 2.3) {
158                "return 'Arguments: ' + arguments[0] + ', ' + arguments[1];"
159            }
160
161            // Then I should get the arguments as is
162            assertEquals(arguments, "Arguments: 1.5, 2.3")
163        }
164    }
165
166    @Test(dataProvider = "JavaScript-enabled WebDriver factory")
167    fun `Execute JavaScript code with a WebElement as its argument and interact with it`(driverFactory: () -> WebDriver) {
168        Browser.drive(driverFactory = driverFactory) {
169            // When I navigate to the Kotlin's page URL
170            to("https://kotlinlang.org/")
171
172            // And I execute JavaScript code with a WebElement as its argument and return its content
173            val text = js(`$`(".terms-copyright", 0)) {
174                "return arguments[0].textContent.replace(/\\n +/g, ' ').trim()"
175            }
176
177            // Then I should get such content as expected
178            assertEquals(text, "Licensed under the Apache 2 license")
179        }
180    }
181
182    @Test(dataProvider = "JavaScript-enabled WebDriver factory")
183    fun `Set a global JS variable and retrieve it via the execute method`(driverFactory: () -> WebDriver) {
184        Browser.drive(driverFactory = driverFactory) {
185            // When I navigate to the Kotlin's page URL
186            to("https://kotlinlang.org/")
187
188            // And I set a global variable
189            js["myGlobal"] = "global variable"
190
191            // And I retrieve such global variable via the `execute` method
192            val globalVariableValue = js.execute { "return window.myGlobal;" }
193
194            // Then I should get the variable's value as is
195            assertEquals(globalVariableValue, "global variable")
196        }
197    }
198
199    @Test(description = "Set a global JS variable and retrieve it via a get",
200        dataProvider = "JavaScript-enabled WebDriver factory")
201    fun set_a_global_js_variable_and_retrieve_it_via_a_get(driverFactory: () -> WebDriver) {
202        Browser.drive(driverFactory = driverFactory) {
203            // When I navigate to the Kotlin's page URL
204            to("https://kotlinlang.org/")
205
206            // And I set a global variable
207            js["myGlobal"] = "super global variable"
208
209            // And I retrieve such global variable via a `get` call
210            val globalVariableValue = js["myGlobal"]
211
212            // Then I should get the variable's value as is
213            assertEquals(globalVariableValue, "super global variable")
214        }
215    }
216
217    @Test(description = "Execute an asynchronous JavaScript code",
218        dataProvider = "JavaScript-enabled WebDriver factory")
219    fun execute_an_asynchronous_javascript_code(driverFactory: () -> WebDriver) {
220        // Given I create a 100-elements array to be passed as arguments to the script
221        val arguments = Array(100) { it }
222
223        Browser.drive(driverFactory = driverFactory) {
224            // When I navigate to the Kotlin's page URL
225            to("https://kotlinlang.org/")
226
227            // And I execute an asynchronous JS code to get how many arguments I passed to it
228            val argumentsLength = js(*arguments, async = true) {
229                """
230                    var argumentsLength = arguments.length - 1;
231
232                    var callback = arguments[arguments.length - 1];
233
234                    window.setTimeout(function() { callback(argumentsLength); }, 500);
235                """
236            }
237
238            // Then I should get the expected length
239            assertEquals(argumentsLength, 100L)
240        }
241    }
242}
243/* ***************************************************************************/
244
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