mirror of
https://github.com/callstack/react-native-testing-library.git
synced 2026-09-18 23:09:04 +08:00
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>)
```
This commit is contained in:
committed by
Michał Pierzchała
parent
8f89cd51ee
commit
a39f879288
@@ -29,6 +29,12 @@ const CustomEventComponent = ({ onCustomEvent }) => (
|
||||
</TouchableOpacity>
|
||||
);
|
||||
|
||||
const DoublePressComponent = ({ onDoublePress }) => (
|
||||
<TouchableOpacity onDoublePress={onDoublePress}>
|
||||
<Text testID="button-text">Click me</Text>
|
||||
</TouchableOpacity>
|
||||
);
|
||||
|
||||
describe('fireEvent', () => {
|
||||
test('should invoke specified event', () => {
|
||||
const onPressMock = jest.fn();
|
||||
@@ -70,6 +76,18 @@ describe('fireEvent', () => {
|
||||
|
||||
expect(handlerMock).toHaveBeenCalledWith(EVENT_DATA);
|
||||
});
|
||||
|
||||
test('should not bubble event to root element', () => {
|
||||
const onPressMock = jest.fn();
|
||||
const { getByTestId } = render(
|
||||
<TouchableOpacity onPress={onPressMock}>
|
||||
<Text testID="test">Content</Text>
|
||||
</TouchableOpacity>
|
||||
);
|
||||
|
||||
expect(() => fireEvent.press(getByTestId('test'))).toThrowError();
|
||||
expect(onPressMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
test('fireEvent.press', () => {
|
||||
@@ -104,11 +122,8 @@ test('fireEvent.scroll', () => {
|
||||
|
||||
test('fireEvent.doublePress', () => {
|
||||
const onDoublePressMock = jest.fn();
|
||||
|
||||
const { getByTestId } = render(
|
||||
<TouchableOpacity onDoublePress={onDoublePressMock}>
|
||||
<Text testID="button-text">Click me</Text>
|
||||
</TouchableOpacity>
|
||||
<DoublePressComponent onDoublePress={onDoublePressMock} />
|
||||
);
|
||||
|
||||
fireEvent.doublePress(getByTestId('button-text'));
|
||||
|
||||
+2
-1
@@ -8,7 +8,8 @@ const findEventHandler = (element: ReactTestInstance, eventName: string) => {
|
||||
return element.props[eventHandler];
|
||||
}
|
||||
|
||||
if (element.parent === null) {
|
||||
// Do not bubble event to the root element
|
||||
if (element.parent === null || element.parent.parent === null) {
|
||||
throw new ErrorWithStack(
|
||||
`No handler function found for event: ${eventName}`,
|
||||
invokeEvent
|
||||
|
||||
Reference in New Issue
Block a user