我正在使用ref
来获取输入框的值。我想做一个搜索组件的测试用例,它可以模拟onChange事件。如果我从测试用例中运行handleSearchChange
。它无法解析ref
。
组件
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:()=>{}
};
测试用例
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');
});
})
已编辑
通过安装检查参考
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');
});
答案 0 :(得分:2)
shallow
似乎不支持refs
-看来您需要使用mount
在这种情况下,您实际上根本不需要使用ref
。您可以像这样使用onChange
处理程序
handleSearchChange = (e) => {
const { handleInputChange } = this.props;
let searchValue = e.target.value;
this.setState({searchValue});
// whatever else you want to do
}
您只需要将this
绑定到某个地方,例如在您的render方法中,例如。
<input onChange={this.handleSearchChange.bind(this)} />