我有一个标签React组件,我正在使用Enzyme和Jest进行测试。
这是组件:
class TabbedArea extends React.Component{
constructor(props) {
super(props)
this.handleClick = this.handleClick.bind(this);
this.state = {
activeIndex: this.props.activeIndex || 0
};
}
componentWillReceiveProps(nextProps){
if (this.state.activeIndex !== nextProps.activeIndex) {
this.setState({
activeIndex: nextProps.activeIndex
});
}
}
handleClick(index, e) {
e.preventDefault();
this.setState({
activeIndex: index
});
}
tabNodes() {
return (_.map(this.props.children, (child, index) => {
let className = classNames({'active': this.state.activeIndex === index});
return (
<li key={index} onClick={(e) => this.handleClick(index, e)}>
<a className={className} href="#">{child.props.display}</a>
</li>
)
}
)
)
}
contentNodes() {
return (
_.map(this.props.children, (child, index) => {
if(this.state.activeIndex === index) {
return (
<div className="TabPane" key={index}>
{child.props.children}
</div>
)
}
}
)
)
}
render() {
return (
<div className={`${styles.ParcelResultsTrackingHistory} col-md-12`}>
<ul className="nav nav-tabs" id="navTabs">
{this.tabNodes()}
</ul>
<section>
{this.contentNodes()}
</section>
</div>
);
}
}
export default TabbedArea;
这是我的测试:
describe('Given the Tabbed Area component is rendered', () => {
describe('Initial Snapshots', () => {
let component
beforeEach(() => {
component = shallow(<TabbedArea />)
})
it('should be as expected', () => {
expect(shallowToJson(component)).toMatchSnapshot()
})
})
describe('I click on the second tab', () => {
let component
let tab2
component = shallow(<TabbedArea/>)
tab2 = component.find('ul li').at(1);
tab2.simulate('click');
describe('the content of the second tab is rendered', () => {
component.update();
it('should match the snapshot', () => {
expect(shallowToJson(component)).toMatchSnapshot()
});
});
});
describe('Clicking on the tab', () => {
const wrapper = mount(<TabbedArea/>)
const handleClick = jest.spyOn(wrapper.instance(), 'handleClick');
wrapper.update();
const tab = wrapper.find('ul#navTabs li').first()
tab.simulate('click')
it('will call handleClick', () => {
expect(handleClick).toBeCalled();
});
});
})
快照测试运行正常但是当我尝试测试handleClick
它失败时:Method “simulate” is only meant to be run on a single node. 0 found instead.
知道为什么找不到节点?我已经尝试通过id找到li
,但得到了相同的错误。
感谢
答案 0 :(得分:0)
不是因为你正在渲染没有孩子的<TabbedArea>
。 tabNodes
方法在this.props.children
上循环,在您的测试中为空。