我有这个与create-react-app一起使用的组件,我想用玩笑/酶测试以下功能。
(在输入中按下向上/向下箭头时将触发handleArrow函数)
import React, {Component} from 'react';
import './styles.scss';
import Results from '../Results';
import ContextualSearchService from '../../services/contextualSearch';
class Search extends Component {
constructor(props) {
super(props);
this.state = {
searchInput: '',
onInput: false,
searchResults: [],
searchService: new ContextualSearchService(),
filteredSearch: [],
fetching: false,
};
this.handleSearch = this.handleSearch.bind(this);
this.sendSearch = this.sendSearch.bind(this);
this.selectSuggestion = this.selectSuggestion.bind(this);
this.handleFocus = this.handleFocus.bind(this);
this.handleBlur = this.handleBlur.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
this.handleArrow = this.handleArrow.bind(this);
}
handleSearch(e) {
this.setState({
searchInput: e.target.value,
fetching: true,
});
}
handleFocus() {
this.setState({onInput: true});
}
handleKeyDown(e) {
if (e.keyCode === 38 || e.keyCode === 40) {
this.handleArrow(e.keyCode);
}
this.handleFocus();
if (e.key === 'Enter' && this.state.searchInput !== '') {
const selected = document
.getElementsByClassName('search__dropdown-option--selected')[0];
if (selected) {
this.setState({searchInput: selected.innerText}, () =>{
this.sendSearch();
this.handleBlur();
});
} else {
this.sendSearch();
this.handleBlur();
}
}
}
handleArrow(e) {
const list = document.getElementsByClassName('search__dropdown')[0];
const len = document
.getElementsByClassName('search__dropdown-option').length;
const arr = Array.from(document
.getElementsByClassName('search__dropdown-option'));
let selected = document
.getElementsByClassName('search__dropdown-option--selected')[0];
let index = arr.indexOf(selected);
let next = null;
if (index === -1 && list) {
index = 0;
selected = list.getElementsByClassName('search__dropdown-option')[0];
selected.classList.add('search__dropdown-option--selected');
} else if (e === 40 && list) {
if (selected) {
index++;
selected.classList.remove('search__dropdown-option--selected');
next = list.getElementsByClassName('search__dropdown-option')[index];
if (next !== undefined && index <= len) {
selected = next;
} else {
index = 0;
selected = list.getElementsByClassName('search__dropdown-option')[0];
selected.classList.add('search__dropdown-option--selected');
}
selected.classList.add('search__dropdown-option--selected');
}
} else if (e === 38 && list) {
if (selected) {
index--;
selected.classList.remove('search__dropdown-option--selected');
next = list.getElementsByClassName('search__dropdown-option')[index];
if (next !== undefined && index >= 0) {
selected = next;
} else {
index = len - 1;
selected = list
.getElementsByClassName('search__dropdown-option')[index];
selected.classList.add('search__dropdown-option--selected');
}
selected.classList.add('search__dropdown-option--selected');
}
}
}
handleBlur() {
setTimeout(() => {
this.setState({onInput: false});
}, 100);
}
sendSearch() {
this.state.searchService.getSearch(this.state.searchInput)
.then((res)=>{
this.setState({
searchResults: res,
fetching: false,
});
});
}
selectSuggestion(term) {
this.setState({
searchInput: term,
}, () => {
this.sendSearch();
});
}
render() {
const activeInput = this.state.onInput;
const term = this.state.searchInput;
if (this.state.fetching && term !== '') {
this.state.searchService.getSuggestions(term)
.then((res)=>{
this.setState({
filteredSearch: res,
fetching: false,
});
});
}
return (
<div>
<div className="search-row">
<div className="search-wrapper container">
<div className="search">
<input type="text"
className="search__input"
value={this.state.searchInput}
onChange={this.handleSearch}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
onKeyDown={this.handleKeyDown}
placeholder="Buscar..."/>
{
(term !== '' && activeInput &&
this.state.filteredSearch.length > 0) &&
<div className="search__dropdown">
{
this.state.filteredSearch.map((obj, i)=>{
return (
<div key={i}
onClick={()=>this.selectSuggestion(obj)}
className="search__dropdown-option">{obj}
</div>
);
})
}
</div>
}
</div>
<button className="btn btn-search" onClick={this.sendSearch}>
<svg xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24">
<path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16
5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59
4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5
11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z">
</path>
</svg>
</button>
</div>
</div>
{
this.state.searchResults.length > 0 &&
<Results results={this.state.searchResults}></Results>
}
</div>
);
}
}
export default Search;
到目前为止,我已经尝试过:
it('should work', () => {
const dropdown = global.document.createElement('div');
const option = global.document.createElement('div');
const selected = global.document.createElement('div');
dropdown.classList.add('search__dropdown');
option.classList.add('search__dropdown-option');
selected.classList.add('search__dropdown-option--selected');
global.document.body.appendChild(dropdown);
dropdown.appendChild(option);
dropdown.appendChild(selected);
jest.useFakeTimers();
const comp = mount(<Search/>);
comp.setState({
fetching: true,
searchInput: 'the',
onInput: true,
searchResults: data,
filteredSearch: filtered,
});
comp.setState({searchInput: 'the'});
comp.find('.search__input').simulate('keydown', {key: 'Enter'});
comp.find('.search__dropdown-option').at(0).simulate('click');
jest.runAllTimers();
comp.unmount();
});
运行测试时,“ index”变量始终为-1(我不理解,因为我只是在DOM中附加了所需的元素)。
问题似乎出在let index = arr.indexOf(selected);
行
在React中还有其他更好的方法来处理此类的类和DOM元素吗?
谢谢。
答案 0 :(得分:1)
您是否有理由在组件中使用JavaScript DOM选择器而不是在React组件中这样做?如果您不熟悉,可以直接在React组件中完成此功能。这里以您现有的代码并在state中添加selectedIndex,以便您可以将其设置为state并通过添加的修饰符类拥有适当的元素...
export default class Search extends Component {
constructor(props) {
super(props);
this.state = {
fetching: false,
filteredSearch: [],
onInput: false,
searchInputValue: '',
searchResults: [],
searchService: new ContextualSearchService(),
selectedIndex: null,
selectedValue: null,
};
this.handleSearch = this.handleSearch.bind(this);
this.sendSearch = this.sendSearch.bind(this);
this.selectSuggestion = this.selectSuggestion.bind(this);
this.handleFocus = this.handleFocus.bind(this);
this.handleBlur = this.handleBlur.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
this.handleArrow = this.handleArrow.bind(this);
}
handleSearch(e) {
this.setState({
searchInput: e.target.value,
fetching: true,
});
}
handleFocus() {
this.setState({onInput: true});
}
handleKeyDown(e) {
const {selectedIndex, selectedValue} = this.state;
const {keyCode} = e;
if (keyCode === 38 || keyCode === 40) {
this.handleArrow(keyCode);
}
this.handleFocus();
if (e.key === 'Enter' && this.state.searchInput !== '') {
if (selectedIndex > 0) {
this.setState({searchInput: selectedValue}, () => {
this.sendSearch();
this.handleBlur();
});
} else {
this.sendSearch();
this.handleBlur();
}
}
}
handleArrow(keyCode) {
const {selectedIndex, filteredSearch} = this.state;
const filteredSearchLength = filteredSearch.length;
let newSelectedIndex;
if (keyCode === 38) {
newSelectedIndex = (this.state.selectedIndex === 0)
? filteredSearchLength - 1
: selectedIndex - 1;
} else {
newSelectedIndex = (selectedIndex + 1 === filteredSearchLength)
? 0
: selectedIndex + 1;
}
this.setState({selectedIndex: newSelectedIndex});
}
handleBlur() {
setTimeout(() => {
this.setState({onInput: false});
}, 100);
}
sendSearch() {
this.state.searchService.getSearch(this.state.searchInput)
.then((res)=>{
this.setState({
searchResults: res,
fetching: false,
});
});
}
selectSuggestion(term, i) {
this.setState({
searchInput: term,
selectedIndex: i,
}, () => {
this.sendSearch();
});
}
render() {
const activeInput = this.state.onInput;
const term = this.state.searchInput;
if (this.state.fetching && term !== '') {
this.state.searchService.getSuggestions(term)
.then((res) => {
this.setState({
filteredSearch: res,
fetching: false,
});
});
}
return (
<div>
<div className="search-row">
<div className="search-wrapper container">
<div className="search">
<input type="text"
className="search__input"
value={this.state.searchInput}
onChange={this.handleSearch}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
onKeyDown={this.handleKeyDown}
placeholder="Buscar..."/>
{
(term !== '' && activeInput &&
this.state.filteredSearch.length > 0) &&
<div className="search__dropdown">
{
this.state.filteredSearch.map((obj, i) => {
// Or you could use that classnames library I suggested here
const className = (i === this.state.selectedIndex)
? 'search__dropdown-option'
: 'search__dropdown-option search__dropdown-option--selected';
return (
<div key={i}
onClick={() => this.selectSuggestion(obj, i)}
className={className}>{obj}
</div>
);
})
}
</div>
}
</div>
<button className="btn btn-search" onClick={this.sendSearch}>
<svg xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24">
<path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16
5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59
4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5
11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z">
</path>
</svg>
</button>
</div>
</div>
{
this.state.searchResults.length > 0 &&
<Results results={this.state.searchResults}></Results>
}
</div>
);
}
}
但是,我建议将您的组件分解一些,以免用时长,并为您的下拉选项添加一个类似这样的新组件...
import React, {Component} from 'react';
import classnames from 'classnames';
class DropDownOptions extends Component {
getClass() {
return classnames({
'dropdown-option': true,
'drowndown-option--selected': this.props.selected
});
}
handleClick() {
this.props.onClick(this.props.value, this.props.selectedIndex)
}
render() {
return (
<div className={this.getClass()} onClick={this.handleClick}>{this.props.children}</div>
);
}
}
classnames是一个节点模块,用于修改元素中的类,但是您可以像在修改后的代码中那样在其中构建自己的功能。
自从您在原始问题中询问测试以来,还有最后一件事,这是一个有关如何使用笑话进行测试的小例子。我强烈建议您仔细研究一些文档,并检查酶。
import Search from '../Search';
describe('Search', () => {
it('should render', () => {
const wrapper = shallow(<Search />);
expect(wrapper).toMatchSnapshot();
});
it('should set selected dropdown', () => {
const wrapper = shallow(<Search />);
const wrapperInstance = wrapper.instance();
wrapper.setState({
filteredSearch: ['a', 'b', 'c'],
selectedIndex: 0,
});
expect(wrapper).toMatchSnapshot();
wrapperInstance.handleArrow(38);
expect(wrapperInstance.state.selectedIndex).toBe(2);
wrapperInstance.handleArrow(40);
expect(wrapperInstance.state.selectedIndex).toBe(0)
});
});
答案 1 :(得分:0)
我遵循了布鲁斯·史密斯(Bruce Smith)的建议,结束了简化代码并仅使用状态的方法:
class Search extends Component {
constructor(props) {
super(props);
this.state = {
searchInput: '',
onInput: false,
searchResults: [],
searchService: new ContextualSearchService(),
filteredSearch: [],
fetching: false,
dropdownIndex: 0,
};
this.handleSearch = this.handleSearch.bind(this);
this.sendSearch = this.sendSearch.bind(this);
this.selectSuggestion = this.selectSuggestion.bind(this);
this.handleFocus = this.handleFocus.bind(this);
this.handleBlur = this.handleBlur.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
this.handleArrow = this.handleArrow.bind(this);
this.getDropdownClass = this.getDropdownClass.bind(this);
}
handleSearch(e) {
this.setState({
searchInput: e.target.value,
fetching: true,
});
}
handleFocus() {
this.setState({onInput: true});
}
handleKeyDown(e) {
if (e.keyCode === 38 || e.keyCode === 40) {
this.handleArrow(e.keyCode);
}
this.handleFocus();
if (e.key === 'Enter' && this.state.searchInput !== '') {
const selected = this.state.filteredSearch[this.state.dropdownIndex];
if (selected) {
this.setState({searchInput: selected}, () =>{
this.sendSearch();
this.handleBlur();
});
} else {
this.sendSearch();
this.handleBlur();
}
}
}
handleArrow(e) {
const len = this.state.filteredSearch.length;
if (e === 40) {
this.setState({
dropdownIndex: this.state.dropdownIndex+1,
}, () => {
if (this.state.dropdownIndex >= len) {
this.setState({dropdownIndex: 0});
}
});
}
if (e === 38) {
this.setState({
dropdownIndex: this.state.dropdownIndex-1,
}, () => {
if (this.state.dropdownIndex <= 0) {
this.setState({dropdownIndex: len-1});
}
});
}
}
handleBlur() {
setTimeout(() => {
this.setState({onInput: false});
}, 100);
}
sendSearch() {
this.state.searchService.getSearch(this.state.searchInput)
.then((res)=>{
this.setState({
searchResults: res,
fetching: false,
});
});
}
selectSuggestion(term) {
this.setState({
searchInput: term,
}, () => {
this.sendSearch();
});
}
getDropdownClass(index) {
if (index === this.state.dropdownIndex) {
return 'search__dropdown-option search__dropdown-option--selected';
} else {
return 'search__dropdown-option';
}
}
render() {
const activeInput = this.state.onInput;
const term = this.state.searchInput;
if (this.state.fetching && term !== '') {
this.state.searchService.getSuggestions(term)
.then((res)=>{
this.setState({
filteredSearch: res,
fetching: false,
});
});
}
return (
<div>
<div className="search-row">
<div className="search-wrapper container">
<div className="search">
<input type="text"
className="search__input"
value={this.state.searchInput}
onChange={this.handleSearch}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
onKeyDown={this.handleKeyDown}
placeholder="Buscar..."/>
{
(term !== '' && activeInput &&
this.state.filteredSearch.length > 0) &&
<div className="search__dropdown">
{
this.state.filteredSearch.map((obj, i)=>{
return (
<div key={i}
onClick={()=>this.selectSuggestion(obj)}
className={this.getDropdownClass(i)}>{obj}
</div>
);
})
}
</div>
}
</div>
<button className="btn btn-search" onClick={this.sendSearch}>
<svg xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24">
<path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16
5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59
4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5
11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z">
</path>
</svg>
</button>
</div>
</div>
{
this.state.searchResults.length > 0 &&
<Results results={this.state.searchResults}></Results>
}
</div>
);
}
}
export default Search;