Types created by Selenium do not match browser types

Viewed 31

I am testing a javascript function that, inside its body, performs a check if a provided object is an Array. Let's simplify it to this:

function isArray(obj) { return obj instanceof Array; }

Then, I call this function from a selenium web driver:

assert driver.execute_script("return isArray([1, 2, 3]);") == True

but the result of calling isArray is false even though the type of the object is Array. After some investigation I found that selenium runs scripts having a Sandbox object as globalThis, thus the prototype of the array input is Sandbox.Array which appears to be not the same object as window.Array, so the instanceof check fails.

Is there any workaround for this? It's not just the Array but every global type is affected. I use selenium to test javascript code and it's important to me that functions under test recognise objects created by selenium. Could it be possible to configure the driver to use the window as the global object? I couldn't find it in the selenium documentation but tbh. their documentation at selenium.dev seems to be very lacking.

Edit - example code:

here is a dummy javascript function in my application that I want to test using selenium:

<!doctype html>
<html>
  <body>
    <script>
      function isArray(obj) {
        console.log("instanceof Array:", obj instanceof Array);
        return obj instanceof Array;
      }
    </script>
  </body>
</html>

In a python script, I open the website above and execute the isArray method providing it with an array.

from selenium.webdriver import Firefox

driver = Firefox()
driver.get("http://localhost:8000/index.html")

assert driver.execute_script("return isArray([1, 2, 3]);")
# AssertionError

The assertion fails because arrays created from within selenium do not have window.Array as a prototype. Instantiating window.Array explicitly works.

assert driver.execute_script("return isArray(window.Array(1, 2, 3));")
# success
0 Answers
Related