Skip to content

Add support for ByRole with name #1127

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Sep 22, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions src/queries/__tests__/role.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ test('getByRole, queryByRole, findByRole', async () => {
expect(() => getByRole(NO_MATCHES_TEXT)).toThrow(
getNoInstancesFoundMessage(NO_MATCHES_TEXT)
);

expect(queryByRole(NO_MATCHES_TEXT)).toBeNull();

expect(() => getByRole('link')).toThrow(
Expand Down Expand Up @@ -77,3 +78,61 @@ test('getAllByRole, queryAllByRole, findAllByRole', async () => {
getNoInstancesFoundMessage(NO_MATCHES_TEXT)
);
});

describe('*ByRole with a name', () => {
test('Find an element that has the corresponding role and a children with the name', () => {
const { getByRole } = render(
<TouchableOpacity accessibilityRole="button" testID="target-button">
<Text>Save</Text>
</TouchableOpacity>
);

// assert on the testId to be sure that the returned element is the one with the accessibilityRole
expect(getByRole('button', { name: 'Save' }).props.testID).toBe(
'target-button'
);
});

test('Find an element that has the corresponding role and a children with a matching accessibilityLabel', () => {
const { getByRole } = render(
<TouchableOpacity accessibilityRole="button" testID="target-button">
<Text accessibilityLabel="Save" />
</TouchableOpacity>
);

// assert on the testId to be sure that the returned element is the one with the accessibilityRole
expect(getByRole('button', { name: 'Save' }).props.testID).toBe(
'target-button'
);
});

test('Find an element that has the corresponding role and a matching accessibilityLabel', () => {
const { getByRole } = render(
<TouchableOpacity
accessibilityRole="button"
testID="target-button"
accessibilityLabel="Save"
></TouchableOpacity>
);

// assert on the testId to be sure that the returned element is the one with the accessibilityRole
expect(getByRole('button', { name: 'Save' }).props.testID).toBe(
'target-button'
);
});

test('Can find by name using a regex', () => {
const { getByRole } = render(
<TouchableOpacity
accessibilityRole="button"
testID="target-button"
accessibilityLabel="Save"
></TouchableOpacity>
);

// assert on the testId to be sure that the returned element is the one with the accessibilityRole
expect(getByRole('button', { name: /Save/ }).props.testID).toBe(
'target-button'
);
});
});
43 changes: 31 additions & 12 deletions src/queries/role.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import type { ReactTestInstance } from 'react-test-renderer';
import { TextMatch } from '../matches';
import type { AccessibilityRole } from 'react-native';
import { matchStringProp } from '../helpers/matchers/matchStringProp';
import { TextMatch } from '../matches';
import { getQueriesForElement } from '../within';
import { makeQueries } from './makeQueries';
import type {
FindAllByQuery,
Expand All @@ -11,20 +13,37 @@ import type {
QueryByQuery,
} from './makeQueries';

type Role = AccessibilityRole | TextMatch;

type ByRoleOptions = {
name?: TextMatch;
};

const filterByAccessibleName = (
node: ReactTestInstance,
name: TextMatch | undefined
) => {
if (!name) return true;

const { queryByText, queryByLabelText } = getQueriesForElement(node);
return Boolean(queryByText(name) || queryByLabelText(name));
};

const queryAllByRole = (
instance: ReactTestInstance
): ((role: TextMatch) => Array<ReactTestInstance>) =>
function queryAllByRoleFn(role) {
): ((role: Role, options?: ByRoleOptions) => Array<ReactTestInstance>) =>
function queryAllByRoleFn(role, options) {
return instance.findAll(
(node) =>
typeof node.type === 'string' &&
matchStringProp(node.props.accessibilityRole, role)
matchStringProp(node.props.accessibilityRole, role) &&
filterByAccessibleName(node, options?.name)
);
};

const getMultipleError = (role: TextMatch) =>
const getMultipleError = (role: Role) =>
`Found multiple elements with accessibilityRole: ${String(role)} `;
const getMissingError = (role: TextMatch) =>
const getMissingError = (role: Role) =>
`Unable to find an element with accessibilityRole: ${String(role)}`;

const { getBy, getAllBy, queryBy, queryAllBy, findBy, findAllBy } = makeQueries(
Expand All @@ -34,12 +53,12 @@ const { getBy, getAllBy, queryBy, queryAllBy, findBy, findAllBy } = makeQueries(
);

export type ByRoleQueries = {
getByRole: GetByQuery<TextMatch>;
getAllByRole: GetAllByQuery<TextMatch>;
queryByRole: QueryByQuery<TextMatch>;
queryAllByRole: QueryAllByQuery<TextMatch>;
findByRole: FindByQuery<TextMatch>;
findAllByRole: FindAllByQuery<TextMatch>;
getByRole: GetByQuery<Role, ByRoleOptions>;
getAllByRole: GetAllByQuery<Role, ByRoleOptions>;
queryByRole: QueryByQuery<Role, ByRoleOptions>;
queryAllByRole: QueryAllByQuery<Role, ByRoleOptions>;
findByRole: FindByQuery<Role, ByRoleOptions>;
findAllByRole: FindAllByQuery<Role, ByRoleOptions>;
};

export const bindByRoleQueries = (
Expand Down
21 changes: 17 additions & 4 deletions typings/index.flow.js
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,11 @@ interface UnsafeByPropsQueries {
| Array<ReactTestInstance>
| [];
}

interface ByRoleOption {
name: string;
}

interface A11yAPI {
// Label
getByLabelText: (matcher: TextMatch) => GetReturn;
Expand Down Expand Up @@ -244,16 +249,24 @@ interface A11yAPI {
) => FindAllReturn;

// Role
getByRole: (matcher: A11yRole | RegExp) => GetReturn;
getAllByRole: (matcher: A11yRole | RegExp) => GetAllReturn;
queryByRole: (matcher: A11yRole | RegExp) => QueryReturn;
queryAllByRole: (matcher: A11yRole | RegExp) => QueryAllReturn;
getByRole: (matcher: A11yRole | RegExp, role?: ByRoleOption) => GetReturn;
getAllByRole: (
matcher: A11yRole | RegExp,
role?: ByRoleOption
) => GetAllReturn;
queryByRole: (matcher: A11yRole | RegExp, role?: ByRoleOption) => QueryReturn;
queryAllByRole: (
matcher: A11yRole | RegExp,
role?: ByRoleOption
) => QueryAllReturn;
findByRole: (
matcher: A11yRole | RegExp,
role?: ByRoleOption,
waitForOptions?: WaitForOptions
) => FindReturn;
findAllByRole: (
matcher: A11yRole | RegExp,
role?: ByRoleOption,
waitForOptions?: WaitForOptions
) => FindAllReturn;

Expand Down
7 changes: 6 additions & 1 deletion website/docs/Queries.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,10 @@ render(<MyComponent />);
const element = screen.getByRole('button');
```

#### Options

`name`: Finds an element with given `accessibilityRole` and an accessible name (equivalent to `ByText` or `queryByLabelText`).

### `ByA11yState`, `ByAccessibilityState`

> getByA11yState, getAllByA11yState, queryByA11yState, queryAllByA11yState, findByA11yState, findAllByA11yState
Expand Down Expand Up @@ -305,7 +309,8 @@ To override normalization to remove some Unicode characters whilst keeping some

```typescript
screen.getByText(node, 'text', {
normalizer: (str) => getDefaultNormalizer({ trim: false })(str).replace(/[\u200E-\u200F]*/g, ''),
normalizer: (str) =>
getDefaultNormalizer({ trim: false })(str).replace(/[\u200E-\u200F]*/g, ''),
});
```

Expand Down