Skip to content

Commit

Permalink
Add findAll base query method (facebook#42829)
Browse files Browse the repository at this point in the history
Summary:
Pull Request resolved: facebook#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
  • Loading branch information
Jack Pope authored and facebook-github-bot committed Feb 6, 2024
1 parent bc3fe0d commit 8da1da2
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});
});
28 changes: 24 additions & 4 deletions packages/react-native-test-renderer/src/renderer/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,10 @@ type FiberPartial = {
};

type ReactNode = {
children: $ReadOnlyArray<ReactNode>,
children: ?Array<ReactNode>,
props: {text?: string | null, ...},
viewName: string,
instanceHandle: FiberPartial,
...
};

type RenderedNodeJSON = {
Expand All @@ -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),
};
}

Expand All @@ -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);
Expand Down Expand Up @@ -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;
}

0 comments on commit 8da1da2

Please sign in to comment.