React Enzyme 找到第二个(或第 n 个)节点 [英] React Enzyme find second (or nth) node
问题描述
我正在测试一个带有 Jasmine Enzyme 浅层渲染的 React 组件.
为了这个问题的目的在这里简化......
function MyOuterComponent() {返回 (...<MyInnerComponent 标题="你好"/>...<MyInnerComponent title="再见"/>...</div>)}MyOuterComponent
有 2 个 MyInnerComponent
实例,我想在每个实例上测试道具.
我知道如何测试的第一个.我使用 find
和 first
...
expect(component.find('MyInnerComponent').first()).toHaveProp('title', 'Hello');
但是,我正在努力测试 MyInnerComponent
的第二个实例.
我希望这样的事情会奏效......
expect(component.find('MyInnerComponent').second()).toHaveProp('title', 'Good-bye');
甚至这个...
expect(component.find('MyInnerComponent')[1]).toHaveProp('title', 'Good-bye');
当然,上述两种方法都不起作用.
我觉得我错过了显而易见的事情.
但是当我查看 docs 时,我没有看到类似的例子.
有人吗?
解决方案 你想要的是 .at(index)
方法:.at(index) .
所以,对于你的例子:
expect(component.find('MyInnerComponent').at(1)).toHaveProp('title', 'Good-bye');
I'm testing a React component with Jasmine Enzyme shallow rendering.
Simplified here for the purposes of this question...
function MyOuterComponent() {
return (
<div>
...
<MyInnerComponent title="Hello" />
...
<MyInnerComponent title="Good-bye" />
...
</div>
)
}
MyOuterComponent
has 2 instances of MyInnerComponent
and I'd like to test the props on each one.
The first one I know how to test. I use find
with first
...
expect(component.find('MyInnerComponent').first()).toHaveProp('title', 'Hello');
However, I'm struggling to test the second instance of MyInnerComponent
.
I was hoping something like this would work...
expect(component.find('MyInnerComponent').second()).toHaveProp('title', 'Good-bye');
or even this...
expect(component.find('MyInnerComponent')[1]).toHaveProp('title', 'Good-bye');
But of course neither of the above work.
I feel like I'm missing the obvious.
But when I look through the docs I don't see an analogous example.
Anyone?
解决方案 What you want is the .at(index)
method: .at(index) .
So, for your example:
expect(component.find('MyInnerComponent').at(1)).toHaveProp('title', 'Good-bye');
这篇关于React Enzyme 找到第二个(或第 n 个)节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文