如何在Xcode的UI测试中检查网络中是否存在静态文本?

时间:2015-07-07 06:27:56

标签: ios swift xctest xcode7 xcode-ui-testing

我正在使用Xcode 7 XCTest中引入的UI测试API。在我的屏幕上,我有一个从网络加载的文本。

如果我只是使用exists属性进行检查,则测试失败。

XCTAssert(app.staticTexts["Text from the network"].exists) // fails

如果我首先将点击或任何其他事件发送到文本,它确实有效:

app.staticTexts["Text from the network"].tap()
XCTAssert(app.staticTexts["Text from the network"].exists) // works

如果我只是调用exists,它会立即对其进行评估并失败,因为尚未从网络下载文本。但我认为当我调用tap()方法时,它会等待文本出现。

有没有更好的方法来检查是否存在从网络传送的文本?

类似的东西(这段代码不起作用):

XCTAssert(app.staticTexts["Text from the network"].eventuallyExists)

3 个答案:

答案 0 :(得分:1)

XCode9的方法waitForExistence(timeout: TimeInterval)XCUIElement

extension XCUIElement {
    // A method for tap element
    @discardableResult
    func waitAndTap() -> Bool {
        let _ = self.waitForExistence(timeout: 10)
        let b = self.exists && self.isHittable
        if (b) {
            self.tap()
        }
        return b
    }
}

// Ex:
if (btnConfig.waitAndTap() == true) {
    // Continue UI automation
} else {
    // `btnConfig` is not exist or not hittable.
}

但是我遇到另一个问题,element存在,但不是可命中的。所以我扩展了一个等待元素可以命中的方法。

extension XCTestCase {
    /// Wait for XCUIElement is hittable.
    func waitHittable(element: XCUIElement, timeout: TimeInterval = 30) {
        let predicate = NSPredicate(format: "isHittable == 1")
        expectation(for: predicate, evaluatedWith: element, handler: nil)
        waitForExpectations(timeout: timeout, handler: nil)
    }
}

// Ex:
// waitHittable(element: btnConfig)

答案 1 :(得分:0)

如果我正确地了解您在检查目标文本时已经显示目标文本,则可以尝试使用hittable属性。

答案 2 :(得分:0)

斯威夫特3:

let predicate = NSPredicate(format: "exists == 1")
let query = app!.staticTexts["identifier"]
expectation(for: predicate, evaluatedWith: query, handler: nil)
waitForExpectations(timeout: 5, handler: nil)

它将持续检查是否显示该文本5秒。

一旦发现文本可能在不到5秒的时间内,它就会执行更多代码。