테스트/단위 테스트 (Vue)
단위 테스트 - Header 컴포넌트
IT Blue
2021. 9. 7. 16:27
단위 테스트 - Header 컴포넌트
Header.vue
<template>
<header>
<Logo />
<div class="nav nav-pills">
<div
v-for="nav in navigations"
:key="nav.name"
class="nav-item">
<!-- vue 라우터에서는 라우터 링크라는 컴포넌트를 제공 -->
<!-- a 태그를 대체해서 조금 더 효율적으로 페이지를 관리 -->
<RouterLink
:to="nav.href"
active-class="active"
:class="{ active: isMatch(nav.path) }"
class="nav-link">
{{ nav.name }}
</RouterLink>
</div>
</div>
<div
class="user"
@click="toAbout">
<img
:src="image"
:alt="name" />
</div>
</header>
</template>
<script>
import { mapState } from 'vuex'
import Logo from '~/components/Logo'
export default {
components: {
Logo
},
data() {
return {
navigations: [
{
name: 'Search',
href: '/'
},
{
name: 'Movie',
href: '/movie/tt4520988',
path: /^\/movie/ // '/movie'
},
{
name: 'About',
href: '/about'
}
]
}
},
computed: {
...mapState('about', [
'image',
'name'
])
},
methods: {
isMatch(path) {
if (!path) return false
console.log(this.$route)
return path.test(this.$route.fullPath)
},
toAbout() {
this.$router.push('/about')
}
}
}
</script>
...
Header.test.js
import { shallowMount } from '@vue/test-utils'
import router from '~/routes'
import store from '~/store'
import Header from '~/components/Header'
describe('components/Header.vue', () => {
let wrapper
// 각각의 테스트가 동작하기 직전에 실행
beforeEach(async () => {
// window.scrollTo를 모의 함수로 동작하는 것처럼 구성
window.scrollTo = jest.fn()
// 페이지 이동
router.push('/movie/tt1234567')
// 페이지 기다림
await router.isReady()
// Header 컴포넌트 연결
wrapper = shallowMount(Header, {
global: {
plugins: [
router,
store
]
}
})
})
// 각각의 테스트 함수 내부에서는 고유한 환경으로 테스트가 동작해야 함
test('경로 정규표현식이 없는 경우 일치하지 않습니다', () => {
const regExp = undefined
expect(wrapper.vm.isMatch(regExp)).toBe(false)
})
test('경로 정규표현식과 일치해야 합니다', () => {
const regExp = /^\/movie/
expect(wrapper.vm.isMatch(regExp)).toBe(true)
})
test('경로 정규표현식과 일치하지 않아야 합니다', () => {
const regExp = /^\/ITBlue/
expect(wrapper.vm.isMatch(regExp)).toBe(false)
})
})
참고
https://next.vue-test-utils.vuejs.org/guide/advanced/vue-router.html
Testing Vue Router | Vue Test Utils for Vue 3 (2.0.0-rc.14)
Testing Vue Router This article will present two ways to test an application using Vue Router: Using the real Vue Router, which is more production like but also may lead to complexity when testing larger applicationsUsing a mocked router, allowing for more
next.vue-test-utils.vuejs.org