Search code examples
reactjsreact-nativetestingautomationdetox

React Native End to End Tests with Detox: Getting height, width, and other properties of matched elements


As the title states, I would like to programmatically retrieve properties of matched elements in Detox. I know Detox sees them, because as we all infamously know when a toBeVisible expectation fails by the 75% view rule (a built in Detox opinion for the uninitated), we can see what detox 'got', usually it is a message something like this:

Got: "ReactTextView{id=13725, visibility=VISIBLE, width=376, height=102, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=android.view.ViewGroup$LayoutParams@ac227fb, tag=PROFILE_NAME_TEXT, root-is-layout-requested=false, has-input-connection=false, x=486.0, y=120.0, text=Anonymous, input-type=0, ime-target=false, has-links=false}"

So we have things like the width, height, focus and so on.

My question is, how can we get at these properties programmatically? Specifically, I have an element that is expanding after a button tap and I want to be sure the height is larger than it was before.

If you check the methods available for element(by.id("SOME_ID")), there are only action methods available...


Solution

  • I've finally discovered the answer which was hard to find initial due to missing typings of detox at the time. Properties like height and width that I mentioned are available through getAttributes() method:

    const attributes = await element(by.text('Tap Me')).getAttributes();
    expect(attributes.text).toBe('Tap Me');
    
    const multipleMatchedElements = await element(by.text('Multiple')).getAttributes();
    expect(multipleMatchedElements.elements.length).toBe(5);
    expect(multipleMatchedElements.elements[0].identifier).toBe('FirstElement');
    

    The available properties vary between Android and iOS as well. See the documentation in the library for getAttributes(), and the pull request on detox which adds all the types.