본문으로 바로가기

TDD-spyOn

category JavaScript/Test 2020. 11. 29. 03:07

실행 확인 테스트

실질적으로 필요한 기능의 메소드는 다 작성했다

하나하나 호출하고 있을 순 없으니까 이 메소드를 한번에 담아서 실행할 메소드 또한 필요하다

이제 그 메소드인 increaseAndUpdateView를 테스트해야한다

테스트 코드

increaseAndUpdateView에 들어가는 increase와 updateView는 앞서 이미 테스트를 끝냈기 때문에 검증할 필요가 없다

그래서 우리는 increaseAndUpdateView안에서 이 메소드들이 호출되었는지만 확인하면 되는데

spyOn(Object,'method') 라는 함수를 사용한다

인자에서 볼 수 있듯이 첫 인자는 객체를, 두번째 인자로는 실행되었는지 확인할 메소드를 적어준다

(_자세한 설명은 이곳에 https://www.tutorialspoint.com/jasminejs/jasminejs_spies.htm _)

increaseAndUpdateView의 테스트 명세는 'increase를 실행해 값을 증가시키고, updateView를 실행해 뷰를 업데이트 하는 것'이다

뜯어보면 두개의 일을 하고 있기 때문에 두개를 분리해서 테스트하도록 한다

describe('increaseAndUpdateView()',()=>{
  it(('ClickCounter의 increase를 실행한다'),()=>{
    spyOn(clickCounter,'increase');

    clickCountView.increaseAndUpdateView();

    expect(clickCounter.increase).toHaveBeenCalled();
  });

  it(('clickCountView의 updateView를 실행한다'),()=>{
    spyOn(clickCountView,'updateView');

    clickCountView.increaseAndUpdateView();

    expect(clickCountView.updateView).toHaveBeenCalled();
  });
});

spyOn으로 clickCounter와 clickCountView의 increase와 updateView를 감시하고

expect의 toHaveBeenCalled로 실행되었는지 검증하는 테스트 코드다

실제 코드

App.ClickCountView = (clickCounter,options)=>{
    if(!clickCounter) throw Error('ClickCounter가 없습니다');
    if(!updateElem) throw Error('updateElem이 없습니다');

    return {
        updateView(){
            updateElem.innerHTML = clickCounter.getValue();
        },
        increaseAndUpdateView(){
            clickCounter.increase();
            this.updateView();
        }
    }
}

increaseAndUpdateView메소드 에서 increase와 updateView를 실행시켜준다

리팩토링

없다

'JavaScript > Test' 카테고리의 다른 글

TDD-사용하기  (0) 2020.12.01
TDD-Event  (0) 2020.11.30
TDD-error  (0) 2020.11.27
TDD-view  (0) 2020.11.26
TDD 2  (0) 2020.11.25