Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test that a component has an attribute?

I use testing-library

I can't target the element if you have syntax solutions, I'm trying to retrieve the tag and compare the xlinkHref. I can get the whole component and not having a class name or ID it bothers me // 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;
like image 690
Cephas Avatar asked Oct 12 '25 10:10

Cephas


1 Answers

getAttribute(attributeName) returns the value of the attribute attributeName, so you should just do :

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

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

like image 155
Florian Motteau Avatar answered Oct 13 '25 23:10

Florian Motteau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!