component.find('a).prop('href') returns undefined instead of the href value
Asked Answered
T

3

12

I have a navigation component that uses Link, IndexLink to render the navigation bar:

class Navigation extends Component {

  renderLinks = (linksData) => {
    return linksData.map((link) => {
      if(link.to === '/') {
        return (
          <li key={link.text}>
            <IndexLink to={link.to}>
              <i>{link.icon}</i>
              <span>{link.text}</span>
            </IndexLink>
          </li>
        );
      } else {
        return (
          <li key={link.text}>
            <Link to={link.to}>
              <i>{link.icon}</i>
              <span>{link.text}</span>
            </Link>
          </li>
        );
      }
    });
  };

  render() {
    const {links} = this.props;
    return(
      <div>
        <ul>
          {this.renderLinks(links)}
        </ul>
      </div>
    )
  }
}

Navigation.propTypes = {
  links: React.PropTypes.array.isRequired
}

export default Navigation;

Now I want to test that my links render correcttly:

import React from 'react';
import {Link, IndexLink} from 'react-router';
import {mount} from 'enzyme';
import Navigation from '../components/core/Navigation.component';

describe('<Navigation/>', () => {
  it('should render Navigation links', () => {
    const links = [
      {
        to: '/',
        icon: 'hourglass_empty',
        text: 'Timer'
      }
    ];
    const navigation = mount(<Navigation links={links}/>);
    console.log(navigation.find('a').prop('href'));
  });
});

But this just logs out undefined. How am I able to test that the correct href value is getting passed to my anchors?

Templin answered 19/1, 2017 at 13:31 Comment(3)
Did you try binding your renderLinks method?Cauldron
nope not yet, since when I host this localy everything works as expectedDanas
I think this has something to do with the solution not rendering correctly. I can find the IndexLink component prop if I look for it. It is just weird, because my tests to find anchor work as well...Danas
I
15

try this: wrapper.find(Foo).at(0).props().href

Inexpiable answered 8/10, 2018 at 9:19 Comment(1)
why is .props().href working but .prop('href') isn't?Riddance
A
0

This question is related to React, but for Vue, the following code works:

wrapper.find('.link').attributes('href')
Ambitendency answered 27/8, 2021 at 21:14 Comment(0)
P
0

The link has a prop of to in React to query the link find it by the text you click - and the right attribute is to not href

eg:

const url1 = screen.getByText("I am a link click me")
expect(url1).toHaveAttribute("to", "https://test-url1#")
Promiscuous answered 9/11, 2021 at 13:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.