如何测试组件是否具有属性?

How can I test that a component has an attribute?

我用testing-library

如果你有语法解决方案,我无法定位元素, 我正在尝试检索标签并比较 xlinkHref。 我可以获得整个组件,但没有 class 名称或 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;

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

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

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