When running fireEvent.press on a disabled TouchableOpacity, the following error appears: No handler function found for event: "press"
Should not raise an error
Run the following
import { TouchableOpacity } from 'react-native'
describe.only('Test TouchableOpacity', () => {
const Button = ({ onPress }) => {
return <TouchableOpacity testID='testBtn' disabled={true} onPress={onPress}></TouchableOpacity>
}
const onPressSpy = sinon.spy()
it('onPress does not trigger', () => {
const { getByTestId } = render( <Button onPress={onPressSpy}/>)
fireEvent.press(getByTestId('testBtn'))
expect(props.onPress.callCount).toBe(0)
})
})
npmPackages:
@testing-library/react-native: ^7.0.0 => 7.0.0
react: 16.13.1 => 16.13.1
react-native: 0.63.0 => 0.63.0
react-test-renderer: ^16.13.0 => 16.13.1
The "touchable" is disabled, so the handler won't be invoked, hence the error thrown. I think we could improve the wording to be more obvious here.
cc @mdjastrzebski as he also has some thoughts on the topic :)
So what is the correct option here to test a disabled touchable ? Something like
const Button = ({ onPress, isDisabled }) => {
return <TouchableOpacity testID='testBtn' disabled={isDisabled} onPress={isDisabled ? () => {}: onPress} />
}
?
expect(...).toThrowError("No handler function found")
it('onPress does not trigger', () => {
const { getByTestId } = render( <Button onPress={() => console.log('called')}/>)
expect(fireEvent.press(getByTestId('testBtn'))).toThrowError('No handler function found')
})
Still raises an error
Use the .toThrowError() Jest matcher. The expectation must be in a function body so that Jest can try to call it:
expect(() => {
fireEvent.press(getByTestId('testBtn'))
}).toThrowError('No handler function found')
Oh sorry nevermind it works, thanks !
@Andarius I think your original complain is a valid point. So fireEvent throws error when it does not find any matching event handler, which should suggested to the programmer that there is a problem with assertions or components under test.
However the case when there is event handler but is disabled should probably be handled without throwing error.
We've just released 7.0.1 which now doesn't throw. So please adjust your tests to something like this:
fireEvent.press(getByTestId('testBtn'));
expect(handlePress).not.toHaveBeenCalled();
Most helpful comment
@Andarius I think your original complain is a valid point. So
fireEventthrows error when it does not find any matching event handler, which should suggested to the programmer that there is a problem with assertions or components under test.However the case when there is event handler but is disabled should probably be handled without throwing error.