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:
data-test-id
for <button>
element<Click />
component and then select the button within(...)
this scopefireEvent
and check that nothing has happenedCan you suggest a better approach?
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();