Search code examples
swiftxctestxcode-ui-testing

how to perform multi-select with perform(withKeyModifier:block:) function in XCUITest


I want to multiple-select some element on the webview, therefore I would need to use perform(withKeyModifer:block:) function of XCUIElement, can any one give an example on how to use this function? I'm new to swift so please elaborate the code, thanks in advance!


Solution

  • You use the method to perform some code while a modifier key is down. You specify the modifier key and pass in a block of code to execute while the key modifier is down. You can use trailing closure syntax for this like so:

    let app = XCUIApplication()
    
    // elements you want to select
    let element1 = app.cells.element(boundBy: 0)
    let element2 = app.cells.element(boundBy: 1)
    let elementsToSelect = [element1, element2]
    
    XCUIElement.perform(withKeyModifiers: XCUIElement.KeyModifierFlags.command) {
        // code in this block executes while the command key is down
        // select each element
        elementsToSelect.forEach({ $0.tap() })
    }
    

    If you are testing a desktop app, you should use click() instead of tap().

    Use whichever modifier key you need from the list here: https://developer.apple.com/documentation/xctest/xcuielement.keymodifierflags