2016-06-01 7 views
1

JestEnzyme을 사용하여 반응 성분에 대한 단위 테스트를 구현하기 만하면됩니다.반응의 원소 순서를 테스트하는 방법

주문을 테스트 할 방법이 있습니까? 버튼이 있고 아이콘과 텍스트를 동시에 렌더링한다고 가정 해 보겠습니다.

물론 사용자에게 정렬 옵션을 제공하는 것이 좋습니다 (아이콘 먼저 또는 어린이 우선).

Button.js는

class Button extends React.Component { 
    constructor() { 
     super(); 
    } 
    render() { 
     let content; 
     const icon = (<Icon type='search' />); 
     if (this.props.iconAlign === 'right') { 
      content = (<span>{this.props.children} {icon}</span> 
     } else { 
      content = (<span>{icon} {this.props.children}</span> 
     } 
     return (
      <button>{content}</button> 
     ); 
    } 
} 

어떻게 및 효소농담으로 iconAlign 소품을 테스트?

답변

2

얕은 렌더링을 사용하고 출력을 비교할 수 있습니다.

import { shallow } from 'enzyme'; 

describe(`Button`,() => { 
    it(`should render the icon on the right`,() => { 
    const children = <div>foo</div>; 
    const actual = shallow(
     <Button iconAlign="right" children={children} /> 
    ); 
    const expected = (
     <button><span>{children} <Icon type='search' /></span></button> 
    ); 
    expect(actual.matchesElement(expected)).toBeTruthy(); 
    }); 
}); 

을 그리고 당신은 "왼쪽"정렬에 대한 또 다른 시험을 만들 수 있습니다 내 예를 들어 그 쪽이 잘못 될 수 있도록 나는 (I 빠르게 자신의 웹 사이트 함) 농담 구문에 익숙하지입니다.


@ pshoukry의 대답 효소 버전.

describe(`Button`,() => { 
    it(`should render icon on the right`,() => { 
    const wrapper = shallow(
     <Button iconAlign="right"> 
     <div>foo</div> 
     </Button> 
    ); 
    const iconIsOnRight = wrapper.find('span').childAt(1).is(Icon); 
    expect(iconIsOnRight).toBeTruthy(); 
    }); 
}); 
참고로

, 여기에 효소 얕은 렌더링 API 문서입니다 : 구성 요소의 종류에 https://github.com/airbnb/enzyme/blob/master/docs/api/shallow.md

+0

니스 해결책! 고마워... –

1

확인

확인 아이콘 첫째

var button = TestUtils.renderIntoDocument(<Button />); 

var buttonNode = ReactDOM.findDOMNode(button); 
expect(buttonNode.props.children[0].type.name).toEqual("Icon")