2016-05-13 59 views
-1

试图使用React的测试实用程序(https://facebook.github.io/react/docs/test-utils.html)来测试我的组件。反应 - 业主Ownee单元测试

我们拥有Owner和Ownee。

业主呈现:

<Ownee> 
    <div class="inner"> 
     <div class="moreInner" /> 
    </div> 
</Ownee> 

我的测试就像是这样的:

var comp = TestUtils.renderIntoDocument(<Owner />); 
var innerClass = TestUtils.findRenderedDOMComponentWithClass(comp, "inner"); 
expect(innterClass).to.not.be.null; 

理想的情况下,这应该很好地工作。但实际上,它输出:“没有找到完全匹配(找到:0)”。

所以,如果我删除上述<Ownee></Ownee>所以它就像:

<div class="inner"> 
     <div class="moreInner" /> 
    </div> 

它正常工作,但我不能用这个(必须给予Ownee元太)。

Ownee呈现类似这样:

<div class="inner"> 
    {this.props.children} 
</div> 

如何使用TestUtils来得到期望的结果(即测试工作,并通过类查找DIV)有什么建议?

谢谢!

+1

使用'className' ** **不类 – ajmajmajma

+0

正在做的,错误类型的简化代码。 –

+0

如果ownee呈现className内部,为什么还要手动将它添加到ownee标签之间?你能否只显示ownee和owner的渲染()是否被修改? – ajmajmajma

回答

0

所以问题不是老板/老板。最后,我正在使用React-Bootstrap的模式对话框(作为Ownee)。所以发生了什么事情是测试会渲染组件,但它会被放在不同的组件树上。

要解决这个问题,我也跟着以前问一个问题: Testing a React Modal component

具体来说,user1778856的答案。

var stubModal =() => { 
    var createElement = React.createElement; 
    modalStub = sinon.stub(React, 'createElement', function (elem: any) { 
     return elem === ModalDialog ? 
      React.DOM.div.apply(this, [].slice.call(arguments, 1)) : 
      createElement.apply(this, arguments); 
    }); 
    return modalStub; 
}; 
var stubModalRestore =() => { 
    if (modalStub) { 
     modalStub.restore(); 
     modalStub = undefined; 
    } else { 
     console.error('Cannot restore nonexistent modalStub'); 
    } 
}; 

before(() => { stubModal(); }); 
after(() => { stubModalRestore(); }); 

其他链接: Unit testing React Bootstrap modal dialog