【问题标题】:enzyme mount fails when there is a function call in the componentDidMountcomponentDidMount 中有函数调用时酶挂载失败
【发布时间】:2018-07-21 03:04:04
【问题描述】:

我有一个反应组件,里面有一个点击功能,如下所示:

    clickTwitter(e) {

    e.stopPropagation();
    let storyId = this.refs.storyToTweet.getAttribute('id');
    if (storyId != undefined) {
        let storyIdValue = this.props.storyId;
        this.postOnTwitter(storyIdValue);
    }
}

在 componentDidMount 我有以下内容:

    componentDidMount(){
    this.fbInit();
}

fbInit(){
    return facebookInitializer= function(d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id;
        js.src = `https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.12&appId=${FACEBOOK.appId}&autoLogAppEvents=1`;
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk');

}

我有以下测试用例:

        it('should call the clickTwitter method once', () => {
        // creates the spy for the clickTwitter method
        let clickTwitterSpy = sinon.spy(StoryMedia.prototype, 'clickTwitter');
        let props={

        }
        // wraps the component by using the enzyme mount method
        const wrapper = mount(<StoryMedia/>);

        // simulates a user clicking the twitter button
        wrapper.find('.shareTwitterDummy').simulate('click');
        // asserts that the clickTwitter method was called once when the button was clicked
        assert.strictEqual(StoryMedia.prototype.clickTwitter.calledOnce, true);
        // restores the method to its original state
        clickTwitterSpy.restore();
    });

当我运行测试时,我收到以下奇怪的错误:

TypeError: Cannot read property 'parentNode' of undefined....

如果我删除 this.fbInit();从 componentDidMount 一切正常。 无论如何我可以告诉测试忽略 this.fbInit() 吗?或任何其他解决方案表示赞赏

【问题讨论】:

    标签: reactjs mocha.js sinon enzyme


    【解决方案1】:

    我认为var js, fjs = d.getElementsByTagName(s)[0]; fjs 是undefined

    【讨论】:

    • 如何避免?
    • 不知道你想要什么fjs
    猜你喜欢
    • 1970-01-01
    • 2016-12-20
    • 2015-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-02
    • 2018-08-30
    • 1970-01-01
    相关资源
    最近更新 更多