我对React还是很陌生,想测试模拟组件上的更改事件。流程如下:
这似乎很基础,但是我尝试了几种方法对其进行测试-但没有一种有效。我非常感谢关于如何在React中进行这种类型的测试的任何建议或指示。
代码工作正常,但我希望能够对其进行测试。这是我要测试的(正在进行中的)代码的简化版本:
import React, {Component} from 'react';
import '../search_option/SearchOption';
import SearchOption from "../search_option/SearchOption";
class AccessibleGlobalSearch extends Component {
constructor(props) {
super(props);
this.handle_search_selection = this.handle_search_selection.bind(this);
this.state = {
active_search_url: '/site_search/results',
select_type: 'Select a search type',
website_search_url: '/site_search/results',
catalogue_search_url: '/catalogue_search/results/',
search_options: {
group_name: 'search_type',
options: [
{
label: 'Search Catalogue',
id: 'catalogue_search'
},
{
label: 'Search the website',
id: 'website_search'
}
]
}
}
}
handle_search_selection(e) {
if(e.target.id === 'catalogue_search') {
this.setState({active_search_url: this.state.discovery_search_url});
}
if(e.target.id === 'website_search') {
this.setState({active_search_url: this.state.website_search_url});
}
}
render() {
return (
<form className="global-search-js" action={this.state.active_search_url} onChange={this.handle_search_selection}>
<fieldset>
<legend>{this.state.select_type}</legend>
<SearchOption group_name={this.state.search_options.group_name} options={this.state.search_options.options}/>
</fieldset>
</form>
);
}
}
export default AccessibleGlobalSearch;
这是我一直在测试它的方法之一
import React from 'react';
import ReactDOM from 'react-dom';
import TestRenderer from 'react-test-renderer';
import ReactTestUtils from 'react-dom/test-utils';
import AccessibleGlobalSearch from './AccessibleGlobalSearch';
const test_renderer = TestRenderer.create(<AccessibleGlobalSearch/>);
const test_instance = test_renderer.root;
const instance = test_renderer.getInstance();
it('changes the form action to when that option is selected', () => {
const rendered_component = test_renderer.toJSON();
expect(rendered_component.props.action).toBe('/site_search/results');
const form = test_instance.findByType('form');
ReactTestUtils.Simulate.change(form, {"target": {"id": "catalogue_search", "checked": true}});
expect(instance.state.active_search_url).toBe('catalogue_search/results/');
});