【问题标题】:How to assert a React component with multiple <a> tags has an <a> tag with a given href如何断言具有多个 <a> 标签的 React 组件具有带有给定 href 的 <a> 标签
【发布时间】:2016-09-01 16:52:42
【问题描述】:

我正在尝试为 React 组件编写 mocha 测试。基本上,组件需要呈现一个 标记,其 href 设置为传入的属性中的值。问题是组件可以以不可预测的顺序呈现多个 标记,并且只有其中一个必须有正确的href。

我正在使用enzymechaichai-enzyme

以下是我真实代码的精简版,但没有一个测试通过:

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);
  });
});

【问题讨论】:

    标签: reactjs mocha.js chai enzyme chai-enzyme


    【解决方案1】:

    事实证明,我正在接近这个错误。与其尝试让表达式的断言部分与查询的多个结果一起工作,不如将 find 查询更改为更具体。可以以类似于 jQuery 的方式使用属性过滤器。因此我的测试变成了这样:

    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();
      });
    });
    

    【讨论】:

    • 我想我会删除我的答案,尽管你得出的断言看起来和我的很相似 ;-)
    • @lux 我认为没有必要删除您的答案,我什至会投赞成票。我同意断言是相似的,尽管我在这里的解决方案确实使用了 Enzyme,这确实使语法不同。
    猜你喜欢
    • 2015-08-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多