Wrong cells count for collection view in UI Tests

I have found the solution, but it's a workaround for wrong API behavior. Collection view is caching cells, that's probably why I have 3 cells, even if I have removed one. Deleted cell is offscreen, so you can test if it is hittable:

XCTAssertFalse(app.cells.staticTexts["Item"].hittable)

To find a count, I have created extension:

extension XCUIElementQuery {
    var countForHittables: UInt {
        return UInt(allElementsBoundByIndex.filter { $0.hittable }.count)
    }
}

and my test looks like this:

func testDeleteItem() {
    app.collectionViews.staticTexts["Item"].tap()
    app.buttons["Delete"].tap()

    XCTAssertEqual(app.collectionViews.cells.countForHittables, 2)
    XCTAssertFalse(app.collectionViews.cells.staticTexts["Item"].hittable)
}

I also came across this issue, but in my case, .cells query wasn't evaluating correctly. Instead of .cells, using

XCUIApplication().collectionViews.element.childrenMatchingType(.Cell).count

worked for me and returned the correct count.


Update:

I also found that scrolling the view so that all the cells are dequeued before getting the count fixed the issue. It seems the accessibility framework does not find the other cells until they have been dequeued (I guess that makes sense).

XCUIApplication().collectionViews.element.swipeUp()