I am giving Jest/Enzyme a try, and am having trouble with a simple example I am trying to create.
I have a small component with an input that should update the text of a DIV. I want to write a test proving the DIV got updated.
My test is simply this:
const app = shallow(<App {...state} />);
const input = app.find('input');
input.simulate('keyDown', {keyCode: 72});
input.simulate('keyDown', {keyCode: 73});
input.simulate('change', {target: input});
expect(app.find('[test="mirror"]').text()).toEqual('hi');
I know that the input is actually returning a ShallowWrapper
. You can see in my component below, I am updating state by looking at e.target.value
. Is there a way to pass the actual DOM node to my simulation of change
? Will simulating the keyDown actually update the input value? Or should I do that a different way?
import React from 'react'
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
mirror: ''
};
this.updateMirror = this.updateMirror.bind(this);
}
updateMirror(e) {
let val = e.target.value;
this.setState((prevState, props) => {
return {
mirror: val
};
});
}
render() {
return <div>
<div><input type="text" onChange={this.updateMirror} /></div>
<div test="mirror">{this.state.mirror}</div>
</div>
}
}
export default App
Testing text input is relatively simple. First mount the component with Enzyme’s mount function, then set the value and simulate the change. When there are multiple input fields, we can use .at (0) to find the input element by index. For checkbox, assign the value for checked instead of value and then simulate change.
First mount the component with Enzyme’s mount function, then set the value and simulate the change. When there are multiple input fields, we can use .at (0) to find the input element by index. For checkbox, assign the value for checked instead of value and then simulate change.
When using Jest and Enzyme, unit testing with snapshots can proceed in the following order. Step 1. Write test for the component and in the expect block, use .toMatchSnapshot () method that creates Snapshot itself. view raw (Create snapshot for TextInput components) TextInput.test.js hosted with ❤ by GitHub Step 2.
Here is the main Form component to be tested. Testing text input is relatively simple. First mount the component with Enzyme’s mount function, then set the value and simulate the change. When there are multiple input fields, we can use .at (0) to find the input element by index.
Try something like this :
const wrapper = shallow(<App {...state} />);
wrapper.find('input').simulate('change', {target: {value: 'Your new Value'}});
expect(wrapper.state('mirror')).toBe('Your new Value');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With