2016-10-01 5 views
4

구성 요소에서 버튼을 클릭하면 클릭을 처리하기 위해 만든 메서드를 호출하는지 확인하고 싶습니다. 여기 내 구성 요소입니다 : 여기Enzyme 및 Sinon을 사용하여 React 구성 요소에 대한 테스트 맞춤 메서드가 호출되었습니다.

import React, { PropTypes, Component } from 'react'; 

class Search extends Component { 

    constructor(){ 
    super(); 
    this.state = { inputValue: '' }; 
    } 

    handleChange = (e) => { 
    this.setState({ inputValue: e.target.value }); 
    } 

    handleSubmit = (e) => { 
    e.preventDefault(); 
    return this.state.inputValue; 
    } 

    getValue =() => { 
    return this.state.inputValue; 
    } 

    render(){ 
    return (
     <form> 
     <label htmlFor="search">Search stuff:</label> 
     <input id="search" type="text" value={this.state.inputValue} onChange={this.handleChange} placeholder="Stuff" /> 
     <button onClick={this.handleSubmit}>Search</button> 
     </form> 
    ); 
    } 
} 

export default Search; 

및 것은

import React from 'react'; 
    import { mount, shallow } from 'enzyme'; 
    import Search from './index'; 
    import sinon from 'sinon'; 

    describe('Search button',() => { 

    it('calls handleSubmit',() => { 
     const shallowWrapper = shallow(<Search />); 
     const stub = sinon.stub(shallowWrapper.instance(), 'handleSubmit'); 
     shallowWrapper.find('button').simulate('click', { preventDefault() {}  }); 
     stub.called.should.be.true(); 
    }); 

    }); 

통화라는 속성이 다시 거짓 오는 내 테스트입니다. 구문에 많은 변형을 시도해 본 결과 나는 근본적으로 뭔가 빠져 있다고 생각합니다. 어떤 도움이라도 대단히 감사하겠습니다.

답변

10

나는 시몬에게도 비교적 익숙하다. 나는 일반적으로 구성 요소 소품으로 spy()의를 통과하고 (같은 방법으로 stub()을 사용할 수 있지만) 그 확인되었습니다

let methodSpy = sinon.spy(), 
 
    wrapper = shallow(<MyComponent someMethod={methodSpy} />) 
 

 
wrapper.find('button').simulate('click') 
 

 
methodSpy.called.should.equal(true)

나는 그것이 가장 간단합니다 생각하기 때문에 나는이 지적 단위 테스트 구성 요소에 대한 방법 (내부 메서드 테스트 can be problematic).

예를 들어, 구성 요소의 내부 메소드를 테스트하려는 경우이 방법은 작동하지 않습니다. 그래도 this issue을 보았습니다. 도움이 될 것입니다. 시도 :

it('calls handleSubmit',() => { 
 
    const shallowWrapper = shallow(<Search />) 
 
    let compInstance = shallowWrapper.instance() 
 

 
    let handleSubmitStub = sinon.stub(compInstance, 'handleSubmit'); 
 
    // Force the component and wrapper to update so that the stub is used 
 
    compInstance.forceUpdate() 
 
    shallowWrapper.update() 
 

 
    shallowWrapper.find('button').simulate('click', { preventDefault() {} }); 
 

 
    handleSubmitStub.called.should.be.true(); 
 
});

+0

두 번째 코드는 실제로 내 테스트를 통과 않습니다. 내부 방법을 테스트하는 흥미로운 기사를 나는 몰랐다. 나는 일반적으로 TDD에 상당히 익숙하다. 그래서 내가 테스트해야하는 것이 틀렸다면 내 이해가 가능할 것이다. 많은 고마워, 나는 내 연구에 인내 할 것이다! –

+0

"단위"의 경계가 무엇인지에 대한 의견이 다르다. 나는 당신의 접근 방식이 틀렸다고 생각하지 않는다. 그러나 그것이 일반적으로 개최 된 의견이기 때문에 나는 그것을 따라 가야한다고 생각했습니다. 테스트 여행을 즐기십시오 :) – bjudson

+0

많은 덕분에, 그것은 많이 도움이됩니다, 나는 효소 repo에 관한 많은 문제를 점검했지만 구성 요소의 내부 방법으로는 작동하지 않습니다. –