【问题标题】:Jest check if an elements attribute exists开玩笑检查元素属性是否存在
【发布时间】:2018-10-15 15:21:54
【问题描述】:

我想开玩笑地检查以下 svg 路径元素是否包含属性 d
<path id="TrendLine" fill="none" stroke="black" d="M170,28.76363636363638C170,28.76363636363638,221.46221083573664,189.150059910"></path> 如何使用 jest 搜索元素中的特定属性?

【问题讨论】:

    标签: reactjs jestjs chai enzyme


    【解决方案1】:

    您可以使用enzyme's shallow method 来渲染您的组件,然后检查路径元素上的道具:

    // 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 中的值
    • 您可以通过使用第一个参数调用 toHaveProperty 来做到这一点:.toHaveProperty('d')
    • 之前试过了,出现这个错误,Error: Invalid Chai property: toHaveProperty,有没有其他方法可以检查d是否存在?
    • 奇怪的是你用的是哪个版本的 jest?
    • 但是是的,props() 函数返回该元素属性的对象,因此您可以像这样检查它是否存在:expect(trendline.props().hasOwnProperty('d')).toBe(true);
    猜你喜欢
    • 1970-01-01
    • 2011-10-25
    • 2021-12-11
    • 1970-01-01
    • 2021-05-09
    • 2019-11-08
    • 2020-07-09
    • 2023-03-21
    • 1970-01-01
    相关资源
    最近更新 更多