Found a bizarre issue where a ClassCastException i...
# javascript
n
Found a bizarre issue where a ClassCastException is thrown when accessing the first element from a List:
Copy code
● org.webscene.core.test.dom › DomQueryTest › testFetchExistingPageId

    ClassCastException: Illegal cast

      36 |             element.hasAttribute("pageId")
      37 |         }
    > 38 |         return if (metaElements.isNotEmpty()) metaElements.first().getAttribute("pageId") ?: "" else ""
         |                                                            ^
r
is metaElements really a list? or is it a JavaScript Array (just a wild guess)
n
It's a Kotlin List of org.w3c.dom.Element.
r
Well then, I would debug and see why it fails
n
Did some some debugging and wasn't able to find out why the issue occurs. Would be very helpful to have someone look and see if they spot anything I haven't spotted (https://gitlab.com/webscene/webscene-core/tree/testing). All that a person needs to do is clone the project and run the tests from the project directory (./gradlew jstest). There is a single test that fails called testFetchExistingPageId.
Would have thought the casting would fail after the asList function (part of Kotlin JS standard library) call but the issue doesn't occur there:
Copy code
internal fun Document.findAllElementsByTagName(tagName: String): List<Element> =
    document.getElementsByTagName(tagName).asList()
The asList function doesn't guarantee safe casting:
Copy code
public fun <T> ItemArrayLike<T>.asList(): List<T> = object : AbstractList<T>() {
    override val size: Int get() = this@asList.length

    override fun get(index: Int): T = when (index) {
        in 0..lastIndex -> this@asList.item(index).unsafeCast<T>()
        else -> throw IndexOutOfBoundsException("index $index is not in range [0..$lastIndex]")
    }
}
I did some checks just in case.