简体   繁体   中英

How to assert a React component with multiple <a> tags has an <a> tag with a given href

I'm trying to write a mocha test for a React component. Basically the component needs to render an <a> tag with its href set to a value in a property that is passed in. The issue is that the component can render multiple <a> tags in an unpredictable order and only one of them has to have the correct href.

I'm using enzyme , chai and chai-enzyme

The following is a cut down version of my real code, but neither of the tests are passing:

const TestComponent = function TestComponent(props) {
  const { myHref } = props;

  return (
    <div>
      <a href="http://example.com">Link 1</a><br />
      <a href={myHref}>Link 2</a><br />
      <a href="http://example.com">Link 3</a>
    </div>
  );
};

TestComponent.propTypes = {
  myHref: React.PropTypes.string.isRequired
};

describe('<TestComonent />', () => {
  it('renders link with correct href', () => {
    const myHref = 'http://example.com/test.htm';
    const wrapper = Enzyme.render(
      <TestComponent myHref={myHref} />
    );

    expect(wrapper).to.have.attr('href', myHref);
  });

  it('renders link with correct href 2', () => {
    const myHref = 'http://example.com/test.htm';
    const wrapper = Enzyme.render(
      <TestComponent myHref={myHref} />
    );

    expect(wrapper.find('a')).to.have.attr('href', myHref);
  });
});

It turns out that I was approaching this wrong. Rather than try to get the assertion part of the expression to work with multiple results from the query, it is better to change the find query to be more specific. It is possible to use attribute filters in a similar way to jQuery. As such my test becomes like this:

const TestComponent = function TestComponent(props) {
  const { myHref } = props;

  return (
    <div>
      <a href="http://example.com">Link 1</a><br />
      <a href={myHref}>Link 2</a><br />
      <a href="http://example.com">Link 3</a>
    </div>
  );
};

TestComponent.propTypes = {
  myHref: React.PropTypes.string.isRequired
};

describe('<TestComonent />', () => {
  it('renders link with correct href', () => {
    const myHref = 'http://example.com/test.htm';
    const wrapper = Enzyme.render(
      <TestComponent myHref={myHref} />
    );

    expect(wrapper.find(`a[href="${myHref}"]`)).be.present();
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM