How to test for view disappear in navigation controller

Issue #670

To test for viewWillDisappear during UINavigationController popViewController in unit test, we need to simulate UIWindow so view appearance works.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
final class PopTests: XCTestCase {
func testPop() {
let window = UIWindow(frame: UIScreen.main.bounds)
let navigationController = UINavigationController()
window.rootViewController = navigationController
let viewController = DetailViewController()

navigationController.viewControllers = [
UIViewController(),
viewController
]

window.makeKeyAndVisible()
let expectation = XCTestExpectation()
navigationController.popViewController(animated: false)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
XCTAssertTrue(viewController.wasDismissed)
expectation.fulfill()
}
wait(for: [expectation], timeout: 1)
}
}
1
2
3
4
5
6
7
8
class DetailViewController: UIViewController {
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if isMovingFromParent {
wasDismissed = true
}
}
}

Comments