React router 一个嵌套组件上的访问状态是如何被HOC包装的? 我正在使用,并且我们实际上可以使用文档中给出的组件作为我的问题的基础。

React router 一个嵌套组件上的访问状态是如何被HOC包装的? 我正在使用,并且我们实际上可以使用文档中给出的组件作为我的问题的基础。,react-router,jestjs,enzyme,react-router-v4,React Router,Jestjs,Enzyme,React Router V4,让我们假设此组件使用来自ReactRouter的组件,因此我们需要将其包装在中进行测试 问题就在这里 it('puts the lotion in the basket', () => { const wrapper = mount( <MemoryRouter> <Foo /> </MemoryRouter> ) wrapper.state('name') // this returns null! We ar

让我们假设此
组件使用来自ReactRouter的
组件,因此我们需要将其包装在
中进行测试

问题就在这里

it('puts the lotion in the basket', () => {
  const wrapper = mount(
    <MemoryRouter>
      <Foo />
    </MemoryRouter>
  )

  wrapper.state('name') // this returns null! We are accessing the MemoryRouter's state, which isn't what we want!
  wrapper.find(Foo).state('name') // this breaks! state() can only be called on the root!
})
it('把乳液放进篮子',()=>{
常量包装器=装入(
)
state('name')//返回null!我们正在访问MemoryRouter的状态,这不是我们想要的!
wrapper.find(Foo.state('name')//这会中断!state()只能在根上调用!
})
因此,不确定在使用
时如何访问本地组件状态

也许我在做一个无知的测试?在测试中试图获取/设置组件状态是一种错误的做法吗?我无法想象,因为酶有获取/设置成分状态的方法

只是不确定如何访问
中包装的组件的内部

任何帮助都将不胜感激

因此,似乎通过酶的使用,有可能解决访问子组件状态的问题

假设我们有
(注意React路由器
的使用)

请注意在浅层测试中的使用,它可以在单个非DOM节点上运行,并将返回浅层渲染的节点


参考文献:


我觉得这可能对你们有用,因为我偶然发现了这一点,并找到了解决办法

在我的例子中,我有一个连接到redux的组件

class ComponentName extends Component {
...
}
export default connect(
  mapStateToProps,
  {
...
 }
)(ComponentName );
connect()显然是一个HOC组件。 那么我们如何访问这里的“组件名”

非常简单:

component
    .find(ComponentName)
    .children()
    .first()
    .props() // returns ComponentName's props 

相关:仍然显示tells
获取作为传递到mount()的根节点呈现的组件的实例,并且当我使用
mount
时,仍然无法访问子组件的状态,tells
state
不是函数。我的代码如下:
let wrapper=mount()这里是我的问题:令人惊讶的是,这是可行的,但是有没有一种方法可以设计用于测试的组件来避免需要它?
it('puts the lotion in the basket shallowly', () => {
  const wrapper = shallow(
    <MemoryRouter>
      <Foo />
    </MemoryRouter>
  )

  expect(wrapper.find(Foo).dive().instance().state).toEqual({
    bar: 'here is the state!'
  })
})
class ComponentName extends Component {
...
}
export default connect(
  mapStateToProps,
  {
...
 }
)(ComponentName );
component
    .find(ComponentName)
    .children()
    .first()
    .props() // returns ComponentName's props