Search code examples
swiftxcodeswift3uicollectionviewcellxcode-ui-testing

How to tap on a button inside a CollectionView cell which is not visible on screen


I am working on UITests using XCode. I have multiple CollectionView cells. When I perform Count in the collectionView it shows the certain count. I can able to access first two cells but coming to the 3rd cell as 3(depends on device size). It says that specific button I am looking for in 3rd Cell as exists.

But isHittable is false.

Is there any way I can tap on the button on the 3rd Cell. I have tried using the extension for forceTapElement() which is available online, it didn’t help.

Extension Used:

extension XCUIElement{
    func forceTapElement(){
        if self.isHittable{
            self.tap()
        }else{
            let coordinate: XCUICoordinate = self.coordinate(withNormalizedOffset: .zero)
            coordinate.tap()
        }
    }
}

Tried to perform swipeUp() and access the button. it still shows isHittable as false


Solution

  • The only way I've found is to swipe up untile the isHittable will be true.

    app.collectionViews.cells.staticTexts["TEST"].tap()
    Thread.sleep(forTimeInterval: 3)
    
    let collectionView = app.otherElements.collectionViews.element(boundBy: 0)
    let testAds = collectionView.cells
    let numberOfTestAds = testAds.count
    if numberOfTestAds > 0 {
        let tester = collectionView.cells.element(boundBy: 2).buttons["ABC"]
        for _ in 0..<100 {
            guard !tester.isHittable else {
                break;
            }
            collectionView.swipeUp()
        }
    }
    

    Please note that the swipeUp() method will only move few pixels. If you want to use more comprehensive methods you can get AutoMate library and try swipe(to:untilVisible:times:avoid:from:):

    app.collectionViews.cells.staticTexts["TEST"].tap()
    Thread.sleep(forTimeInterval: 3)
    
    let collectionView = app.otherElements.collectionViews.element(boundBy: 0)
    let testAds = collectionView.cells
    let numberOfTestAds = testAds.count
    if numberOfTestAds > 0 {
        let tester = collectionView.cells.element(boundBy: 2).buttons["ABC"]
        collectionView.swipe(to: .down, untilVisible: tester)
        // or swipe max 100 times in case 10 times is not enough
        // collectionView.swipe(to: .down, untilVisible: tester, times: 100)
    }