2016-09-01 3 views
0

私はReactコンポーネントのテストをmochaと書こうとしています。基本的に、コンポーネントは、hrefが渡されるプロパティの値に設定された<>タグをレンダリングする必要があります。問題は、複数の<>タグを予測不能な順序でレンダリングすることができ、正しいhrefを持っている私は私の実際のコードの削減バージョンされ、次のenzimechaichai-enzime複数の<a>タグを持つReactコンポーネントをアサートする方法は、特定のhrefを持つ<a>タグを持っています

を使用していますが、テストのどちらも渡している

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

答えて

0

それは私がしたことが判明これは間違っています。式のアサーション部分がクエリの複数の結果を処理するようにするのではなく、より具体的になるように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(); 
    }); 
}); 
+0

あなたが到着したアサーションは、私は削除する必要があると表示されていない@lux ;-) – lux

+0

を採掘するために妙に似ていますが、私は、私は私の答えを削除しますと仮定し、あなたの答え、私はそれにも賛成投票をするだろう。アサーションは類似していると私は同意しますが、私がここで使っている解決法では、構文を異ならせるEnzymeを使用しています。 –

関連する問題