Last active
February 4, 2016 13:22
-
-
Save camjackson/920ec45e1fb33552db9c to your computer and use it in GitHub Desktop.
Better example of testing interaction in a React.js component
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
| /* | |
| I think this is a better example of interaction testing, because the component has its own | |
| internal function, which a) does more than one thing, and b) has a small amount of logic | |
| where it plucks the new value out of the DOM event. Those we can test in isolation. | |
| */ | |
| const MyInput = props => { | |
| const handleChange = event => { | |
| props.updateTheValue(event.target.value); | |
| props.fetchSomeDataThatDependsUponTheValue(); | |
| }; | |
| return <input type="text" onChange={handleChange} value={props.value}/>; | |
| } | |
| MyInput.propTypes = { | |
| value: React.PropTypes.string.isRequired, | |
| updateTheValue: React.PropTypes.func.isRequired, | |
| fetchSomeDataThatDependsUponTheValue: React.PropTypes.func.isRequired | |
| } | |
| describe('MyInput', () => { | |
| it('emits the new value when it changes, and causes a fetch of some data that depends upon the new value', () => { | |
| const updater = jasmine.createSpy(); | |
| const fetcher = jasmine.createSpy(); | |
| const myInput = shallowRender(<MyInput updateTheValue={updater} fetchSomeDataThatDependsUponTheValue={fetcher}/>); | |
| myInput.props.onChange({ target: { value: 'new value!' } }); | |
| expect(updater).toHaveBeenCalledWith('new value!'); | |
| expect(fetcher).tohaveBeenCalled(); | |
| }); | |
| }); | |
| /* | |
| Where the example potentially expands even further, is if the component's internal function | |
| only calls the callback props under certain conditions. E.g. you might have a handleBlur | |
| inside the component, which can check if the value has actually changed, and will only call | |
| a callback if it has. You could test that by reaching into the props and manually calling | |
| onBlur with different event values, and check whether or not the input callbacks are invoked. | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for clarifying the shallow rendering part, then all is good :). This would actually have the test on the "level" I think I want them.