Reputation: 7969
I am using ref
to get the value of input box. I want to make a test case of search component where it can simulate the onChange event. If I running my handleSearchChange
from test case. it is not able to resolve ref
.
Component
import React,{ Component } from 'react';
import { injectProps } from 'relpers';
import PropTypes from 'prop-types';
export class Search extends Component{
state = {
searchValue: ''
}
handleSearchChange = ()=>{
const { handleInputChange } = this.props;
let searchValue = this.search.value;
this.setState({
searchValue
});
//handleInputChange(searchValue);
}
render(){
let { searchValue } = this.state;
let { placeHolder } = this.props;
return (
<form>
<input
id={'searchInput'}
placeholder={placeHolder}
ref={input => this.search = input}
value={searchValue}
onChange={this.handleSearchChange}
/>
</form>
)
}
}
Search.propTypes = {
placeHolder: PropTypes.string,
handleInputChange: PropTypes.func,
};
Search.defaultProps = {
placeHolder: "Search for order..",
handleInputChange:()=>{}
};
Test case
import React from 'react';
import { shallow } from 'enzyme';
import { Search } from './search';
describe('<Search /> component test cases', ()=>{
it('check if search component render properly',()=>{
const wrapper = shallow(<Search />);
expect(wrapper.find('input')).toHaveLength(1);
});
it('checks if handleSearchChange method works correctly', () => {
const wrapper = shallow(<Search />);
const searchInput = wrapper.find("#searchInput");
searchInput.value = "123456";
searchInput.simulate('change');
expect(wrapper.instance().state.searchValue).toEqual('123456');
});
})
Edited
Checking ref with mount
it('checks if handleSearchChange method works correctly', () => {
const wrapper = mount(<Search />);
const instance = wrapper.instance();
const searchInput = wrapper.find("#searchInput");
searchInput.value = "123456";
searchInput.simulate('change');
expect(wrapper.instance().state.searchValue).toEqual('123456');
});
Upvotes: 0
Views: 2142
Reputation: 5797
shallow
does not appear to support refs
- it looks like you need to use mount
Also, you really don't need to use ref
at all in this situation. You can just use your onChange
handler like so
handleSearchChange = (e) => {
const { handleInputChange } = this.props;
let searchValue = e.target.value;
this.setState({searchValue});
// whatever else you want to do
}
You'll just have to bind this
somewhere, for example in your render method, something like.
<input onChange={this.handleSearchChange.bind(this)} />
Upvotes: 4