Jest检查元素属性是否存在。

6
我希望使用jest来检查以下svg路径元素是否包含属性d:
<path id="TrendLine" fill="none" stroke="black" d="M170,28.76363636363638C170,28.76363636363638,221.46221083573664,189.150059910"></path> 如何使用jest在元素中搜索特定属性?
1个回答

20

您可以使用enzyme的浅渲染方法来渲染组件,然后检查路径元素上的props:

// at the top of your test file file:
import { shallow } from 'enzyme';

...

it('should render path element with the expected d attribute', () => {
  // shallowly render your component:
  const wrapper = shallow(<Component />);

  // find the path element using a css selector
  const trendline = wrapper.find('path#TrendLine');

  // make assertion
  expect(trendline.props()).toHaveProperty('d', 'M170,28.76363636363638C170,28.76363636363638,221.46221083573664,189.150059910');
});

“d”值可能会发生变化,我如何检查“d”是否存在,而不考虑“d”中的值? - Athif Shaffy
你可以通过调用第一个参数为‘d’的toHaveProperty来实现。 - Billy Reilly
之前尝试过,但出现了错误 Error: Invalid Chai property: toHaveProperty,是否有其他检查 d 是否存在的方法? - Athif Shaffy
请问您正在使用哪个版本的Jest?这很奇怪。 - Billy Reilly
1
但是,props()函数返回该元素属性的对象,因此您可以像这样检查它是否存在:expect(trendline.props().hasOwnProperty('d')).toBe(true); - Billy Reilly
expect(trendline.props().hasOwnProperty('d')).toBe(true); 做到了,谢谢! - Athif Shaffy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接