Skip to content

feat: add autocomplete for fireEvent event names #1434

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
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
27 changes: 26 additions & 1 deletion src/fireEvent.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { ReactTestInstance } from 'react-test-renderer';
import {
ViewProps,
TextProps,
Copy link
Member

Choose a reason for hiding this comment

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

Let's also add TextInputProps

TextInputProps,
PressableProps,
ScrollViewProps,
} from 'react-native';
import act from './act';
import { isHostElement } from './helpers/component-tree';
import { getHostComponentNames } from './helpers/host-component-names';
Expand Down Expand Up @@ -108,9 +115,27 @@ function getEventHandlerName(eventName: string) {
return `on${eventName.charAt(0).toUpperCase()}${eventName.slice(1)}`;
}

// Allows any string but will provide autocomplete for type T
type StringWithAutoComplete<T> = T | (string & Record<never, never>);

// String union type of keys of T that start with on, stripped from on
type OnKeys<T> = keyof {
Copy link
Member

Choose a reason for hiding this comment

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

Nice trick! One think I find disturbing is that it's suggesting uppercase names, e.g. Press instead of press. Could you add another step that would make the event name lowercase?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Yes I agree, I updated it so that it's now lowercase

[K in keyof T as K extends `on${infer Rest}`
? Uncapitalize<Rest>
: never]: T[K];
};

type EventName = StringWithAutoComplete<
| OnKeys<ViewProps>
| OnKeys<TextProps>
| OnKeys<TextInputProps>
| OnKeys<PressableProps>
| OnKeys<ScrollViewProps>
>;

function fireEvent(
element: ReactTestInstance,
eventName: string,
eventName: EventName,
...data: unknown[]
) {
const handler = findEventHandler(element, eventName);
Expand Down