使用 enzyme ,我尝试测试组件的渲染文本。该组件是 LinkButton
,它的渲染结果如下:
<a><button to="/projects">See list of all projects</button></a>
我不确定如何直接引用字符串“查看所有项目的列表”。我目前正在测试如下:
let { link } = setup({ type: 'Project' })
link = link.shallow()
const text = link.prop('children').props.children.join('')
expect(link.prop('to')).to.eq('/projects')
expect(text).to.eq('See list of all projects')
link
来自shallow(<NotFoundCard />).find(LinkButton)
.
我尝试使用link.find('button')
和link.find('a')
但都返回 0 节点。
编辑 1
代码 setup
:
const setup = propOverrides => {
const props = Object.assign({
children: null,
type: 'None',
}, propOverrides)
const wrapper = shallow(<NotFoundCard {...props} />)
return {
props,
wrapper,
card: wrapper.find(Card),
title: wrapper.find(CardTitle),
text: wrapper.find(CardText),
link: wrapper.find(LinkButton),
}
}
最佳答案
我认为正确的方法是检查按钮元素是否已传递给 children
以及您想要的值。
此测试通过(正在使用 chai-enzyme )
describe('Link', () => {
it('should have text', () => {
const Link = () => (
<a>
<button to="/projects">See list of all projects</button>
</a>
);
const wrapper = shallow(<Link />);
expect(wrapper.find('button')).to.have.prop(
'children',
'See list of all projects'
);
});
});
关于reactjs - 如何测试 enzyme 中子元素的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43011540/