본문으로 바로가기

TDD-사용하기

category JavaScript/Test 2020. 12. 1. 02:14

사용

이번엔 TDD로 만든 모듈들을 불러와서 화면을 구성해 볼 차례다

코드

// in index.html

<body>
    <span class="display"></span>
    <button class="btn-increase">+</button>

<script src="ClickCounter.js"></script>
<script src="ClickCountView.js"></script>

<script>
    (()=>{
    })();
</script>
</body>

우리가 만든 모듈의 인자로 들어갈 div.display와 button.btn-increase를 만들어놓고 스크립트 부분을 구현하려고 한다

즉시 실행 함수를 이용해서 전역 변수 사용을 억제하는 모습

 //in <script>

const clickCounter = App.ClickCounter();
const disElem = document.querySelector('.display');
const btnElem = document.querySelector('.btn-increase');
const view = App.ClickCountView(clickCounter,{disElem, btnElem});

view.updateView();

ClickCountView를 만들기위한 각각의 객체를 생성해준 후에 주입해주어 view를 만들고

초기 데이터 업데이트를 위해 updateView 함수를 실행해 주었다

분명 강의를 보고 따라했는데 이상하게 작동을 안하길래 스크립트 파일을 다시 살펴봤는데 답은 ClickCountView.js에 있었다

ClickCountView.js

var App = App || {};


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

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

    options.buttonElem.addEventListener('click',()=>{
        view.increaseAndUpdateView();
    });

    return view;
}

너무 간단했는데 두개의 엘리먼트를 받아온 ClickCountView가 객체들을 options로 묶어서 사용하고 있기 때문..

options.객체이름 으로 명시해서 사용하고 있기 때문에 넘겨주는 객체의 이름이 다르면 작동을 하지 않나보다

해결

<script>
    (()=>{
        const clickCounter = App.ClickCounter();
        const updateElem = document.querySelector('.display');
        const buttonElem = document.querySelector('.btn-increase');
        const view = App.ClickCountView(clickCounter,{updateElem, buttonElem});

        view.updateView();
    })();
</script>

이제 제대로 작동하는 클릭 카운터를 볼 수 있다

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

TDD-데이터 주입  (0) 2020.12.02
TDD-Event  (0) 2020.11.30
TDD-spyOn  (0) 2020.11.29
TDD-error  (0) 2020.11.27
TDD-view  (0) 2020.11.26