如何测试componentDidMount和componentWillUnmount内部的条件?

时间:2019-06-24 08:11:48

标签: javascript reactjs unit-testing jestjs enzyme

以下是我的组件,我需要测试ifcomponentDidMount中的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();

});

0 个答案:

没有答案