gpt4 book ai didi

reactjs - 单元测试 : How to mock document. getElementsByClassName() react ?

转载 作者:行者123 更新时间:2023-11-28 21:19:30 24 4
gpt4 key购买 nike

我有这个组件是用 create-react-app 做的,我想用 jest/enzyme 测试以下功能。

(在输入中按下向上/向下箭头时触发函数 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();
});

当我运行测试时,“索引”变量始终为 -1(这是我不理解的,因为我只是在 DOM 中附加了所需的元素)。

看来问题出在行 let index = arr.indexOf(selected);

是否有另一种更好的方法来处理像这样的类和 DOM 元素?

提前致谢。

最佳答案

你在组件中使用 javascript DOM 选择器而不是在 React 组件中这样做有什么原因吗?如果您不熟悉,可以直接在 React 组件中完成此功能。这里采用您现有的代码并在状态中添加 selectedIndex,这样您就可以在状态中设置它并使用添加的修饰符类拥有适当的元素...

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 是一个节点模块,用于修改元素中的类,但您可以在那里构建自己的功能,就像我在修改的代码中所做的那样。

自从您在原始问题中询问有关测试的最后一件事,这里有一个关于如何用 Jest 测试它的小示例。我强烈建议您阅读一些 Jest 文档,并查看 enzyme 。

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)
});
});

关于reactjs - 单元测试 : How to mock document. getElementsByClassName() react ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53566077/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com