Skip to content

feat: simulated native TextInput state #1653

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 3, 2024
Merged
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
16 changes: 13 additions & 3 deletions src/__tests__/fire-event.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
View,
} from 'react-native';
import { fireEvent, render, screen } from '..';
import '../matchers/extend-expect';

type OnPressComponentProps = {
onPress: () => void;
Expand Down Expand Up @@ -139,17 +140,26 @@ test('fireEvent.scroll', () => {

test('fireEvent.changeText', () => {
const onChangeTextMock = jest.fn();
const CHANGE_TEXT = 'content';

render(
<View>
<TextInput placeholder="Customer placeholder" onChangeText={onChangeTextMock} />
</View>,
);

fireEvent.changeText(screen.getByPlaceholderText('Customer placeholder'), CHANGE_TEXT);
const input = screen.getByPlaceholderText('Customer placeholder');
fireEvent.changeText(input, 'content');
expect(onChangeTextMock).toHaveBeenCalledWith('content');
});

it('sets native state value for unmanaged text inputs', () => {
render(<TextInput testID="input" />);

const input = screen.getByTestId('input');
expect(input).toHaveDisplayValue('');

expect(onChangeTextMock).toHaveBeenCalledWith(CHANGE_TEXT);
fireEvent.changeText(input, 'abc');
expect(input).toHaveDisplayValue('abc');
});

test('custom component with custom event name', () => {
Expand Down
9 changes: 6 additions & 3 deletions src/cleanup.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import * as React from 'react';
import { clearNativeState } from './native-state';
import { clearRenderResult } from './screen';

type CleanUpFunction = (nextElement?: React.ReactElement<any>) => void;
let cleanupQueue = new Set<CleanUpFunction>();
type CleanUpFunction = () => void;

const cleanupQueue = new Set<CleanUpFunction>();

export default function cleanup() {
clearNativeState();
clearRenderResult();

cleanupQueue.forEach((fn) => fn());
cleanupQueue.clear();
}
Expand Down
14 changes: 14 additions & 0 deletions src/fire-event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { isHostTextInput } from './helpers/host-component-names';
import { isPointerEventEnabled } from './helpers/pointer-events';
import { isTextInputEditable } from './helpers/text-input';
import { StringWithAutocomplete } from './types';
import { nativeState } from './native-state';

type EventHandler = (...args: unknown[]) => unknown;

Expand Down Expand Up @@ -120,6 +121,8 @@ type EventName = StringWithAutocomplete<
>;

function fireEvent(element: ReactTestInstance, eventName: EventName, ...data: unknown[]) {
setNativeStateIfNeeded(element, eventName, data[0]);

const handler = findEventHandler(element, eventName);
if (!handler) {
return;
Expand All @@ -143,3 +146,14 @@ fireEvent.scroll = (element: ReactTestInstance, ...data: unknown[]) =>
fireEvent(element, 'scroll', ...data);

export default fireEvent;

function setNativeStateIfNeeded(element: ReactTestInstance, eventName: string, value: unknown) {
if (
eventName === 'changeText' &&
typeof value === 'string' &&
isHostTextInput(element) &&
isTextInputEditable(element)
) {
nativeState?.elementValues.set(element, value);
}
}
8 changes: 7 additions & 1 deletion src/helpers/text-input.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { ReactTestInstance } from 'react-test-renderer';
import { nativeState } from '../native-state';
import { isHostTextInput } from './host-component-names';

export function isTextInputEditable(element: ReactTestInstance) {
Expand All @@ -14,5 +15,10 @@ export function getTextInputValue(element: ReactTestInstance) {
throw new Error(`Element is not a "TextInput", but it has type "${element.type}".`);
}

return element.props.value ?? element.props.defaultValue;
return (
element.props.value ??
nativeState?.elementValues.get(element) ??
element.props.defaultValue ??
''
);
}
22 changes: 22 additions & 0 deletions src/native-state.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { ReactTestInstance } from 'react-test-renderer';

/**
* Simulated native state for unmanaged controls.
*
* Values from `value` props (managed controls) should take precedence over these values.
*/
export type NativeState = {
elementValues: WeakMap<ReactTestInstance, string>;
};

export let nativeState: NativeState | null = null;

export function initNativeState(): void {
nativeState = {
elementValues: new WeakMap(),
};
}

export function clearNativeState(): void {
nativeState = null;
}
3 changes: 3 additions & 0 deletions src/render.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { validateStringsRenderedWithinText } from './helpers/string-validation';
import { renderWithAct } from './render-act';
import { setRenderResult } from './screen';
import { getQueriesForElement } from './within';
import { initNativeState } from './native-state';

export interface RenderOptions {
wrapper?: React.ComponentType<any>;
Expand Down Expand Up @@ -127,6 +128,8 @@ function buildRenderResult(
});

setRenderResult(result);
initNativeState();

return result;
}

Expand Down
13 changes: 13 additions & 0 deletions src/user-event/__tests__/clear.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as React from 'react';
import { TextInput, TextInputProps, View } from 'react-native';
import { createEventLogger, getEventsNames } from '../../test-utils';
import { render, userEvent, screen } from '../..';
import '../../matchers/extend-expect';

beforeEach(() => {
jest.useRealTimers();
Expand Down Expand Up @@ -205,4 +206,16 @@ describe('clear()', () => {
await user.clear(screen.getByTestId('input'));
expect(parentHandler).not.toHaveBeenCalled();
});

it('sets native state value for unmanaged text inputs', async () => {
render(<TextInput testID="input" />);

const user = userEvent.setup();
const input = screen.getByTestId('input');
await user.type(input, 'abc');
expect(input).toHaveDisplayValue('abc');

await user.clear(input);
expect(input).toHaveDisplayValue('');
});
});
12 changes: 12 additions & 0 deletions src/user-event/__tests__/paste.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as React from 'react';
import { TextInput, TextInputProps, View } from 'react-native';
import { createEventLogger, getEventsNames } from '../../test-utils';
import { render, userEvent, screen } from '../..';
import '../../matchers/extend-expect';

beforeEach(() => {
jest.useRealTimers();
Expand Down Expand Up @@ -221,4 +222,15 @@ describe('paste()', () => {
await user.paste(screen.getByTestId('input'), 'Hi!');
expect(parentHandler).not.toHaveBeenCalled();
});

it('sets native state value for unmanaged text inputs', async () => {
render(<TextInput testID="input" />);

const user = userEvent.setup();
const input = screen.getByTestId('input');
expect(input).toHaveDisplayValue('');

await user.paste(input, 'abc');
expect(input).toHaveDisplayValue('abc');
});
});
2 changes: 2 additions & 0 deletions src/user-event/paste.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { ErrorWithStack } from '../helpers/errors';
import { isHostTextInput } from '../helpers/host-component-names';
import { isPointerEventEnabled } from '../helpers/pointer-events';
import { isTextInputEditable } from '../helpers/text-input';
import { nativeState } from '../native-state';
import { EventBuilder } from './event-builder';
import { UserEventInstance } from './setup';
import { dispatchEvent, getTextContentSize, wait } from './utils';
Expand Down Expand Up @@ -32,6 +33,7 @@ export async function paste(
dispatchEvent(element, 'selectionChange', EventBuilder.TextInput.selectionChange(rangeToClear));

// 3. Paste the text
nativeState?.elementValues.set(element, text);
dispatchEvent(element, 'change', EventBuilder.TextInput.change(text));
dispatchEvent(element, 'changeText', text);

Expand Down
12 changes: 12 additions & 0 deletions src/user-event/type/__tests__/type.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { TextInput, TextInputProps, View } from 'react-native';
import { createEventLogger, getEventsNames, lastEventPayload } from '../../../test-utils';
import { render, screen } from '../../..';
import { userEvent } from '../..';
import '../../../matchers/extend-expect';

beforeEach(() => {
jest.useRealTimers();
Expand Down Expand Up @@ -372,4 +373,15 @@ describe('type()', () => {
},
});
});

it('sets native state value for unmanaged text inputs', async () => {
render(<TextInput testID="input" />);

const user = userEvent.setup();
const input = screen.getByTestId('input');
expect(input).toHaveDisplayValue('');

await user.type(input, 'abc');
expect(input).toHaveDisplayValue('abc');
});
});
2 changes: 2 additions & 0 deletions src/user-event/type/type.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { ReactTestInstance } from 'react-test-renderer';
import { isHostTextInput } from '../../helpers/host-component-names';
import { nativeState } from '../../native-state';
import { EventBuilder } from '../event-builder';
import { ErrorWithStack } from '../../helpers/errors';
import { isTextInputEditable } from '../../helpers/text-input';
Expand Down Expand Up @@ -94,6 +95,7 @@ export async function emitTypingEvents(
return;
}

nativeState?.elementValues.set(element, text);
dispatchEvent(element, 'change', EventBuilder.TextInput.change(text));
dispatchEvent(element, 'changeText', text);

Expand Down
Loading