-
항해 99 5기 TIL_28항해 99 2022. 2. 6. 10:21
▶ Today I Learned
<TDD>
[Jest]
페이스북에서 만들어진 테스팅 라이브러리,
Test Runner, Test Matcher, Test Mock 프레임워크까지 제공해주기에 편히 사용할 수 있다는 장점이 있음,
그러나 Mocha보다 느리다고 함
[객체 간 비교 vs 원시자료형 간 비교]
테스트 코드를 시행 함에 있어서 다음의 코드를 작성하였다.
if (this.boards.includes(board)) { throw this.addBoard(board); } else { this.boards.push(board); // push에 성공하면 // Site { boards: [ Board { name: '공지사항' } ] } 라는 모양이 된다.
board라는 객체 값을 site라는 배열 안에 중복으로 집어넣게 할 수 없도록 하기 위해
처음엔 board (Board 클래스의 {name: '공지사항'}이라는 객체이다.)를 this.boards 라는 Site클래스의 빈 배열에 넣어주고
두번째로 board가 들어오면 this.boards에 이전의 그 객체가 들어있는지를 본다음 들어있다면 이를 예외처리 throw해주려 하고 있었다.
그러나 여기서 문제가 발생하였다.
분명 식은 맞게 짠 것 같은데 이상하게 board와 this.boards.board가 일치하지 않았다.
원인을 알 수 없어 아래와 같이 콘솔을 찍어보았다.
console.log('여기도 있다!!', board) console.log('디스보드엔 이게들었다!!', this.boards) console.log('보드', this.boards.includes(board)) console.log('이것이 진짜 보드쩜 네임', board.name) console.log('보드 쩜 네임이다', this.boards.includes(board.name))
여기서 발견한 것은 board를 배열 this.boards에 집어넣고도 this.boards.includes(board)의
결과가 true가 아닌 false가 나왔다는 것이다.
아니, 방금 집어넣었는데 왜 해당 값이 존재하지 않을까?
그 이유는 원시자료형은 데이터 전달 시 값을 복제하여 전달하기에 비교할 때는 '값'이 같은지 다른지를 비교하지만
객체는 데이터 전달 시 주소값을 복재한 참조를 전달하기에 비교할 때는 각 객체의 메모리
'참조 주소'가 같은지 다른지를 비교하기 때문이란다.
팀원 분에게 문의해보니 자세히 정리된 블로그가 있어 아래를 참조하니 이해가 쉬웠다.
그렇기에 board라는 객체의 값은 완전 같아도 두 객체간의 주소는 다르기에 이 둘을 다르다고 인식한 includes()가 false를
반환한 것이다.
-> 생성자를 통한 객체 생성식을 보면 아래와 같이 new를 활용하여 매번 새로운 객체를 만들어 내는 형태인 것으로 보인다.
class Board { ... } const noticeBoard1 = new Board('내용') const noticeBoard2 = new Board('내용') ...
각각의 인스턴스는 매번 새롭게 만들어 내는 것이다 보니(나의 추측이지만 그간 생성자를 통해 객체를 만들땐 꼭
new를 써야한다는 말을 들었던 것 같다.) 같은 구조와 내용이더라도 주소값이 다르므로
둘을 비교하면 언제나 false가 나오는 것이다..!
실제로 공식문서를 참조하니 new는 인스턴스(객체) 생성 연산자였다..!
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/new
▶ 느낀 점
오늘 배운 부분은 정말 그동안 깨닫지 못했던 것인데 팀원 분 덕분에 새로운 눈을 뜨게 된 것 같다.
내일 과제를 빠르게 풀어볼 수 있을 듯하다 :)
나도 누군가에게 많은 도움을 줄 수 있도록 계속해서 열심히 공부하고 찾아보고 적용해보고 깨달아야겠다.
오늘도 많진 않지만 지식이 늘어난 느낌이니 머지 않아 할 수 있겠지..!
내일도 화이팅팅이다! ㅎㅎ
▶ 공부 시 참고 링크들
https://overcome-the-limits.tistory.com/455
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw
https://7942yongdae.tistory.com/48
'항해 99' 카테고리의 다른 글
항해 99 5기 TIL_29 (0) 2022.02.07 항해 99 5기 WIL_4 (0) 2022.02.06 항해 99 5기 TIL_27 (0) 2022.02.06 항해 99 5기 TIL_26 (0) 2022.02.05 항해 99 5기 TIL_25 (0) 2022.02.04