I can not write the correct test case for the button property disable
. I use TestUtils
out react-addons-test-utils
.
I have a very simple component:
const propTypes = {
disabled: PropTypes.func.isRequired
};
class MyComponent extends Component {
constructor(props) {
super(props);
}
render() {
return (
<span>
<button id="my-button" type="submit" disabled={this.props.disabled}>
MyButton
</button>
</span>
);
}
}
MyComponent.propTypes = propTypes;
export default MyComponent;
And I want to write a test that checks if the button with the specified details is disabled or not disabled. And the test is as follows:
describe('MyComponent', () => {
it('should render disabled button when props.disabled is equal to true', () => {
// given
const props = {
disabled: () => true
};
// when
const myComponent = TestUtils.renderIntoDocument(<MyComponent {...props}/>);
// then
const root = ReactDOM.findDOMNode(myComponent);
const myButton = root.querySelector('#my-button');
expect(myButton.disabled).toEqual(true);
});
it('should render enebled button when props.disabled returns false', () => {
// given
const props = {
disabled: () => false
};
// when
const myComponent = TestUtils.renderIntoDocument(<MyComponent {...props}/>);
// then
const root = ReactDOM.findDOMNode(myComponent);
const myButton = root.querySelector('#my-button');
expect(myButton.disabled).toEqual(false);
})
});
And this test implementation does not work. The first test is passed, but the second is unsuccessful.
But when propTypes is set to disabled: false
instead disabled: () => false
, both tests succeed.
The question is, why are the tests successful when the function disabled
is a Boolean constant equal to false and does not work when disabled
is the function that returns false
?
failure test logs:
expect (received) .toEqual (expected)
Expected value to equal:
false
Received:
true
at Object.<anonymous> (__tests__/unit/components/create/MyComponent-test.js:90:37)
at new Promise (<anonymous>)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:118:7)