Has anyone successfully implemented the Page Object pattern in their UI tests? I gave it a try and ran into an issue. When I use the predicate to wait for the element to exist, I get a warning in the log. Here's a code snippet from the Page Object class:
XCUIElement *myCoolButton = self.app.buttons[@"Super Cool Button"];
[self expectationForPredicate:self.existsPredicate evaluatedWithObject:myCoolButton handler:nil];
[self waitForExpectationsWithTimeout:5.0f handler:nil];
When this code executes, I see the following in the log:
Questionable API usage: creating XCTestExpectation for test case -[MyPageObject (null)] which is not the currently running test case -[MyTestCase test]
and when the timeout is exceeded, I see the error in the log but the test itself doesn't actually fail. I'm assuming that this is because the predicate is set up in the Page Object class, not the test itself. Has anyone been able to work around this?
From the question, I assume waitForExpection is written in the Page Objects class.
Generally Page Objects are not inherited from XCTestCase since they are used only to hold references of all the UI Elements possibly in a page.Hence they cannot have assert actions(waitForExpectation in this case)
If what you are trying is to write a re-usable function which can have assertions like waitForExpectation in the PageObject class then you need to pass the test case as a parameter to the function(Your function should accept a test case)
For this case ,I would suggest you to write a category(extension in swift) on XCTestCase with XCUIElement as an input param which waitsForTheElementToExist instead of writing in the pageobject class.You can avoid replicating the same code in all page objects.
Sample code here
class LoginPageObect {
let userNameTextField = XCUIApplication().textFields["UserName"]
let passwordTextField = XCUIApplication().textFields["Password"]
func loginUser(testcase: XCTestCase) {
testcase.waitForElementToAppear(userNameTextField)
testcase.waitForElementToAppear(passwordTextField)
//Do rest of things here
}
}
extension XCTestCase {
func waitForElementToAppear(element: XCUIElement) {
let existsPredicate = NSPredicate(format: "exists == true")
expectationForPredicate(existsPredicate,
evaluatedWithObject: element, handler: nil)
waitForExpectationsWithTimeout(5, handler: nil)
}
}