如何用酶测试子成分方法?

Fom*_*aut 24 javascript reactjs react-router enzyme

我有一个这样的组件:

<Parent>
  <Child/>
</Parent>
Run Code Online (Sandbox Code Playgroud)

<Child/>组件有一个方法foo.我想测试foo方法,但我不知道如何访问它.我试过了:

mount(<Parent><Child/></Parent>).props().children.foo
Run Code Online (Sandbox Code Playgroud)

要么

mount(<Parent><Child/></Parent>).children().foo
Run Code Online (Sandbox Code Playgroud)

但他们都是undefined.我无法使用,.instance()因为它不是root.我无法挂载<Child/>只是因为<Parent>添加了一些东西(react-router's context.router),context而我在init时需要它们<Child/>.有这个想法吗?

jac*_*cnr 5

这对我有用:

mount(<Parent><Child/></Parent>).find(Child).instance().foo
Run Code Online (Sandbox Code Playgroud)

  • 实例只能在 root 上调用。 (8认同)

小智 2

我认为你的问题与如何测试子组件有很大不同。

我的第一个问题是:为什么要检查子组件在父组件测试中是否具有特定方法?

恕我直言,您需要针对该组件进行特定的测试,然后在该测试中检查该方法是否存在。

只是为了不没有答案就离开,你尝试过吗.find(Child).instance().foo