Skip to content

feat: predicate query #973

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

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
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
89 changes: 89 additions & 0 deletions src/queries/__tests__/predicate.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import React from 'react';
import { View, Text, TextInput, Button } from 'react-native';
import { ReactTestInstance } from 'react-test-renderer';
import { render } from '../..';

test('getByPredicate returns only native elements', () => {
const testIdPredicate = (testID: string) => (element: ReactTestInstance) => {
return element.props.testID === testID;
};

const textInputPredicate = function matchTextInput(
element: ReactTestInstance
) {
// @ts-expect-error - ReatTestInstance type is missing host element typing
return element.type === 'TextInput';
};

const { getByPredicate, getAllByPredicate } = render(
<View>
<Text testID="text">Text</Text>
<TextInput testID="textInput" />
<View testID="view" />
<Button testID="button" title="Button" onPress={jest.fn()} />
</View>
);

expect(getByPredicate(testIdPredicate('text'))).toBeTruthy();
expect(getByPredicate(testIdPredicate('textInput'))).toBeTruthy();
expect(getByPredicate(testIdPredicate('view'))).toBeTruthy();
expect(getByPredicate(testIdPredicate('button'))).toBeTruthy();

expect(getAllByPredicate(testIdPredicate('text'))).toHaveLength(1);
expect(getAllByPredicate(testIdPredicate('textInput'))).toHaveLength(1);
expect(getAllByPredicate(testIdPredicate('view'))).toHaveLength(1);
expect(getAllByPredicate(testIdPredicate('button'))).toHaveLength(1);

expect(getByPredicate(textInputPredicate)).toBeTruthy();
});

test('getByPredicate error messages', () => {
function hasStylePredicate(element: ReactTestInstance) {
return element.props.style !== undefined;
}

const textInputPredicate = function textInputPredicate(
element: ReactTestInstance
) {
// @ts-expect-error - ReatTestInstance type is missing host element typing
return element.type === 'TextInput';
};

const testIdPredicate = (testID: string) => (element: ReactTestInstance) => {
return element.props.testID === testID;
};

const { getByPredicate, getAllByPredicate } = render(
<View>
<Text testID="text">Text</Text>
</View>
);

expect(() => getByPredicate(hasStylePredicate))
.toThrowErrorMatchingInlineSnapshot(`
"Unable to find an element matching predicate: function hasStylePredicate(element) {
return element.props.style !== undefined;
}"
`);

expect(() => getByPredicate(textInputPredicate))
.toThrowErrorMatchingInlineSnapshot(`
"Unable to find an element matching predicate: function textInputPredicate(element) {
// @ts-expect-error - ReatTestInstance type is missing host element typing
return element.type === 'TextInput';
}"
`);

expect(() => getByPredicate(testIdPredicate('myComponent')))
.toThrowErrorMatchingInlineSnapshot(`
"Unable to find an element matching predicate: element => {
return element.props.testID === testID;
}"
`);
expect(() => getAllByPredicate(testIdPredicate('myComponent')))
.toThrowErrorMatchingInlineSnapshot(`
"Unable to find an element matching predicate: element => {
return element.props.testID === testID;
}"
`);
});
63 changes: 63 additions & 0 deletions src/queries/predicate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import type { ReactTestInstance } from 'react-test-renderer';
import { isHostElement } from '../helpers/component-tree';
import { findAll } from '../helpers/findAll';
import { makeQueries } from './makeQueries';
import type {
FindAllByQuery,
FindByQuery,
GetAllByQuery,
GetByQuery,
QueryAllByQuery,
QueryByQuery,
} from './makeQueries';
import { CommonQueryOptions } from './options';

type PredicateFn = (instance: ReactTestInstance) => boolean;
type ByPredicateQueryOptions = CommonQueryOptions;

function queryAllByPredicate(instance: ReactTestInstance) {
return function queryAllByPredicateFn(
predicate: PredicateFn,
options?: ByPredicateQueryOptions
): Array<ReactTestInstance> {
const results = findAll(
instance,
(node) => isHostElement(node) && predicate(node),
options
);

return results;
};
}

const getMultipleError = (predicate: PredicateFn) =>
`Found multiple elements matching predicate: ${predicate}`;

const getMissingError = (predicate: PredicateFn) =>
`Unable to find an element matching predicate: ${predicate}`;

const { getBy, getAllBy, queryBy, queryAllBy, findBy, findAllBy } = makeQueries(
queryAllByPredicate,
getMissingError,
getMultipleError
);

export type ByTestIdQueries = {
getByPredicate: GetByQuery<PredicateFn, ByPredicateQueryOptions>;
getAllByPredicate: GetAllByQuery<PredicateFn, ByPredicateQueryOptions>;
queryByPredicate: QueryByQuery<PredicateFn, ByPredicateQueryOptions>;
queryAllByPredicate: QueryAllByQuery<PredicateFn, ByPredicateQueryOptions>;
findByPredicate: FindByQuery<PredicateFn, ByPredicateQueryOptions>;
findAllByPredicate: FindAllByQuery<PredicateFn, ByPredicateQueryOptions>;
};

