Created
December 29, 2015 05:09
-
-
Save kylekellogg/ec9800ed368f1172c65d to your computer and use it in GitHub Desktop.
ES2015 React JS Component classes can pass React's TestUtils tests (using Jest in my case) while not working in a practical implementation. Here's an example of what to do and what not to do.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
/* | |
This will happily pass your tests (via TestUtils), but will not work when | |
implemented in a real-world scenario (via browserify & babelify with es2015 | |
and react presets, for example) | |
*/ | |
export class CheckboxWithLabel extends React.Component { | |
constructor (props) { | |
super(props) | |
this.state = {isChecked: false} | |
} | |
onChange () { | |
this.setState({isChecked: !this.state.isChecked}) | |
} | |
render () { | |
return ( | |
<label> | |
<input type='checkbox' checked={this.state.isChecked} onChange={this.onChange.bind(this)} /> | |
{this.state.isChecked ? this.props.labelOn : this.props.labelOff} | |
</label> | |
) | |
} | |
} | |
CheckboxWithLabel.propTypes = { | |
labelOn: React.PropTypes.string, | |
labelOff: React.PropTypes.string | |
} | |
CheckboxWithLabel.defaultProps = { | |
labelOn: 'On', | |
labelOff: 'Off' | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
/* | |
This will pass your tests (via TestUtils) and will also work when implemented | |
in a real-world scenario (via browserify & babelify with es2015 and react | |
presets, for example) | |
*/ | |
class CheckboxWithLabel extends React.Component { | |
constructor (props) { | |
super(props) | |
this.state = {isChecked: false} | |
} | |
onChange () { | |
this.setState({isChecked: !this.state.isChecked}) | |
} | |
render () { | |
return ( | |
<label> | |
<input type='checkbox' checked={this.state.isChecked} onChange={this.onChange.bind(this)} /> | |
{this.state.isChecked ? this.props.labelOn : this.props.labelOff} | |
</label> | |
) | |
} | |
} | |
CheckboxWithLabel.propTypes = { | |
labelOn: React.PropTypes.string, | |
labelOff: React.PropTypes.string | |
} | |
CheckboxWithLabel.defaultProps = { | |
labelOn: 'On', | |
labelOff: 'Off' | |
} | |
/* | |
This is the important bit: export default <ClassName> instead of | |
export class <ClassName> | |
*/ | |
export default CheckboxWithLabel |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment