Skip to content

refactor: component tree dead code #1403

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 8 commits into from
May 3, 2023
Merged
Show file tree
Hide file tree
Changes from 6 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
16 changes: 14 additions & 2 deletions src/__tests__/host-component-names.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,17 @@ beforeEach(() => {
describe('getHostComponentNames', () => {
test('returns host component names from internal config', () => {
configureInternal({
hostComponentNames: { text: 'banana', textInput: 'banana' },
hostComponentNames: {
text: 'banana',
textInput: 'banana',
switch: 'banana',
},
});

expect(getHostComponentNames()).toEqual({
text: 'banana',
textInput: 'banana',
switch: 'banana',
});
});

Expand All @@ -34,6 +39,7 @@ describe('getHostComponentNames', () => {
expect(hostComponentNames).toEqual({
text: 'Text',
textInput: 'TextInput',
switch: 'RCTSwitch',
});
expect(getConfig().hostComponentNames).toBe(hostComponentNames);
});
Expand Down Expand Up @@ -61,19 +67,25 @@ describe('configureHostComponentNamesIfNeeded', () => {
expect(getConfig().hostComponentNames).toEqual({
text: 'Text',
textInput: 'TextInput',
switch: 'RCTSwitch',
});
});

test('does not update internal config when host component names are already configured', () => {
configureInternal({
hostComponentNames: { text: 'banana', textInput: 'banana' },
hostComponentNames: {
text: 'banana',
textInput: 'banana',
switch: 'banana',
},
});

configureHostComponentNamesIfNeeded();

expect(getConfig().hostComponentNames).toEqual({
text: 'banana',
textInput: 'banana',
switch: 'banana',
});
});

Expand Down
36 changes: 25 additions & 11 deletions src/__tests__/react-native-api.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as React from 'react';
import { View, Text, TextInput } from 'react-native';
import { View, Text, TextInput, Switch } from 'react-native';
import { render } from '..';

/**
Expand All @@ -19,7 +19,6 @@ test('React Native API assumption: <View> renders single host element', () => {

test('React Native API assumption: <Text> renders single host element', () => {
const view = render(<Text testID="test">Hello</Text>);
expect(view.getByText('Hello')).toBe(view.getByTestId('test'));

expect(view.toJSON()).toMatchInlineSnapshot(`
<Text
Expand All @@ -40,11 +39,6 @@ test('React Native API assumption: nested <Text> renders single host element', (
</Text>
</Text>
);
expect(view.getByText(/Hello/)).toBe(view.getByTestId('test'));
expect(view.getByText('Before')).toBe(view.getByTestId('before'));
expect(view.getByText('Deeply nested')).toBe(
view.getByTestId('deeplyNested')
);

expect(view.toJSON()).toMatchInlineSnapshot(`
<Text
Expand Down Expand Up @@ -78,10 +72,6 @@ test('React Native API assumption: <TextInput> renders single host element', ()
placeholder="Placeholder"
/>
);
expect(view.getByPlaceholderText('Placeholder')).toBe(
view.getByTestId('test')
);

expect(view.toJSON()).toMatchInlineSnapshot(`
<TextInput
defaultValue="default"
Expand All @@ -91,3 +81,27 @@ test('React Native API assumption: <TextInput> renders single host element', ()
/>
`);
});

test('React Native API assumption: <Switch> renders single host element', () => {
const view = render(
<Switch testID="test" value={true} onChange={jest.fn()} />
);
expect(view.getByTestId('test')).toBe(view.getByTestId('test'));

expect(view.toJSON()).toMatchInlineSnapshot(`
<RCTSwitch
accessibilityRole="switch"
onChange={[Function]}
onResponderTerminationRequest={[Function]}
onStartShouldSetResponder={[Function]}
style={
{
"height": 31,
"width": 51,
}
}
testID="test"
value={true}
/>
`);
});
1 change: 1 addition & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export type ConfigAliasOptions = {
export type HostComponentNames = {
text: string;
textInput: string;
switch: string;
};

export type InternalConfig = Config & {
Expand Down
104 changes: 0 additions & 104 deletions src/helpers/__tests__/component-tree.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,8 @@ import { render } from '../..';
import {
getHostChildren,
getHostParent,
getHostSelf,
getHostSelves,
getHostSiblings,
getCompositeParentOfType,
isHostElementForType,
} from '../component-tree';

function ZeroHostChildren() {
Expand Down Expand Up @@ -106,72 +103,6 @@ describe('getHostChildren()', () => {
});
});

describe('getHostSelf()', () => {
it('returns passed element for host components', () => {
const view = render(
<View testID="grandparent">
<View testID="parent">
<View testID="subject" />
<View testID="sibling" />
</View>
</View>
);

const hostSubject = view.getByTestId('subject');
expect(getHostSelf(hostSubject)).toEqual(hostSubject);

const hostSibling = view.getByTestId('sibling');
expect(getHostSelf(hostSibling)).toEqual(hostSibling);

const hostParent = view.getByTestId('parent');
expect(getHostSelf(hostParent)).toEqual(hostParent);

const hostGrandparent = view.getByTestId('grandparent');
expect(getHostSelf(hostGrandparent)).toEqual(hostGrandparent);
});

it('returns single host child for React Native composite components', () => {
const view = render(
<View testID="parent">
<Text testID="text">Text</Text>
<TextInput
testID="textInput"
defaultValue="TextInputValue"
placeholder="TextInputPlaceholder"
/>
</View>
);

const compositeText = view.UNSAFE_getByType(Text);
const hostText = view.getByTestId('text');
expect(getHostSelf(compositeText)).toEqual(hostText);

const compositeTextInput = view.UNSAFE_getByType(TextInput);
const hostTextInput = view.getByTestId('textInput');
expect(getHostSelf(compositeTextInput)).toEqual(hostTextInput);
});

it('throws on non-single host children elements for custom composite components', () => {
const view = render(
<View testID="parent">
<ZeroHostChildren />
<MultipleHostChildren />
</View>
);

const zeroCompositeComponent = view.UNSAFE_getByType(ZeroHostChildren);
expect(() => getHostSelf(zeroCompositeComponent)).toThrow(
'Expected exactly one host element, but found none.'
);

const multipleCompositeComponent =
view.UNSAFE_getByType(MultipleHostChildren);
expect(() => getHostSelf(multipleCompositeComponent)).toThrow(
'Expected exactly one host element, but found 3.'
);
});
});

describe('getHostSelves()', () => {
it('returns passed element for host components', () => {
const view = render(
Expand Down Expand Up @@ -293,38 +224,3 @@ describe('getHostSiblings()', () => {
]);
});
});

test('getCompositeParentOfType', () => {
const root = render(
<View testID="view">
<Text testID="text" />
</View>
);
const hostView = root.getByTestId('view');
const hostText = root.getByTestId('text');

const compositeView = getCompositeParentOfType(hostView, View);
// We get the corresponding composite component (same testID), but not the host
expect(compositeView?.type).toBe(View);
expect(compositeView?.props.testID).toBe('view');
const compositeText = getCompositeParentOfType(hostText, Text);
expect(compositeText?.type).toBe(Text);
expect(compositeText?.props.testID).toBe('text');

// Checks parent type
expect(getCompositeParentOfType(hostText, View)).toBeNull();
expect(getCompositeParentOfType(hostView, Text)).toBeNull();

// Ignores itself, stops if ancestor is host
expect(getCompositeParentOfType(compositeText!, Text)).toBeNull();
expect(getCompositeParentOfType(compositeView!, View)).toBeNull();
});

test('isHostElementForType', () => {
const view = render(<View testID="test" />);
const hostComponent = view.getByTestId('test');
const compositeComponent = getCompositeParentOfType(hostComponent, View);
expect(isHostElementForType(hostComponent, View)).toBe(true);
expect(isHostElementForType(hostComponent, Text)).toBe(false);
expect(isHostElementForType(compositeComponent!, View)).toBe(false);
});
14 changes: 7 additions & 7 deletions src/helpers/accessiblity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@ import {
AccessibilityState,
AccessibilityValue,
StyleSheet,
Switch,
Text,
TextInput,
} from 'react-native';
import { ReactTestInstance } from 'react-test-renderer';
import { getHostSiblings, isHostElementForType } from './component-tree';
import { getConfig } from '../config';
import { getHostSiblings } from './component-tree';

type IsInaccessibleOptions = {
cache?: WeakMap<ReactTestInstance, boolean>;
Expand Down Expand Up @@ -101,9 +99,11 @@ export function isAccessibilityElement(
return element.props.accessible;
}

const hostComponentNames = getConfig().hostComponentNames;

return (
isHostElementForType(element, Text) ||
isHostElementForType(element, TextInput) ||
isHostElementForType(element, Switch)
element?.type === hostComponentNames?.text ||
element?.type === hostComponentNames?.textInput ||
element?.type === hostComponentNames?.switch
);
}
62 changes: 1 addition & 61 deletions src/helpers/component-tree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { ReactTestInstance } from 'react-test-renderer';
* Checks if the given element is a host element.
* @param element The element to check.
*/
export function isHostElement(element?: ReactTestInstance | null): boolean {
export function isHostElement(element?: ReactTestInstance | null) {
return typeof element?.type === 'string';
}

Expand Down Expand Up @@ -59,32 +59,6 @@ export function getHostChildren(
return hostChildren;
}

/**
* Return a single host element that represent the passed host or composite element.
*
* @param element The element start traversing from.
* @throws Error if the passed element is a composite element and has no host children or has more than one host child.
* @returns If the passed element is a host element, it will return itself, if the passed element is a composite
* element, it will return a single host descendant.
*/
export function getHostSelf(
element: ReactTestInstance | null
): ReactTestInstance {
const hostSelves = getHostSelves(element);

if (hostSelves.length === 0) {
throw new Error(`Expected exactly one host element, but found none.`);
}

if (hostSelves.length > 1) {
throw new Error(
`Expected exactly one host element, but found ${hostSelves.length}.`
);
}

return hostSelves[0];
}

/**
* Return the array of host elements that represent the passed element.
*
Expand Down Expand Up @@ -113,37 +87,3 @@ export function getHostSiblings(
(sibling) => !hostSelves.includes(sibling)
);
}

export function getCompositeParentOfType(
element: ReactTestInstance,
type: React.ComponentType
) {
let current = element.parent;

while (!isHostElement(current)) {
// We're at the root of the tree
if (!current) {
return null;
}

if (current.type === type) {
return current;
}
current = current.parent;
}

return null;
}

/**
* Note: this function should be generally used for core React Native types like `View`, `Text`, `TextInput`, etc.
*/
export function isHostElementForType(
element: ReactTestInstance,
type: React.ComponentType
) {
// Not a host element
if (!isHostElement(element)) return false;

return getCompositeParentOfType(element, type) !== null;
}
4 changes: 3 additions & 1 deletion src/helpers/host-component-names.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as React from 'react';
import { ReactTestInstance } from 'react-test-renderer';
import { Text, TextInput, View } from 'react-native';
import { Switch, Text, TextInput, View } from 'react-native';
import { configureInternal, getConfig, HostComponentNames } from '../config';
import { renderWithAct } from '../render-act';

Expand Down Expand Up @@ -33,12 +33,14 @@ function detectHostComponentNames(): HostComponentNames {
<View>
<Text testID="text">Hello</Text>
<TextInput testID="textInput" />
<Switch testID="switch" />
</View>
);

return {
text: getByTestId(renderer.root, 'text').type as string,
textInput: getByTestId(renderer.root, 'textInput').type as string,
switch: getByTestId(renderer.root, 'switch').type as string,
};
} catch (error) {
const errorMessage =
Expand Down