以下是我的组件,我需要测试if
和componentDidMount
中的componentWillUnmount
条件。我能够为componentDidMount
编写测试用例,但是在componentDidMount
内使用if进行测试。任何指针都会对我有帮助。
代码-
class TestComponent extends React.Component {
constructor(props) {
super(props);
this.element = React.createRef();
}
componentDidMount() {
const scrollableContainer = this.element.current;
if (scrollableContainer) {
scrollableContainer.addEventListener('scroll', this.handleScroll);
}
this.getUserData();
}
componentWillUnmount() {
const scrollableContainer = this.element.current;
if (scrollableContainer) {
scrollableContainer.removeEventListener('scroll', this.handleScroll);
}
}
handleScroll = () => {
console.log(`Event Firing`);
}
render() {
return (
<div className="container">
<div className="basic-info">
<p>Dummy Text Basic 1</p>
<p>Dummy Text Basic 2</p>
<p>Dummy Text Basic 3</p>
<p>Dummy Text Basic 4</p>
</div>
<div className="advance-info" ref={this.element}>
<p>Dummy Text Advance 1</p>
<p>Dummy Text Advance 2</p>
<p>Dummy Text Advance 3</p>
<p>Dummy Text Advance 4</p>
<p>Dummy Text Advance 5</p>
<p>Dummy Text Advance 6</p>
<p>Dummy Text Advance 7</p>
<p>Dummy Text Advance 8</p>
</div>
</div>
)
}
}
componentDidMount的测试用例-
it('should test componentDidMount for handling scroll Event', () => {
const component = shallow(<TestComponent {...props} />);
const funcSpy = jest.spyOn(component.instance(), 'getUserData');
component.instance().componentDidMount();
expect(funcSpy).toHaveBeenCalled();
});