如何使用 expectationForPredicate 并点击一个按钮

how to use expectationForPredicate and tap a button

如何在检查按钮是否启用后点击按钮?

我在这里找到了这个样本,但它对我的情况不起作用。

这里是部分代码:

    let app = XCUIApplication()
    let button = app.buttons["Tap me"]
    let exists = NSPredicate(format: "exists == 1")
    expectationForPredicate(exists, evaluatedWithObject: button){
        button.tap()
        return true
    }
 waitForExpectationsWithTimeout(5, handler: nil)

但是我的测试通过点击按钮失败了。 谢谢

您的代码示例不检查按钮是否启用,仅检查它是否存在。

如果按钮存在,您传递给 expectationForPredicate 的块将被执行,因此即使按钮被禁用,按钮也会被点击。

要检查启用的按钮:

let app = XCUIApplication()
let button = app.buttons["Tap me"]
let exists = NSPredicate(format: "exists == 1")
expectationForPredicate(exists, evaluatedWithObject: button) {
    // If the button exists, also check that it is enabled
    if button.enabled {
        button.tap()
        return true
    } else {
        // Do not fulfill the expectation since the button is not enabled
        return false
    }
}
waitForExpectationsWithTimeout(5, handler: nil)