我正在使用Xcode 7 XCTest中引入的UI测试API。在我的屏幕上,我有一个从网络加载的文本。
如果我只是用exists
属性检查它,测试就会失败。
XCTAssert(app.staticTexts["Text from the network"].exists) // fails
如果我首先将tap或任何其他事件发送到文本,它确实有效:
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。
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)
如果我正确地了解您在检查目标文本时是否已显示目标文本,则可以尝试使用hittable
属性。
斯威夫特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秒的时间内,它就会执行更多代码。