iostestingearlgrey

Pressing the Back Button on Navigation Bar using EarlGrey


I've run into a bit of a snag trying to write a test that uses the back button, hopefully someone can point me in the right direction with this one.

My views are pretty standard I have a UINavigation controller as my root view controller and I'm pushing through it to a point and then need to go back.

I've tried to make a matcher that finds the back button in the navigation bar but have not had any success. I've attempted to use the label, id and value, setting the accessibility identifier on the back button item has not resulted in matches even though it works on my other interface elements.

[self.navigationItem.backBarButtonItem setAccessibilityIdentifier:@"Back"];

in my test I have the following:

// Press the back button

id<GREYMatcher> backMatcher =
    grey_allOf(grey_accessibilityID(@"Back"), grey_sufficientlyVisible(), nil);

[[EarlGrey selectElementWithMatcher:backMatcher] performAction:grey_tap()];

I used a breakpoint and PO to delve deeper and found the accessibilityLabel of the back button is indeed set to @"Back" but it does not match with the following code either.

// Press the back button

id<GREYMatcher> backMatcher =
    grey_allOf(grey_accessibilityID(@"Back"), grey_sufficientlyVisible(), nil);

[[EarlGrey selectElementWithMatcher:backMatcher] performAction:grey_tap()];

Solution

  • The problem is that you need a more specific matcher to get the Back button from a UINavigationController. If you look at the ui hierarchy that gets dumped when the test fails, you'll notice that more than one element has the accessibility label Back. So you need to narrow down the search a bit more by using the grey_accessibilityTrait matcher like so:

    id<GREYMatcher> matcherForBackButton =
        grey_allOf(grey_accessibilityLabel(@"Back"),
                   grey_accessibilityTrait(UIAccessibilityTraitButton),
                   nil);
    
    [[EarlGrey selectElementWithMatcher:matcherForBackButton]
        performAction:grey_tap()];