-
Notifications
You must be signed in to change notification settings - Fork 274
/
Copy pathevent-handler.ts
39 lines (31 loc) · 1.07 KB
/
event-handler.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import type { ReactTestInstance } from 'react-test-renderer';
export type EventHandlerOptions = {
/** Include check for event handler named without adding `on*` prefix. */
loose?: boolean;
};
export function getEventHandler(
element: ReactTestInstance,
eventName: string,
options?: EventHandlerOptions,
) {
const handlerName = getEventHandlerName(eventName);
if (typeof element.props[handlerName] === 'function') {
return element.props[handlerName];
}
if (options?.loose && typeof element.props[eventName] === 'function') {
return element.props[eventName];
}
if (typeof element.props[`testOnly_${handlerName}`] === 'function') {
return element.props[`testOnly_${handlerName}`];
}
if (options?.loose && typeof element.props[`testOnly_${eventName}`] === 'function') {
return element.props[`testOnly_${eventName}`];
}
return undefined;
}
export function getEventHandlerName(eventName: string) {
return `on${capitalizeFirstLetter(eventName)}`;
}
function capitalizeFirstLetter(str: string) {
return str.charAt(0).toUpperCase() + str.slice(1);
}