XCUITest ios 12 switch element value, is on?

Viewed 620

I've come across a weird issue with swift xcuitest regarding switches in my tests. I'm testing settings app, to check if certain switches are on. I'm fairly new to swift but from resources I've read I've found I should do something like the following:

let mySwitch = settingsApp.switches["Block Pop-ups"]
XCTAssert(mySwitch.exists)
let isOn = (mySwitch.value as? String).map { $0 == "1" }
XCTAssert(isOn == true)

However when testing for simulators on ios 12, I've found the value for the switch always seems to have nil value whether is on or off e.g. both assertions below are false

XCTAssertFalse(isOn == true)
XCTAssertFalse(isOn == false)

I found this on apple forums but there is no answer posted. Does anyone have a fix or workaround for this?

I'm using swift 5.1, and xcode 11

Edit: need a solution for iOS 12, I am not in a position to upgrade to 13

2 Answers

If updating version is not an option you can use some workaround - e.g. checking the color instead of the value. Here is an example test case that uses SUITCase (https://github.com/devexperts/suitcase)

import XCTest
import SUITCase

let app = XCUIApplication(bundleIdentifier: "com.apple.Preferences")

class Tests: XCTestCase {

    let mapsCell = app.cells["Maps"]
    let someSwitch = app.switches["Background App Refresh"]

    override func setUp() {
        app.launch()
    }

    func testSwitch() {
        let green = #colorLiteral(red: 0.737254902, green: 0.9411764706, blue: 0.7725490196, alpha: 1)
        let gray = #colorLiteral(red: 0.968627451, green: 0.968627451, blue: 0.968627451, alpha: 1)
        mapsCell.tap()
        if someSwitch.averageColorIs(green) {
            someSwitch.tap()
        }
        XCTAssert(someSwitch.averageColorIs(gray))
        someSwitch.tap()
        XCTAssert(someSwitch.averageColorIs(green))
    }
}

Color Literals look nice in Xcode: enter image description here

This test code runs fine on Xcode 11.5 @ iOS 13.5. Seems like updating to the newest versions fixes the issue.

import XCTest
import XCTApps

let app = XCTApps.settings.app

class Tests: XCTestCase {

    let developerCell = app.cells["Developer"]
    let someSwitch = app.switches["Dark Appearance"]

    override func setUp() {
        app.launch()
    }

    func testSwitch() {
        developerCell.tap()
        let switchState1 = someSwitch.value as! String
        someSwitch.tap()
        let switchState2 = someSwitch.value as! String
        XCTAssertEqual([switchState1, switchState2].sorted(), ["0", "1"])
    }
}
Related