小编ind*_*dge的帖子

如何在HOC包装的嵌套React组件上访问状态?

我正在使用Enzyme,我们实际上可以使用文档中给出的示例组件作为我的问题的基础.

假设这个<Foo />组件使用了<Link>ReactRouter中的一个组件,因此我们需要将它包装在一个<MemoryRouter>for测试中.

这就是问题所在.

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!
})
Run Code Online (Sandbox Code Playgroud)

因此,在使用时不确定如何访问本地组件状态<MemoryRouter>.

也许我正在进行无知的测试?试图在测试中获取/设置组件状态不良做法?我无法想象,因为Enzyme有获取/设置组件状态的方法.

只是不确定应该如何访问包含在其中的组件的内部<MemoryRouter>.

任何帮助将不胜感激!

jestjs react-router enzyme react-router-v4

17
推荐指数
1
解决办法
6859
查看次数

标签 统计

enzyme ×1

jestjs ×1

react-router ×1

react-router-v4 ×1