How can I assert that a button is disabled in React Native Testing Library? I would imagine something like:
expect(getByRole('button')).toBeDisabled()
but RNTL doesn't provide toBeDisabled
assertion.
How can I assert that a button is disabled in React Native Testing Library? I would imagine something like:
expect(getByRole('button')).toBeDisabled()
but RNTL doesn't provide toBeDisabled
assertion.
this is a common issue due to RN nature. I have managed to reach my goal by just testing the actual effect of callback function, not just comparing the number of calls or something like that...
describe('<Button /> - ', () => {
let state = false
const onPressMock = jest.fn(() => {
state = !state
})
const props: ButtonProps = {
text: 'Submit',
onPress: onPressMock
}
it('should become disabled', () => {
// act: render container
const { container } = render(<Button {...props} isDisabled />)
// assert 1: check if button receives {isDisabled}
expect(container.props.isDisabled).toEqual(true)
// act2: fire callback
fireEvent(container, 'onPress')
// assert 2: "state" should remain as false.
expect(state).toEqual(false)
})
})
make sure that your button looks like:
const isBlockedInteraction: boolean = isLoading || isDisabled;
return (
<TouchableOpacity
onPress={!isBlockedInteraction && onPress}
disabled={isBlockedInteraction}
{...props}
/>
)
state
to true
–
Southernmost Quite a simple try toHaveProperty
method, I hope that helped.
example:
import React from 'react'
import {fireEvent, render} from '@testing-library/react-native';
import {SignInScreen} from './SignInScreen';
it('disabled button if email and password are empty', () => {
const screen = render(<SignInScreen />);
const button = screen.getByText('Login');
// screen.debug();
// console.log(button.props);
expect(button.props).toHaveProperty('disabled', true);
});
© 2022 - 2024 — McMap. All rights reserved.
.toHaveAttribute('disabled')
? – InsurgenttoHaveProp
. – Peccant.toBeDisabled
indeed. Doc: github.com/testing-library/jest-native#tobedisabled – Peccant