Hello, is there a way to test shared ViewModels in...
# multiplatform
c
Hello, is there a way to test shared ViewModels in a Compose Multiplatform app? I couldn’t figure it out, and I only saw UI tests or pure business logic unit tests in the example apps listed on the jetbrains website.
I got it running I was missing the
Copy code
Dispatchers.setMain(UnconfinedTestDispatcher())
k
@Carmen How are you defining your view models? Ideally you would want to inject the dispatcher as a parameter and you can use
StandardTestDispatcher
in your tests. If you're targeting android & ios there isn't an ideal way to do integration testing i.e tests that run on the device. But there is a tricky way to do it using mokkery.
c
I use viewModelScope to launch a coroutine in my ViewModel. ViewModelScope is using a hardcoded Main dispatcher under the hood, I can't replace it in my ViewModel code, therefore I need to use the Dispatcher.setMain method to in my UnitTest to replace it.
k
oh. You can do it like this
Copy code
class MyViewModel(val dispatcher: CoroutineDispatcher) : ViewModel() {
     fun someFunction() {
        viewmodelScope.launch(dispatcher) { ... } 
    }
}
and in your test
Copy code
class MyViewModelTest { 
    val testDispatcher = StandardTestDispatcher() 

    val myViewModel = MyViewModel(testDispatcher)

    @Test
    fun `my viewmodel test`() = runTest { 
       myViewModel.someFunction()
       testDispatcher.scheduler.advanceUntilIdle()
       // verify the function call
    } 
}
c
Interesting the Android Documentation about testing coroutines says viewModelScope uses a hardcoded Main Dispatcher under the hood. https://developer.android.com/kotlin/coroutines/test#setting-main-dispatcher