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

How to check for the presence of static text displayed from the network in UI tests in Xcode?

我正在使用 UI 7 XCTest 中引入的测试 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)

Xcode 7 Beta 4 添加了对异步事件的原生支持。这是一个如何等待 UILabel 出现的简单示例。

XCUIElement *label = self.app.staticTexts[@"Hello, world!"];
NSPredicate *exists = [NSPredicate predicateWithFormat:@"exists == 1"];

[self expectationForPredicate:exists evaluatedWithObject:label handler:nil];
[self waitForExpectationsWithTimeout:5 handler:nil];

首先创建一个查询以等待带有文本 "Hello, world!" 的标签出现。当元素存在 (element.exists == YES) 时谓词匹配。然后传入谓词并根据标签对其进行评估。

如果在达到预期之前过了五秒,则测试将失败。您还可以附加一个处理程序块,在预期失败或超时时调用该处理程序块。

如果您正在寻找有关 UI 一般测试的更多信息,请查看 UI Testing in Xcode 7

如果我的理解是正确的,当你检查目标文本是否存在时,目标文本已经显示,你可以尝试使用 hittable 属性.

Swift 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 秒,它就会执行进一步的代码。

XCode9 有一个方法 waitForExistence(timeout: TimeInterval) of 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)