JetBrains / kotlin-wrappers

Kotlin wrappers for popular JavaScript libraries
Apache License 2.0
1.35k stars 161 forks source link

Request for wrappers for React Testing Library #2230

Open jfontsaballs opened 7 months ago

jfontsaballs commented 7 months ago

Is your feature request related to a problem? Please describe. I have a React app developed in Kotlin using kotlin-wrappers. I've started to have some React components with complicated logic and I would like to unit test them.

Describe the solution you'd like I would like wrappers for React Testing Library. It seems to be the recommended approach to test React components.

Describe alternatives you've considered

Additional context

67 #325 #344

react.dev docs contain little to no information on testing.


Additionally, I would greatly appreciate any suggestion or example on how to proceed with testing using what is available right now.

jfontsaballs commented 7 months ago

I was able to render a React component inside a unit test. I leave here my code in case it may be useful to someone:

import assertk.assertThat
import assertk.assertions.isEqualTo
import assertk.assertions.isNotNull
import react.dom.html.ReactHTML.div
import web.dom.document
import kotlin.test.Test

private const val MY_TEST_DIV = "myTestDiv"

private val myTestComponent by VComponent {
    div {
        id = MY_TEST_DIV
        +"Hello test!"
    }
}

class ReactComponentTests {
    @Test
    fun tryingToTestAReactComponent() = testReact(myTestComponent) {
        val myDiv = document.getElementById(MY_TEST_DIV)
        assertThat(myDiv).isNotNull()
        assertThat(myDiv?.innerText).isEqualTo("Hello test!")
    }
}

private var initialized = false

fun testReact(reactNode: ReactNode, test: () -> Unit) = runTest {
    if (!initialized){
        js("globalThis.IS_REACT_ACT_ENVIRONMENT = true;")
        initialized = true
    }

    val root = document.createElement("div")
    root.id = "root"
    document.body.appendChild(root)
    act { createRoot(root).render(reactNode) }
    try {
        test()
    } finally {
        document.body.removeChild(root)
    }
}

fun testReact(component: FC<Props>, test: () -> Unit) = testReact(component.create(), test)
turansky commented 7 months ago

With runReactTest less code will be required

jfontsaballs commented 7 months ago

Probably, having wrappers for the DOM Testing Library as well would be a good complement to the React Testing Library.

lppedd commented 7 months ago

@jfontsaballs see https://github.com/robertfmurdock/jsmints#react-testing-library