Javascript 使用完整装载,找到的组件的实例等于null
我有要测试的向导组件 向导组件Javascript 使用完整装载,找到的组件的实例等于null,javascript,reactjs,testing,enzyme,Javascript,Reactjs,Testing,Enzyme,我有要测试的向导组件 向导组件 class WizardComponent extends React.Component { render(){ return ( <div> {this.props.steps.map(({Component, ...props}) => <Component {...props} />)} </div> ) } } it('Provides props
class WizardComponent extends React.Component {
render(){
return (
<div>
{this.props.steps.map(({Component, ...props}) => <Component {...props} />)}
</div>
)
}
}
it('Provides props to the component', () => {
const FakeComponent = props => <div>1</div>
const fakeProps = {
test:1,
prop4:'test'
}
const wrapper = mount(<WizardComponent currentStepName="fakeComponent" steps={[
{Component:FakeComponent, name:'fakeComponent'},
]}/>)
const component = wrapper.find(FakeComponent);
console.log(wrapper.contains(<FakeComponent />)) // logs true
console.log(component) // logs ReactWrapper { length: 1 }
console.log(component.instance()) // logs null
expect(component.instance().props).objectContaining(fakeProps)
})
类向导组件扩展了React.Component{
render(){
返回(
{this.props.steps.map(({Component,…props})=>)}
)
}
}
测试
class WizardComponent extends React.Component {
render(){
return (
<div>
{this.props.steps.map(({Component, ...props}) => <Component {...props} />)}
</div>
)
}
}
it('Provides props to the component', () => {
const FakeComponent = props => <div>1</div>
const fakeProps = {
test:1,
prop4:'test'
}
const wrapper = mount(<WizardComponent currentStepName="fakeComponent" steps={[
{Component:FakeComponent, name:'fakeComponent'},
]}/>)
const component = wrapper.find(FakeComponent);
console.log(wrapper.contains(<FakeComponent />)) // logs true
console.log(component) // logs ReactWrapper { length: 1 }
console.log(component.instance()) // logs null
expect(component.instance().props).objectContaining(fakeProps)
})
it('为组件提供道具',()=>{
常量FakeComponent=props=>1
常数fakeProps={
测试:1,
建议4:‘测试’
}
const wrapper=mount()
const component=wrapper.find(FakeComponent);
console.log(wrapper.contains())//日志为true
console.log(component)//日志{length:1}
console.log(component.instance())//日志为空
expect(component.instance().props).objectContaining(fakeProps)
})
为什么我不能访问组件实例?我想测试它的子组件道具。有人能帮忙吗?根据,组件包装的道具是使用包装器。道具()
访问的
你在你的组件中使用了
wrapper.instance().props
u lost}。谢谢,但这没有帮助。我只是在编写这个演示时输入了拼写错误。组件正确地呈现了component.props()
而不是component.instance().props
@SamBokai谢谢,这就成功了,如果你写一个,我愿意接受你的回答。如果你能告诉我为什么我不能访问组件的实例(我应该吗?),我会非常高兴。干杯!不客气。文档说只有根组件的实例才能被访问。过去我肯定能够使用.instance()
。