반응형
💿 카카오 주소 화면 세팅
테스트 사항은 간단하다.
- 주소 팝업 호출여부를 확인한다
- 주소 검색을 성공 후 값을 세팅한다
<template>
<div>
<button id="postbtn" @click="openPostCode">주소 검색 버튼</button>
<p class="address">{{ address }}</p>
</div>
</template>
<script>
export default {
name: 'PostcodeView',
data() {
return {
address: ''
}
},
mounted() {},
methods: {
openPostCode() {
new window.daum.Postcode({
oncomplete: (data) => {
const { address } = data
this.address = address
}
}).open()
}
}
}
</script>
<style scoped>
button {
border: 2px solid white;
color: #fff;
padding: 10px;
cursor: pointer;
}
.address {
color: #fff;
}
</style>
⏰ 카카오 주소 테스트 코드
주소 팝업 호출 여부 확인
PostCode객체와 open을 가짜로 구현하고,
테스트 작성시에는 open을 감시할 수 있도록 spyOn으로 감시한다.
그리고 버튼을 눌렀을때 PostCode에서 open 호출 여부를 확인한다.
import { shallowMount } from '@vue/test-utils'
import postcodeView from '@/views/mainLayout/postcodeView.vue'
function Postcode(callback) {
this.callback = callback
}
Postcode.prototype.open = jest.fn().mockImplementation(() => {})
describe('카카오 주소 테스트', () => {
let wrapper = null
let spyOn = null
beforeEach(async () => {
wrapper = shallowMount(postcodeView)
spyOn = jest.spyOn(window, 'window', 'get')
// 1.spy를 통해 즉시 구현하고, daum 객체를 리턴해준다. 여기서 PostCode는 필요한 기능을 직접 function 을 통해 작성하였다.
spyOn.mockImplementation(() => {
return {
daum: {
//2.daum객체에 Postcode 객체가 존재하고, open함수도 가짜로 구현하였다.
Postcode
}
}
})
})
afterEach(() => {
// 테스트가 끝나고 mockRestore해준다
spyOn.mockRestore()
})
test('주소 검색 버튼을 누르면 카카오 주소 검색 팝업이 뜬다', async () => {
//3. open함수를 감시 할 수 있도록 spyOn을 통해 추가해준다.
const spyPost = jest.spyOn(Postcode.prototype, 'open')
const postBtn = wrapper.findComponent('#postbtn')
await postBtn.trigger('click')
//4.open 함수 호출 여부를 확인한다.
expect(spyPost).toHaveBeenCalled()
})
})
카카오 주소 oncomplete 테스트
여기서 new를 통해 PostCode를 생성한다.
그리고 new를 통해 생성된 객체 result에 인자로 넣었던 oncomplete를 호출한다
그리고 oncomplete를 통해 세팅된 결과값 address가 같은지 확인한다.
import { shallowMount } from '@vue/test-utils'
import postcodeView from '@/views/mainLayout/postcodeView.vue'
function Postcode(callback) {
this.callback = callback
}
Postcode.prototype.open = jest.fn().mockImplementation(() => {})
describe('카카오 주소 테스트', () => {
let wrapper = null
let spyOn = null
beforeEach(async () => {
wrapper = shallowMount(postcodeView)
spyOn = jest.spyOn(window, 'window', 'get')
spyOn.mockImplementation(() => {
return {
daum: {
Postcode
}
}
})
})
afterEach(() => {
spyOn.mockRestore()
})
test('주소검색에서 받은 값을 세팅한다 ', async () => {
const result = new Postcode({
oncomplete: (data) => {
wrapper.vm.address = data.address
}
})
result.callback.oncomplete({
address: '서울시 마포구'
})
expect(wrapper.vm.address).toBe('서울시 마포구')
})
})
반응형
'테스트코드' 카테고리의 다른 글
| 🔗 vuex jest 사용 (1) | 2024.03.31 |
|---|---|
| 💿 부모컴퍼넌트에서 emit 테스트 (1) | 2024.03.18 |
| 🍟 jest 에서 setTimeOut,setInterVal을 사용하기 (0) | 2024.02.27 |
| 🌮 부모컴퍼넌트에 Video 태그가 있는 경우의 단위테스트 (1) | 2024.01.22 |
| lottie, $route 모킹 (0) | 2024.01.02 |
댓글