代码之家  ›  专栏  ›  技术社区  ›  Hamed Minaee

当组件didmount中有函数调用时,酶挂载失败

  •  0
  • Hamed Minaee  · 技术社区  · 6 年前

    我有一个react组件,其中有一个click函数,如下所示:

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

    在组件didmount中,我有以下内容:

        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....
    

    如果我从componentDidMount中删除this.fbInit();一切正常。 我能告诉测试忽略this.fbinit()吗?或者任何其他的解决方案

    1 回复  |  直到 6 年前
        1
  •  0
  •   Safi Nettah    6 年前

    我想是的 var js, fjs = d.getElementsByTagName(s)[0]; FJS是 undefined

    推荐文章