Espresso Example

Link to Espresso Example copied to clipboard

Below is an example of getting started with axe DevTools testing with Espresso.

For XML Layouts

class ExampleInstrumentedTestWithAccessibility : Utils {

    @Rule
    @JvmField
    var rule: ActivityScenarioRule<MainActivity> = ActivityScenarioRule(MainActivity::class.java)

    private val axe = AxeDevTools()

    init {
        //Connect using an API Key
        axe.connect(
            "<API_KEY>",
            ConnectionConfig.DEFAULT_CONNECTION_CONFIG
        )
    }

    @Before
    fun setup() {
        axe.tagScanAs(setOf("YourTag"))
        axe.setTestingConfig(AxeDevToolsEspressoConfig(IdlingRegistry.getInstance()))
    }

    @Test
    fun exampleTest() {
        onView(withText("Your View Name")).perform(click())
        onView(withText("Button")).perform(click())
        onView(withContentDescription("Content Description")).perform(click())
    }

    @After
    fun runAccessibilityScan() {
        rule.scenario.onActivity {
            val scan = axe.scan(it)
            scan?.uploadToDashboard()
            axe.tearDown()
        }
    }
}

For Compose Layouts

@ExperimentalComposeUiApi
class ExampleComposeTest {
    @get:Rule
    val composeTestRule = createAndroidComposeRule<TestComposeActivity>()

    private val axe = AxeDevToolsCompose()

    init {
        // Connect using an API key 
        axe.connect(
            "<API_KEY>",
            ConnectionConfig.DEFAULT_CONNECTION_CONFIG
        )
    }

    @Before
    fun setup() {
        composeTestRule.setContent { YourComposableFunction() }
        composeTestRule.mainClock.autoAdvance = false
        composeTestRule.waitForIdle()

        axe.tagScanAs(setOf("YourTag"))
    }

    @Test
    fun foobar() {
        // Must be set in the tests itself
        axe.setComposeTestRule(composeTestRule)
        val scan = axe.scan()
        scan?.uploadToDashboard()
        axe.tearDown()
    }
}