【问题标题】:How can I test that a component has an attribute?如何测试组件是否具有属性?
【发布时间】:2021-09-17 13:25:36
【问题描述】:

我用testing-library

如果您有语法解决方案,我无法定位元素, 我正在尝试检索标签并比较xlinkHref。 我可以获得整个组件,但没有类名或 ID,这让我很困扰 // Type.test.jsx

import React from 'react';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';

import Type from '../index';

describe('Type', () => {

  it('Watch Type', () => { 
    const {container} = render(<Type type="Watch Type" />);

    expect(container.firstElementChild.getAttribute('xlinkHref')).toHaveAttribute('xlinkHref', 'https://www.test.com/')
  });

});

// Type.jsx

import React from 'react';

const Type = (props) => {
  const type = props.type;

  if (type === 'Watch Type') {
    return (
      <span className="platform-icon">
        <svg>
          <use xlinkHref="https://www.test.com/" />
        </svg>
      </span>
    )
  }
}

export default App;

【问题讨论】:

    标签: reactjs jestjs react-testing-library


    【解决方案1】:

    getAttribute(attributeName) 返回属性attributeName 的值,所以你应该这样做:

    expect(container.querySelector('svg use').getAttribute('xlinkHref')).toEqual('https://www.test.com/');
    

    https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute

    【讨论】:

    • 感谢同时我找到了querySelector,但不知道它是否适用于getAttribute 我绕了一圈x)expect(container.querySelector('svg use').getAttribute('xlink:href')).toEqual('https://www.test.com/')
    • np! querySelectorAll 也可以很方便(返回匹配选择器的节点列表)。
    猜你喜欢
    • 1970-01-01
    • 2011-06-24
    • 2015-09-20
    • 2016-11-09
    • 2020-06-08
    • 2013-12-28
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多