如何使用反应酶选择元素文本

新手上路,请多包涵

正是它所说的。一些示例代码:

 let wrapper = shallow(<div><button class='btn btn-primary'>OK</button></div>);

const b = wrapper.find('.btn');

expect(b.text()).to.be.eql('OK'); // fail

此外 html 方法返回元素的内容以及元素本身以及所有属性,例如它给出 <button class='btn btn-primary'>OK</button> 。所以我想,最坏的情况,我可以调用 html 并对其进行正则表达式,但是……

有没有办法只获取元素的内容,所以我可以断言它。

原文由 Kevin 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 338
2 个回答

不要忘记您将节点(ReactElement)传递给 shallow 函数,并且 React 中没有 HTML 属性 class 。您必须使用 className

来自 React 文档

All attributes are camel-cased and the attributes class and for are className and htmlFor , respectively, to match the DOM API specification.

这个测试应该有效

const wrapper = shallow(<div><button className='btn btn-primary'>OK</button></div>);
const button = wrapper.find('.btn');
expect(button.text()).to.be.eql('OK');

原文由 Louis Barranqueiro 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果您在查找 “包含文本” 时发现了这一点,请尝试:

 it('should show correct text', () => {
  const wrapper = shallow(<MyComponent />);
  expect(wrapper.text().includes('my text')).toBe(true);
});

原文由 Nelu 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进