Detox get length of element

1.2k views Asked by At

Hi i'm using detox and i would like to know how can I get the number of matches to one element(length).

For example "card" match three times, how can I get the three.

const z = await element(by.id("card"))

https://github.com/wix/Detox/blob/master/docs/APIRef.Expect.md https://github.com/wix/Detox/blob/master/docs/APIRef.Matchers.md

They don't support it in the API /:

z output:

Element {
  _invocationManager: InvocationManager {
    executionHandler: Client {
      isConnected: true,
      configuration: [Object],
      ws: [AsyncWebSocket],
      slowInvocationStatusHandler: null,
      slowInvocationTimeout: undefined,
      successfulTestRun: true,
      pandingAppCrash: undefined
    }
  },
  matcher: Matcher { predicate: { type: 'id', value: 'card' } }
}
2

There are 2 answers

0
Pedro Trogo On

A workaround could be

async function getMatchesLength(elID) {
    let index = 0;

    try {
        while (true) {
            await expect(element(by.id(elID)).atIndex(index)).toExist();
            index++;
        }
    } catch (error) {
        console.log('find ', index, 'matches');
    }

    return index;
}

then you can use

const length = await getMatchesLength('card');
jestExpect(length).toBe(3);
1
neiker On

Here is my solution in typescript:

async function elementCount(matcher: Detox.NativeMatcher) {
  const attributes = await element(matcher).getAttributes();

  // If the query matches multiple elements, the attributes of all matched elements is returned as an array of objects under the elements key.
  https://wix.github.io/Detox/docs/api/actions-on-element/#getattributes
  if ("elements" in attributes) {
    return attributes.elements.length;
  } else {
    return 1;
  }
}

Then you can use it like this:

const jestExpect = require("expect");

jestExpect(await elementCount(by.id("some-id"))).toBe(2);