Open jfontsaballs opened 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)
With runReactTest
less code will be required
Probably, having wrappers for the DOM Testing Library as well would be a good complement to the React Testing Library.
@jfontsaballs see https://github.com/robertfmurdock/jsmints#react-testing-library
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
Enzyme
: the library seems to be dead and not compatible with current React versions.kotlin-react-dom-test-utils
: in its own documentation it recommends the use of the React Testing Library due to better developer ergonomics.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.