2017-12-11 2 views
1

반응 구성 요소의 span 태그를 onClick 테스트하려고합니다.오류 : 예상 모의 ​​함수가 호출되었습니다

<span id="A" onClick={this.changeImage}> Image A</span> 

'onClick'에 'changeImage'기능이 호출되고 있는지 테스트하고 싶습니다. 같은 오류를 반환

it('Should call changeImage() function on click',() => { 
    const spy = jest.spyOn(wrapper.instance(), 'changeImage'); 
    wrapper.find('#A').simulate('click', { target: { id: 'A' } }); 
    expect(spy).toHaveBeenCalled(); 
}); 

두 -

//은

describe('Tests',() => { 
const wrapper = shallow(<Image />); 
it('Should render without exploading',() => { 
    expect(wrapper).toHaveLength(1); 
}); 

it('Should call changeImage() function on click',() => { 
    wrapper.instance().changeImage = jest.fn(); 
    wrapper.update(); 
    wrapper.find('#A').simulate('click', { target: { id: 'A' } }); 
    expect(wrapper.instance().changeImage).toHaveBeenCalled(); 
    }); 
}); 

는 또한이 시도 test.js. // 오류

● Tests › Should call changeImage() function on click 

expect(jest.fn()).toHaveBeenCalled() 

Expected mock function to have been called. 

누군가가 내가 잘못 뭐하는 거지 지적시겠습니까? 감사.

+0

가능한 복제 (https://stackoverflow.com/questions/43245040/using-jest-to-spy- : 스파이 전에 래퍼를 선언하면이 오류가 발생합니다 on-method-call-in-componentdidmount) –

+0

@OluwafemiSule 고마워요, 알아 냈습니다. 내가 그 링크에서 잘못하고있는 것. :) – remelkabir

+0

'wrapper.instance()'에 대한 참조를 여러 번 호출하는 대신 저장할 수 있습니까? 문제가 해결되었는지 확인 하시겠습니까? 매번 새 인스턴스를 얻는 지 궁금합니다. –

답변

-1

jest.spyOn() 모의 함수 뒤에 래퍼 퍼팅 // 고정 실수

describe('Tests',() => { 
it('Should render without exploading',() => { 
    const wrapper = shallow(<Image />); 
    expect(wrapper).toHaveLength(1); 
}); 

it('Should call changeImage() function on click',() => { 
    const spy = jest.spyOn(Image.prototype, 'changeImage'); 
    const wrapper = shallow(<Image/>); 
    wrapper.find('#A').simulate('click', { target: { id: 'A' } }); 
    expect(spy).toHaveBeenCalled(); 
    spy.mockClear();//clearing the mock functions 
    });  
}); 

는 테스트 작업을했다.

조롱 기능의 경우 const 선언 순서가 중요합니다. 스파이를 처음 선언 한 다음 래퍼를 선언해야합니다. [componentDidMount에서 메서드 호출에 스파이 농담을 사용]의

expect(jest.fn()).toHaveBeenCalled() 

Expected mock function to have been called. 
+0

- 1 작동하는 코드를 붙여 넣는 대신 문제가 무엇인지 설명하십시오. 왜 래퍼가 작동 한 후에 코드를 움직이게 했습니까? 그렇게하면 대답이 다른 사람들에게 도움이 될 수 있습니다. –

+0

공유 프로토 타입 메소드를 감시하고 있기 때문에 객체의 다른 인스턴스가'changeImage'를 호출하면 false positive를 줄 수 있기 때문에 좋은 테스트는 아닙니다. –

+0

@JuanMendes 당신 말이 맞습니다. 다른 인스턴스에서 올바르게 사용하려면 모의 기능을 삭제해야합니다. :) 나는 나의 대답을 편집했다. 그것을 지적 주셔서 감사합니다. – remelkabir

관련 문제