Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check that button is disabled in react-testing-library

I have a React component that generates a button whose content contains a <span> element like this one:

function Click(props) {
    return (
        <button disable={props.disable}>
            <span>Click me</span>
        </button>
    );
}

I want to test the logic of this component with the use of react-testing-library and mocha + chai.

The problem at which I stuck at the moment is that the getByText("Click me") selector returns the <span> DOM node, but for the tests, I need to check the disable attribute of the <button> node. What is the best practice for handling such test cases? I see a couple of solutions, but all of them sound a little bit off:

  1. Use data-test-id for <button> element
  2. Select one of the ancestors of the <Click /> component and then select the button within(...) this scope
  3. Click on the selected element with fireEvent and check that nothing has happened

Can you suggest a better approach?

like image 873
Nikita Sivukhin Avatar asked Jun 14 '19 07:06

Nikita Sivukhin


People also ask

How do I enable the disabled button in React?

Use the disabled prop to disable a button in React, e.g. <button disabled={true}>Click</button> . You can use the prop to conditionally disable the button based on the value of an input field or another variable or to prevent multiple clicks to the button. Copied!


2 Answers

Assert if button is disabled

You can use the toHaveAttribute and closest to test it.

import { render } from '@testing-library/react';  const { getByText } = render(Click); expect(getByText(/Click me/i).closest('button')).toHaveAttribute('disabled'); 

or toBeDisabled

expect(getByText(/Click me/i).closest('button')).toBeDisabled(); 

Assert if button is enabled

To check if the button is enabled, use not as follows

expect(getByText(/Click me/i).closest('button')).not.toBeDisabled(); 
like image 169
johnny peter Avatar answered Sep 22 '22 11:09

johnny peter


You can use toBeDisabled() from @testing-library/jest-dom, it is a custom jest matcher to test the state of the DOM:

https://github.com/testing-library/jest-dom

Example:

<button>Submit</button>
expect(getByText(/submit/i)).toBeDisabled()
like image 43
Meysam Izadmehr Avatar answered Sep 20 '22 11:09

Meysam Izadmehr