如何在酶中通过选择器找到下面的元素

问题描述 投票:2回答:1

我使用酶+ jest来测试我们的反应应用。

如果呈现的html具有嵌套相同的结构,如何通过选择器找到下面的元素?

如果button方法返回HTML,我想要父两个render元素。

<ul>
  <li><button ...>parent1</button></li>
  <li><button ...>parent2</button>
    <ul>
      <li><button ...>child1</button></li>
      <li><button ...>child2</button></li>
    </ul>
  </li>
</ul>

在酶2.7.1中,我可以通过button选择器得到父两个> ul > li > button元素,如下面的代码。 (呃......这显然是奇怪的选择器。但确实有效)

const component = shallow(<Sample {...props}/>)
const parentButtons = component.find('> ul > li > button')
expect(parentButtons.length).toBe(2)

但在酶3.3.0中出现“无法解析选择器”错误。

I tried...

  • ul > li > button返回包含子按钮的所有按钮,这是有道理的。
  • :root伪选择器,它还不支持酶。

有谁有想法吗?

reactjs jestjs enzyme
1个回答
1
投票

假设给定的DOM结构不会改变(至少parent按钮将永远是顶级li的第一个节点),这应该工作:

const parentButtons = component.find('ul').first().children().map(child => child.childAt(0));
const parentButtonsTexts = component.find('ul').first().children().map(child => child.childAt(0).text());

expect(parentButtons).toHaveLength(2);
expect(parentButtonsTexts).toEqual(['parent1', 'parent2']);
© www.soinside.com 2019 - 2024. All rights reserved.