Search code examples
swiftxcodeunit-testingui-testing

UI Test to check if an item exists is not working in Swift


I've looked through a dozen of different tutorials, articles etc., but nothing seems to be working for me. I'm attaching the code of an easy UI test in Swift to see if a section of a drawer exists. Any ideas why my test fails (not because I found a bug, but because my UI test is written incorrectly)? Thanks!

import XCTest
var app: XCUIApplication!


class MyAppUITests: XCTestCase {

    override func setUp() {
        super.setUp()
        continueAfterFailure = false
        app = XCUIApplication()
        app.launchArguments.append("--uitesting")
        app.launch()
    }

    func testDrawerDisplaysPrivacyAgreement() {   app.navigationBars["MyApp.MainView"].buttons["burgerButton"].tap()

        XCTAssertTrue(app.tables.staticTexts["Privacy Policy"].exists)


    }

    override func tearDown() {
        super.tearDown()
    }
}

Solution

  • I solved my problem.

    What I've done:

    • I deleted the old version of MyAppUITests.
    • From now on I add let app = XCUIApplication(); app.launch() every time I create a test.

    The test below passes successfully! That works perfectly for me. :)

    import XCTest
    var app: XCUIApplication!
    
    
    class MyAppUITests: XCTestCase {
    
        override func setUp() {
            super.setUp()
            continueAfterFailure = false
        // Delete these. Doesn't work if put here and not in each test
        //    app = XCUIApplication()
        //    app.launchArguments.append("--uitesting")
        //    app.launch()
        }
    
        func testDrawerDisplaysPrivacyAgreement() {   
    //  ** These two should be written in each test 
    // **
            let app = XCUIApplication()
            app.launch()
    // **
    
           let burgerButtonMenu =         app.navigationBars["MyApp.MainView"].buttons["burgerButton"]
            burgerButtonMenu.tap()
            let privacy = app.tables.staticTexts["Privacy Policy"]
    
            if  burgerButtonMenu.isEnabled && burgerButtonMenu.isSelected {
                XCTAssertTrue(privacy.exists)
    
    
        }
    
        override func tearDown() {
            super.tearDown()
        }
    }