Last active
September 11, 2017 09:12
-
-
Save koba04/4821249eb50882eee54a27b624cabd36 to your computer and use it in GitHub Desktop.
A React TestRenderer Sample
This file contains 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
const React = require('react'); | |
const TestRenderer = require('react-test-renderer'); | |
const Child = props => <div>{props.children}</div>; | |
const Counter = props => <div>{props.count}</div>; | |
class App extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
count: 0 | |
}; | |
} | |
componentDidMount() { | |
if (this.button) this.button.focus(); | |
} | |
render() { | |
return ( | |
<section> | |
<div>bar</div> | |
<Child><p>Hello</p></Child> | |
<div>bar</div> | |
<button | |
ref={el => this.button = el} | |
onClick={() => this.setState({count: this.state.count + 1})} | |
> | |
++ | |
</button> | |
<Counter count={this.state.count} /> | |
</section> | |
); | |
} | |
} | |
const root = TestRenderer.create(<App />).root; | |
// find a component by Type | |
console.assert(root.find(node => node.type === Child).props.children.type === 'p'); | |
// find a component by Props | |
console.assert(root.findByProps({children: 'Hello'}).type === 'p'); | |
// find all components by Type | |
console.assert(root.findAllByType('div').length === 4); | |
// initial state | |
const instance = root.instance; | |
console.assert(root.findByType(Counter).props.count === 0); | |
console.assert(instance.state.count === 0); | |
// click the button | |
const button = root.findByType('button').props.onClick(); | |
console.assert(root.findByType(Counter).props.count === 1); | |
console.assert(instance.state.count === 1); | |
// setState directly | |
instance.setState({count: instance.state.count + 1}); | |
console.assert(root.findByType(Counter).props.count === 2); | |
console.assert(instance.state.count === 2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment