Add findAll base query method (#42829)

Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/42829

This is the base query method that we can wrap to use specific matchers like `findByTestID` or `findByRole`

Changelog: [internal]

Reviewed By: noahlemen

Differential Revision: D53359005

fbshipit-source-id: d1ac9c503b05d479567b6ced71d4517d5bc55b0b
This commit is contained in:
Jack Pope
2024-02-06 13:32:28 -08:00
committed by Facebook GitHub Bot
parent bc3fe0d76d
commit 8da1da2e73
2 changed files with 39 additions and 4 deletions
@@ -45,4 +45,19 @@ describe('render', () => {
expect(result.toJSON()).toMatchSnapshot();
});
});
describe('findAll', () => {
it('returns all nodes matching the predicate', () => {
const result = ReactNativeTestRenderer.render(<TestComponent />);
const textNode = result.findAll(node => {
return node.props?.text === 'Hello';
})[0];
expect(textNode).not.toBeUndefined();
const viewNodes = result.findAll(node => {
return node.viewName === 'RCTView';
});
expect(viewNodes.length).toBe(2);
});
});
});
+24 -4
View File
@@ -25,11 +25,10 @@ type FiberPartial = {
};
type ReactNode = {
children: $ReadOnlyArray<ReactNode>,
children: ?Array<ReactNode>,
props: {text?: string | null, ...},
viewName: string,
instanceHandle: FiberPartial,
...
};
type RenderedNodeJSON = {
@@ -41,12 +40,14 @@ type RenderedNodeJSON = {
type RenderedJSON = RenderedNodeJSON | string;
type RenderResult = {
toJSON: () => $ReadOnlyArray<RenderedJSON> | RenderedJSON | null,
toJSON: () => Array<RenderedJSON> | RenderedJSON | null,
findAll: (predicate: (ReactNode) => boolean) => Array<ReactNode>,
};
function buildRenderResult(rootNode: ReactNode): RenderResult {
return {
toJSON: () => toJSON(rootNode),
findAll: (predicate: ReactNode => boolean) => findAll(rootNode, predicate),
};
}
@@ -61,7 +62,7 @@ export function render(element: Element<ElementType>): RenderResult {
});
// $FlowFixMe
const root: RootReactNode = manager.getRoot(containerTag);
const root: [ReactNode] = manager.getRoot(containerTag);
if (root == null) {
throw new Error('No root found for containerTag ' + containerTag);
@@ -94,3 +95,22 @@ function toJSON(node: ReactNode): RenderedJSON {
return json;
}
function findAll(
node: ReactNode,
predicate: ReactNode => boolean,
): Array<ReactNode> {
const results = [];
if (predicate(node)) {
results.push(node);
}
if (node.children != null && node.children.length > 0) {
for (const child of node.children) {
results.push(...findAll(child, predicate));
}
}
return results;
}