Make XCUIElement perform 3D touch for Automate UITest?
Asked Answered
C

2

10

I'm creating Automate UITest test case where I'd like to test the scenario when users make 3D Touch interaction with an element, then shows them Peek and Pop view.

I can't seem to find any possible ways to simulate 3D Touch on an element and continue.

Anyone has any idea about this, or 3D Touch is still unavailable to test?

Thanks

Christly answered 2/9, 2016 at 3:58 Comment(0)
C
5

I was able to execute a force press / 3D Touch on an app icon on an iPhone 7 running iOS 10.3. It was not possible on 10.2.

Objective-C

First you have to declare the following or import this header

typedef void (^CDUnknownBlockType)(void);

@interface XCEventGenerator : NSObject

+ (id)sharedGenerator;

// iOS 10.3 specific
- (double)forcePressAtPoint:(struct CGPoint)arg1 orientation:(long long)arg2 handler:(CDUnknownBlockType)arg3;

@end

And then execute the force press

XCUIElement *element = ...; // Get your element
XCUICoordinate *coord = [mapsIcon coordinateWithNormalizedOffset:CGVectorMake(0.5, 0.5)];

[[XCEventGenerator sharedGenerator] forcePressAtPoint:coord.screenPoint orientation:0 handler:^{}]; // handler cannot be nil

Here I execute a force press on the Maps icons.

Swift (not tested)

For Swift you have to declare/import the same interface/header as above and then execute the force press like this

let el = ...; // Get your element
let coord = el.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5) )
let eventGenerator: XCEventGenerator = XCEventGenerator.sharedGenerator() as! XCEventGenerator

eventGenerator.forcePress(at: coord.screenPoint, orientation: 0) { }
Cottonseed answered 18/4, 2017 at 3:1 Comment(2)
Can you provide a sample project? I've tried as you said above but still doesn't force touch. Also, I'm trying to force touch on an icon on springboardRedbud
Works like a charm. Do hope XCTest.framework's further version can expose these useful gestures.Mollusc
L
1

As of Xcode 10 there's no public API to achieve this. However you can use the -[XCUIElement forcePress] private API to simulate a full Peek and Pop interaction. Here's a simple Swift extension that exposes this functionality.

extension XCUIElement {
    func _forcePress() {
        XCTAssert(exists) // Forces the app to idle before interacting
        perform(Selector(("forcePress")))
    }
}

Keep in mind that this is a private API and so may be subject to change/removal in future releases of Xcode. That is, your tests may start crashing when running with a different Xcode version.

Love answered 28/6, 2019 at 15:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.