Skip to content

Commit a39f879

Browse files
Esemesekthymikee
authored andcommitted
fix: do not bubble event to root element (#30)
Remove bubbling events to the root element as in the most common use case we pass handler prop to the root element: ```jsx // That's usually what we do in tests const tree = render(<SomeElement onPress={mockedHandler} />); // Unsupported use case const tree = render(<TouchableOpacity onPress={mockHandler()}><Text>XD</Text></TouchableOpacity>) ```
1 parent 8f89cd5 commit a39f879

File tree

2 files changed

+21
-5
lines changed

2 files changed

+21
-5
lines changed

src/__tests__/fireEvent.test.js

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

32+
const DoublePressComponent = ({ onDoublePress }) => (
33+
<TouchableOpacity onDoublePress={onDoublePress}>
34+
<Text testID="button-text">Click me</Text>
35+
</TouchableOpacity>
36+
);
37+
3238
describe('fireEvent', () => {
3339
test('should invoke specified event', () => {
3440
const onPressMock = jest.fn();
@@ -70,6 +76,18 @@ describe('fireEvent', () => {
7076

7177
expect(handlerMock).toHaveBeenCalledWith(EVENT_DATA);
7278
});
79+
80+
test('should not bubble event to root element', () => {
81+
const onPressMock = jest.fn();
82+
const { getByTestId } = render(
83+
<TouchableOpacity onPress={onPressMock}>
84+
<Text testID="test">Content</Text>
85+
</TouchableOpacity>
86+
);
87+
88+
expect(() => fireEvent.press(getByTestId('test'))).toThrowError();
89+
expect(onPressMock).not.toHaveBeenCalled();
90+
});
7391
});
7492

7593
test('fireEvent.press', () => {
@@ -104,11 +122,8 @@ test('fireEvent.scroll', () => {
104122

105123
test('fireEvent.doublePress', () => {
106124
const onDoublePressMock = jest.fn();
107-
108125
const { getByTestId } = render(
109-
<TouchableOpacity onDoublePress={onDoublePressMock}>
110-
<Text testID="button-text">Click me</Text>
111-
</TouchableOpacity>
126+
<DoublePressComponent onDoublePress={onDoublePressMock} />
112127
);
113128

114129
fireEvent.doublePress(getByTestId('button-text'));

src/fireEvent.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@ const findEventHandler = (element: ReactTestInstance, eventName: string) => {
88
return element.props[eventHandler];
99
}
1010

11-
if (element.parent === null) {
11+
// Do not bubble event to the root element
12+
if (element.parent === null || element.parent.parent === null) {
1213
throw new ErrorWithStack(
1314
`No handler function found for event: ${eventName}`,
1415
invokeEvent

0 commit comments

Comments
 (0)