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.

3
  • .toHaveAttribute('disabled')? Commented Nov 5, 2020 at 11:42
  • @jonrsharpe Thanks for pointing me in the right direction. The correct method is toHaveProp. Commented Nov 5, 2020 at 14:17
  • 1
    At the end I've found out that there is .toBeDisabled indeed. Doc: github.com/testing-library/jest-native#tobedisabled Commented Nov 5, 2020 at 14:25

2 Answers 2

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}
  />
)
Sign up to request clarification or add additional context in comments.

1 Comment

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 true
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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.