我喜欢在Redux应用程序中测试Connect中的组件:
this.component = TestUtils.renderIntoDocument(<Provider store={store}><Header path={this.path} /></Provider>);
我不知道如何在Provider中访问Header ...(因为我从CLI运行jest时无法在调试器中停止。
所以当我试图让一个孩子进入Header
时 const path = findDOMNode(self.component.refs.pathElemSpan);
console.log("path="+path)
我在路径上未定义
有什么建议吗?
感谢
答案 0 :(得分:6)
使用enzyme
,你有一堆不错的选择器来浏览你的虚拟DOM王国。 :)
访问组件的超级简单测试:
import { mount } from 'enzyme'
import Header from './header'
//... in your test
const wrapper = mount(<Provider store={store}><Header path='foo' /></Provider>)
const header = wrapper.find(Header).first()
expect(header.exists()).toBe(true)
// you can even check out the props
expect(header.prop('path')).toBe('foo')
此示例使用mount
,但您也可以选择执行浅层渲染。我强烈建议你喝点东西喝一点,然后阅读文档。 ;)
答案 1 :(得分:0)
import Foo from '../components/Foo';
const wrapper = mount(<MyComponent />);
expect(wrapper.find(Foo)).to.have.lengthOf(1); //you can use this one
expect(wrapper.find('Foo')).to.have.lengthOf(1); //you can use this one as well
答案 2 :(得分:-1)
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
function App() {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Cahal" />
<Welcome name="Edite" />
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);