Search code examples
push-notificationtogglesettingsxctestxcuitest

XCTest how to toggle Notification Switch in OS Settings?


I'm trying to Enable / Disable the OS Notification Switch for the app I'm testing and I'm unable to. I get as far as the Settings > Notifications > App screen itself but the switch doesn't seem to have a button I can interact with.

This is how far I get:

let settingsApp = XCUIApplication(bundleIdentifier: "com.apple.Preferences")
        settingsApp.launch()
        
settingsApp.tables.cells.staticTexts["Notifications"].tap()
settingsApp.tables.cells.staticTexts["app_name"].tap()

So far so good but here the button list is returned like this:

Failed to get matching snapshot: No matches found for Element at index 7 from input {(
    Button,
    Button, identifier: 'Lock Screen', Selected,
    Button, identifier: 'Notification Center',
    Button, identifier: 'Banners',
    Button, Disabled,
    Button, Disabled
)}

I've tried settingsApp.buttons.element(boundBy: 0).tap() but that ends up being the back button and boundBy: 1 ends up being the 'Lock Screen' button.

Is the 'Allow Notifications' toggle un-tappable? :)


Solution

  • Allow Notifications is a switch, which will respond to tap(). The following should do the trick:

    settingsApp.tables.cells.switches["Allow Notifications"].tap()
    

    I typically wrap switch tapping in a toggle function, which takes an expected state and only taps if it's not already in that state.