element.find('span.active-nav-option')
不返回任何内容,而element.find('.active-nav-option')
返回范围。测试的重点是确定是否渲染了span
而不是Link
。
组件如下:
const PageNav = ({
router,
slides,
}) => (
<nav className="PageNav">
<span className="chevron">
<MoreVerticalIcon
strokeWidth="0.5px"
size="3em"
/>
</span>
<ul className="nav-links">
{mapSlides(slides, router)}
</ul>
<style jsx>{styles}</style>
</nav>
)
function mapSlides(slides, router) {
return Object.entries(slides)
.sort((
[, { order: a }],
[, { order: b }],
) => a - b)
.map(([slidename, { altText, order }]) => {
const isActiveLink = router.query.slidename === slidename
const navItemClassnames = [
'nav-item',
isActiveLink && 'active',
]
.filter(Boolean)
.join(' ')
const Element = isActiveLink
? props => <span {...props} />
: Link
const liInternalElementProps = {
...(isActiveLink && { className: 'active-nav-option' }),
...(!isActiveLink && {
href: `/CVSlide?slidename=${slidename}`,
as: `/cv/${slidename}`,
}),
}
return (
<li
className={navItemClassnames}
key={order}
>
<Element {...liInternalElementProps}>
<a title={altText}>
<img
src={`/static/img/nav-icons/${slidename}.svg`}
alt={`An icon for the ${slidename} page, ${altText}`}
/>
</a>
</Element>
<style jsx>{styles}</style>
</li>
)
})
}
要复制 运行此行作为测试:
const wrapperOne = shallow(
<PageNav
slides={mockSlides}
router={{
query: {
slidename: 'hmmm',
},
}}
/>
)
const spanExists = wrapperOne
.find('.active-nav-option')
.html() // outputs <span class="active-nav-option">...</span>
// so one would expect span.active-nav-option to work?
const spanDoesNotExist = wrapperOne
.find('span.active-nav-option')
.html() // throws an error `Method “html” is only meant to be run on a single node. 0 found instead.`
// subsequently if I use `.exists()` to test if the element exists, it returns nothing.
预期的行为
element.find('span.active-nav-option')
应该返回span
。我认为?最初,我认为这与shallow
和mount
有关,但mount也是如此。我是白痴吗这与组件中的map函数有关吗?
答案 0 :(得分:0)
看起来像是因为您没有在<span/>
方法返回的JSX中直接使用render
,而是将其分配给变量,然后将该变量添加到JSX中。
如果执行console.log(wrapperOne.debug())
,将会看到以下结果(我删除了您未提供的样式和组件):
<nav className="PageNav">
<span className="chevron" />
<ul className="nav-links">
<li className="nav-item active">
<Component className="active-nav-option">
<a title={[undefined]}>
<img src="/static/img/nav-icons/0.svg" alt="An icon for the 0 page, undefined" />
</a>
</Component>
</li>
</ul>
</nav>
如您所见,您拥有<Component className="active-nav-option">
而不是<span className="active-nav-option">
,因此span.active-nav-option
找不到任何东西。