React native add test Ids to the components

Spread the love

To allow the test tools to select the UI components in the app for automation of testing, we need to give a testId to each element. You use the following method to maintain it:

Define a file with ids that you will giving and a helper function which will return the needed props:

export interface ITestProps {
  testId: string;
  accessibilityLabel: string;
}

export const createTestProps = (id: string): ITestProps => {
  return {testId: id, accessibilityLabel: id};
};

export const TestIds = {
  Screen1: {
    Field1: 'Filed1Id',
    Field2: 'Field2Id'
  },
};

Now you can use it the following way:

<TextInput {...createTestProps(TestIds.Screen1.Field1)}/>

Off-course you name the ids logically 🙂

Cheers and Peace Out!!!