google-developer-training / basic-android-kotlin-compose-training-tip-calculator

Apache License 2.0
61 stars 93 forks source link

java.lang.AssertionError: No node with this text was found. Reason: Expected exactly '1' node but could not find any node that satisfies: (Text + EditableText contains 'Tip Amount: $2.00' (ignoreCase: false)) #183

Open PrashantBajracharya opened 6 months ago

PrashantBajracharya commented 6 months ago

There is small error in instrument testing where composeTestRule.onNodeWithText("Bill Amount") .performTextInput("10") makes the input 100 because there is a initial value of 0 in the Bill amount text field so the test fails.

To fix this issue we need to first clear the bill amount text field.

package com.example.tiptime

import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performTextClearance
import androidx.compose.ui.test.performTextInput
import com.example.tiptime.ui.theme.TipTimeTheme
import org.junit.Rule
import org.junit.Test
import java.text.NumberFormat

class TipUITests {

    @get:Rule
    val composeTestRule = createComposeRule()

    @Test
    fun calculate_20_percent_tip() {
        composeTestRule.setContent {
            TipTimeTheme {
                Surface (modifier = Modifier.fillMaxSize()){
                    TipTimeLayout()
                }
            }
        }

        composeTestRule.onNodeWithText("Bill Amount")
            .performTextClearance()/*This line is required to clear input otherwise the input will be 100 instead of 10.*/
        composeTestRule.onNodeWithText("Bill Amount")
            .performTextInput("10")

        composeTestRule.onNodeWithText("Tip Percentage")
            .performTextInput("20")

        val expectedTip = NumberFormat.getCurrencyInstance().format(2)
        println(expectedTip)

        composeTestRule.onNodeWithText("Tip Amount: $expectedTip")
            .assertExists(
            "No node with this text was found."
        )
    }
}