Skip to content

Commit 8984abb

Browse files
ferrannpEsemesek
authored andcommitted
feat: being able to fire custom events that do not need to start with "on" (#147)
### Summary If I have a custom button like: ```js <MyCustomButton handlePress={onPress} /> ``` The following will not work: ```js fireEvent(getByTestId('my-custom-button'), 'handlePress'); ``` Because we are trying to call `onHandlePress`. ### Test plan ``` yarn test fireEvent ```
1 parent 55b9c67 commit 8984abb

File tree

3 files changed

+23
-0
lines changed

3 files changed

+23
-0
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@ node_modules
22
*.log
33
.eslintcache
44
build
5+
.idea

src/__tests__/fireEvent.test.js

+20
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,14 @@ const CustomEventComponent = ({ onCustomEvent }) => (
2929
</TouchableOpacity>
3030
);
3131

32+
const MyCustomButton = ({ handlePress }) => (
33+
<OnPressComponent onPress={handlePress} />
34+
);
35+
36+
const CustomEventComponentWithCustomName = ({ handlePress }) => (
37+
<MyCustomButton testID="my-custom-button" handlePress={handlePress} />
38+
);
39+
3240
describe('fireEvent', () => {
3341
test('should invoke specified event', () => {
3442
const onPressMock = jest.fn();
@@ -128,3 +136,15 @@ test('fireEvent.changeText', () => {
128136

129137
expect(onChangeTextMock).toHaveBeenCalledWith(CHANGE_TEXT);
130138
});
139+
140+
test('custom component with custom event name', () => {
141+
const handlePress = jest.fn();
142+
143+
const { getByTestId } = render(
144+
<CustomEventComponentWithCustomName handlePress={handlePress} />
145+
);
146+
147+
fireEvent(getByTestId('my-custom-button'), 'handlePress');
148+
149+
expect(handlePress).toHaveBeenCalled();
150+
});

src/fireEvent.js

+2
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ const findEventHandler = (element: ReactTestInstance, eventName: string) => {
77

88
if (typeof element.props[eventHandler] === 'function') {
99
return element.props[eventHandler];
10+
} else if (typeof element.props[eventName] === 'function') {
11+
return element.props[eventName];
1012
}
1113

1214
// Do not bubble event to the root element

0 commit comments

Comments
 (0)