export const bindByPredicateQueries = (
instance: ReactTestInstance
): ByTestIdQueries => ({
getByPredicate: getBy(instance),
getAllByPredicate: getAllBy(instance),
queryByPredicate: queryBy(instance),
queryAllByPredicate: queryAllBy(instance),
findByPredicate: findBy(instance),
findAllByPredicate: findAllBy(instance),
});
6 changes: 6 additions & 0 deletions src/screen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,12 @@ const defaultScreen: RenderResult = {
queryAllByText: notImplemented,
findByText: notImplemented,
findAllByText: notImplemented,
getByPredicate: notImplemented,
getAllByPredicate: notImplemented,
queryByPredicate: notImplemented,
queryAllByPredicate: notImplemented,
findByPredicate: notImplemented,
findAllByPredicate: notImplemented,
};

export let screen: RenderResult = defaultScreen;
Expand Down
2 changes: 2 additions & 0 deletions src/within.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { bindByA11yStateQueries } from './queries/a11yState';
import { bindByA11yValueQueries } from './queries/a11yValue';
import { bindUnsafeByTypeQueries } from './queries/unsafeType';
import { bindUnsafeByPropsQueries } from './queries/unsafeProps';
import { bindByPredicateQueries } from './queries/predicate';

export function within(instance: ReactTestInstance) {
return {
Expand All @@ -22,6 +23,7 @@ export function within(instance: ReactTestInstance) {
...bindByRoleQueries(instance),
...bindByA11yStateQueries(instance),
...bindByA11yValueQueries(instance),
...bindByPredicateQueries(instance),
...bindUnsafeByTypeQueries(instance),
...bindUnsafeByPropsQueries(instance),
};
Expand Down
33 changes: 33 additions & 0 deletions typings/index.flow.js
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,38 @@ interface A11yAPI {
) => FindAllReturn;
}

type PredicateFn = (node: ReactTestInstance) => boolean;
type ByPredicateOptions = CommonQueryOptions;

interface ByPredicateQueries {
getByPredicate: (
predicate: PredicateFn,
options?: ByPredicateOptions
) => ReactTestInstance;
getAllByPredicate: (
predicate: PredicateFn,
options?: ByPredicateOptions
) => Array<ReactTestInstance>;
queryByPredicate: (
predicate: PredicateFn,
options?: ByPredicateOptions
) => ReactTestInstance | null;
queryAllByPredicate: (
predicate: PredicateFn,
options?: ByPredicateOptions
) => Array<ReactTestInstance> | [];
findByPredicate: (
predicate: PredicateFn,
queryOptions?: ByPredicateOptions,
waitForOptions?: WaitForOptions
) => FindReturn;
findAllByPredicate: (
predicate: PredicateFn,
queryOptions?: ByPredicateOptions,
waitForOptions?: WaitForOptions
) => FindAllReturn;
}

interface Thenable {
then: (resolve: () => any, reject?: () => any) => any;
}
Expand All @@ -412,6 +444,7 @@ type Queries = ByTextQueries &
ByTestIdQueries &
ByDisplayValueQueries &
ByPlaceholderTextQueries &
ByPredicateQueries &
UnsafeByTypeQueries &
UnsafeByPropsQueries &
A11yAPI;
Expand Down
18 changes: 18 additions & 0 deletions website/docs/Queries.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ title: Queries
- [Default state for: `disabled`, `selected`, and `busy` keys](#default-state-for-disabled-selected-and-busy-keys)
- [Default state for: `checked` and `expanded` keys](#default-state-for-checked-and-expanded-keys)
- [`ByA11Value`, `ByAccessibilityValue`](#bya11value-byaccessibilityvalue)
- [`ByPredicate`](#bypredicate)
- [Common options](#common-options)
- [`includeHiddenElements` option](#includehiddenelements-option)
- [TextMatch](#textmatch)
Expand Down Expand Up @@ -391,6 +392,23 @@ const element = screen.getByA11yValue({ now: 25 });
const element2 = screen.getByA11yValue({ text: /25/ });
```

### `ByPredicate`

> getByPredicate, getAllByPredicate, queryByPredicate, queryAllByPredicate, findByPredicate, findAllByPredicate

```ts
getByPredicate(
predicate: (element: ReactTestInstance) => boolean,
options?: {
includeHiddenElements?: boolean;
}
): ReactTestInstance;
```

Returns a host element matching a custom `predicate` function.

This query type is an escape hatch and should be used with care. In most cases you using the standard queries like `getByRole` or `getByText` will lead to test more-resembling user perspective. Use this query with care in rare cases where more flexibility is needed.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could we provide an example of a real scenario where we might need it and how to use it in that case? (like it's done for ByAccessibilityValue above)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea to add some examples there. One thought that I have atm is that these examples will be somewhat hacky, as if they were really good ideas we would make regular queries from them ;-)

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i see what you mean, but then RNTL only provides queries for common case scenarios. We could find a legit scenario that's very uncommon maybe? Like find all underline text? (so hard to find a rare but legit scenario haha ^^')

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, we can build examples to showcase how you can recreate some existing queries like *ByTestId.

I went back to the source, DTL docs, to check what examples they give, but they are basically implementing *ByTestId queries using some queryByAttribute function. All that seems like legacy stuff that has no good examples.


## Common options

### `includeHiddenElements` option
Expand Down