AstFreelancer
AstFreelancer

Reputation: 17

createComposeRule() for another file while testing Compose Multiplatform UI

I have a desktop app. Its source code is a lot of composable functions in separate *.kt files, for example

@Composable
fun MyView()
    ...

And now I have to write an UI test for these functions in another file.

@OptIn(ExperimentalTestApi::class)
@get:Rule
val rule = createComposeRule(???)

I found an example for Android app UI testing:

class ExampleInstrumentedTest {
    @get:Rule
    val composeTestRule = createAndroidTestRule(MainActivity::class.java)          

But in my desktop Compose Multiplatform app I have no activities. How can I use MyView() function while creating a compose test rule in this case?

Upvotes: 1

Views: 448

Answers (1)

Trent Meyer
Trent Meyer

Reputation: 375

createComposeRule doesn't take any parameters, is a factory function.

There's a good document for how to use this function and compose tests in general.

Create the rule

@get:Rule val composeTestRule = createComposeRule()

(In a test) Apply your content to the rule

composeTestRule.setContent {
    MainScreen(uiState = fakeUiState, /*...*/)
}

Test the visibility of some node

composeTestRule.onNodeWithText("Welcome").assertIsDisplayed()

Edit

If the above doesn't work with compose for desktop I recommend looking into the JetBrains test library.

@OptIn(ExperimentalTestApi::class)
@Test
fun myTest() = runComposeUiTest {
    setContent { MainScreen(uiState = fakeUiState, /*...*/) }
    onNodeWithTag("text").assertTextEquals("Compose")
}

Upvotes: 2

Related Questions