Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the text from a matched view using Detox?

I want to test a view that has a list and filtering functionality:

  1. I want to check the text of the first row and save it
  2. Filter using that text
  3. Check again that the same element is rendered

Thing is, when I match and element using element(by.id('some-id')), how can I retrieve info from that element (if it is possible) like the text it contains?

like image 485
Ferran Negre Avatar asked Nov 17 '17 13:11

Ferran Negre


2 Answers

I created the detox-getprops npm package incorporating the hack mentioned by Maxime Helen. It allows retrieving the text and some other (platform-dependent) properties of the element.

const { getText } = require('detox-getprops');

const text = await getText(element(by.id('heading')));
expect(text).toEqual('Step One');

I hope Detox #445 will be resolved soon after which this package can be deprecated.

Update: You can now fetch the text on iOS using the getAttributes method. The detox-getprops library is still needed for Android (tracked using Detox #2083).

like image 137
Sampo Avatar answered Oct 19 '22 21:10

Sampo


Hacky/funny workaround elaborated from this comment:

const readVisibleText = async (testID) => {
  try {
    await expect(element(by.id(testID))).toHaveText('_unfoundable_text');
    throw 'We never should get here unless target element has unfoundable text';
  } catch (error) {
    if (device.getPlatform() === 'ios') {
      const start = `accessibilityLabel was "`;
      const end = '" on ';
      const errorMessage = error.message.toString();
      const [, restMessage] = errorMessage.split(start);
      const [label] = restMessage.split(end);
      return label;
    } else {
      // Android to be tested
      const start = 'Got:';
      const end = '}"';
      const errorMessage = error.message.toString();
      const [, restMessage] = errorMessage.split(start);
      const [label] = restMessage.split(end);
      const value = label.split(',');
      var combineText = value.find(i => i.includes('text=')).trim();
      const [, elementText] = combineText.split('=');
      return elementText;
    }
  }
};
like image 21
Maxime Helen Avatar answered Oct 19 '22 23:10

Maxime Helen