How to test to get all value of StateFlow in Coroutine?

39 Views Asked by At

Test Result is always received first value(=init) and last value(=success) How to get LoaderType State (Fail Case)

Without the delay() function, the test case consistently fails, and only the initial state and success state are obtained. How can the test case be successful without the delay()?

fun getExhibitions(loaderType: LoaderType) {
    viewModelScope.launch {
        state.update { it.loading(loaderType) } // #1 Change State (to Loading)

        val result = useCase.getExhibitions(
            params = GetExhibitionsUseCase.Params(shopId, sellerId)
        )

        when (result) {
            is UseCaseResult.Success -> {
                val displayModel = mapper.mapExhibitionList(result.value)
                state.update { it.loadingSuccess(displayModel.exhibitions) } // #2 Change State (to Success)
            }
            is UseCaseResult.Fail -> {
                onErrorGetExhibitions(result.throwable)
            }
        }
    }
}
@Test
fun load_success() = runTest {

    // given
    prepareViewModel_success()

    viewModel.uiState.test {

        // init
        assert((awaitItem() as UiState.Loading).loaderType == QCommerceLoaderType.NONE)

        // when
        viewModel.getExhibitions(loaderTyp = LoaderType.TEXT)

        // then
        assert((awaitItem() as UiState.Loading).loaderType == QCommerceLoaderType.TEXT) // Fail Case
        assert((awaitItem() as UiState.Success).exhibitions.isNotEmpty())
    }

}

Below cases are Passes

fun getExhibitions(loaderType: LoaderType) {
    viewModelScope.launch {
        state.update { it.loading(loaderType) } // #1 Change State (to Loading)

        delay(500) // Add this code

        val result = useCase.getExhibitions(
            params = GetExhibitionsUseCase.Params(shopId, sellerId)
        )

        when (result) {
            is UseCaseResult.Success -> {
                val displayModel = mapper.mapExhibitionList(result.value)
                state.update { it.loadingSuccess(displayModel.exhibitions) } // #2 Change State (to Success)
            }
            is UseCaseResult.Fail -> {
                onErrorGetExhibitions(result.throwable)
            }
        }
    }
}
fun getExhibitions(loaderType: LoaderType) {
    state.update { it.loading(loaderType) } // Edit Location
    viewModelScope.launch {
        val result = useCase.getExhibitions(
            params = GetExhibitionsUseCase.Params(shopId, sellerId)
        )

        when (result) {
            is UseCaseResult.Success -> {
                val displayModel = mapper.mapExhibitionList(result.value)
                state.update { it.loadingSuccess(displayModel.exhibitions) } // #2 Change State (to Success)
            }
            is UseCaseResult.Fail -> {
                onErrorGetExhibitions(result.throwable)
            }
        }
    }
}
0

There are 0 best solutions below