반응 구성 요소 내에서 메소드를 테스트하려고합니다. 구성 요소는 양식이며 제출 버튼을 클릭하면 handleSubmit() 메서드가 호출되는지 테스트해야합니다. 나는 아래를 시도했다. . wrapper.instance() handleSubmit는 농담 모의 기능이 없기 때문에 첫 번째 블록이 실패 Expected mock function to have been called
jest와 효소가 포함 된 맞춤 반응 방법 테스트
2
A
답변
5
말
it('handlesSubmit when submit button is clicked',() => {
const handleSubmit = jest.fn();
wrapper.find(Button).simulate('click');
expect(handleSubmit).toHaveBeenCalled();
})
이 오류 :
it('handlesSubmit when submit button is clicked',() => {
wrapper.find(Button).simulate('click');
expect(wrapper.instance().handleSubmit).toHaveBeenCalled();
})
이 그래서 난이 시도 jest.fn() value must be a mock function or spy.
오류를 준 ; 클래스 메쏘드가 그것을 정의하는 것은 무엇이든합니다.
handleSubmit은 jest mock 기능이지만 래퍼 구성 요소에 전혀 묶이지 않으므로 두 번째 블록이 실패합니다. 지역 변수입니다. 클릭을 시뮬레이션 할 때 실제 구현을 다시 호출합니다. 당신이 뭘 하려는지 달성하기 위하여
, 당신은 WrapperComponent이 테스트중인 구성 요소가이
it('handlesSubmit when submit button is clicked',() => {
const handleSubmit = jest.fn();
WrapperComponent.prototype.handleSubmit = handleSubmit;
const wrapper = shallow(<WrapperComponent />);
wrapper.find(Button).simulate('click');
expect(handleSubmit).toHaveBeenCalled();
})
같은 것을해야한다.
위의 사항은 작동해야하지만 때로는 더 좋은 방식으로 비슷한 것을 얻을 수 있습니다. 구성 요소의 구현에 따라 handleSubmit 메서드 자체가 아니라 handleSubmit 메서드의 기능이 호출되는지 테스트하는 것이 더 쉽습니다. 예를 들어, 경우 내 구성 요소는 내가 프로토 타입을 덮어 쓸 필요가 없기 때문에
class TestComponent extends React.Component {
constructor(props) {
super(props)
this.state = { clicked: false }
this.onClick = this.onClick.bind(this)
}
onClick() {
this.props.onClick()
this.setState({ clicked: true })
}
render() {
return (
<button onClick={ this.onClick }>
{ 'Click Me' }
</button>
)
}
}
같은 뭔가 내가 일반적으로 시험의 유형을 선호
it('calls onClick props and sets clicked state to true when clicked',() => {
const onClick = jest.fn();
const testComp = shallow(<TestComponent onClick={ onClick } />);
wrapper.find('button').simulate('click');
expect(onClick).toHaveBeenCalled();
expect(testComp.state('clicked')).toBe(true)
})
을 수행하여 테스트 할 수 있었고, 그것은 실제로 클릭이 내가 기대하는 논리를 유발한다는 것을 테스트합니다. 원래의 테스트는 실제로 this.handleSubmit을 onClick 소품으로 Button 구성 요소에 전달하는 것만을 다루고 있습니다.