How to assert that a button is disabled in React Native Testing Library?
Asked Answered
P

2

8

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.

Peccant answered 5/11, 2020 at 11:33 Comment(3)
.toHaveAttribute('disabled')?Insurgent
@Insurgent Thanks for pointing me in the right direction. The correct method is toHaveProp.Peccant
At the end I've found out that there is .toBeDisabled indeed. Doc: github.com/testing-library/jest-native#tobedisabledPeccant
D
3

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}
  />
)
Deliquescence answered 14/3, 2021 at 9:23 Comment(1)
this solution for some reason doesn't work in react native... it still says that the function was called once and still changes the variable state to trueSouthernmost
O
0

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);
});
Oligarchy answered 19/6, 2022 at 4:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.