btw, the view model is meant to set the state base...
# orbit-mvi
r
btw, the view model is meant to set the state based on what it finds in shared prefs, I haven’t written that logic yet as I wanted to write the test first.
So I can’t work out how to test the initial state is correct so I am passing a “dummy” initial state that I can ignore and then use the create method to do the real work to test the state. Here’s my logic and the test.
Copy code
class AnalyticsConsentViewModel(val prefs: Preferences) : ViewModel(),
    ContainerHost<AnalyticsConsentState, NavigationEvent> {
    override val container: Container<AnalyticsConsentState, NavigationEvent> =
        container(AnalyticsConsentState()) {
            getInitialState()
        }

    private fun getInitialState() = intent {
        val hasAnalyticsConsentGiven = prefs.hasAnalyticsConsentGiven()
        if (hasAnalyticsConsentGiven == null || hasAnalyticsConsentGiven) {
            reduce {
                state.copy(consentGivenChecked = true)
            }
        } else {
            reduce {
                state.copy(consentGivenChecked = false)
            }
        }
    }
}

data class AnalyticsConsentState(
    val consentGivenChecked: Boolean? = null
)
and the tests
Copy code
@Test
    fun `nothing in shared prefs so asking during registration`() = runTest {
        // given
        val initialState = AnalyticsConsentState()
        every { prefs.hasAnalyticsConsentGiven() } returns null
        val viewModel = AnalyticsConsentViewModel(prefs).test(initialState)

        // when
        viewModel.runOnCreate()

        // then
        viewModel.assert(initialState) {
            states(
                { copy(consentGivenChecked = true) }
            )
        }
    }

    @Test
    fun `analytics consent given`() = runTest {
        // given
        val initialState = AnalyticsConsentState()
        every { prefs.hasAnalyticsConsentGiven() } returns true
        val viewModel = AnalyticsConsentViewModel(prefs).test(initialState)

        // when
        viewModel.runOnCreate()

        // then
        viewModel.assert(initialState) {
            states(
                { copy(consentGivenChecked = true) }
            )
        }
    }

    @Test
    fun `analytics consent denied`() = runTest {
        // given
        val initialState = AnalyticsConsentState()
        every { prefs.hasAnalyticsConsentGiven() } returns false
        val viewModel = AnalyticsConsentViewModel(prefs).test(initialState)

        // when
        viewModel.runOnCreate()

        // then
        viewModel.assert(initialState) {
            states(
                { copy(consentGivenChecked = false) }
            )
        }
    }