Vue:UnitTest
lastmod 2021-07-27created 2020-10-167 edits
| WARNING |
| If you want to use a library for testing, see the Vue Test Utils page |
Simple testing
In terms of code structure for testing, there is nothing special you need to do. Just export the raw options.
<template>
<span>{{ message }}</span>
</template>
<script>
export default {
data () {
return {
message: 'hello!'
}
},
created () {
this.message = 'bye!'
}
}
</script>
When testing the component, Import the options object together with Vue and run the tests. (Here, Jasmine/Jest-style expect assertions are used as an example)
// Vue 및 테스트할 컴포넌트 가져오기
import Vue from 'vue'
import MyComponent from 'path/to/MyComponent.vue'
// Jasmine 2.0 테스트는 다음과 같습니다.
// 원하는 테스트 러너 / 테스트 라이브러리를 사용하십시오
describe('MyComponent', () => {
// 원시 컴포넌트 옵션을 검사합니다.
it('has a created hook', () => {
expect(typeof MyComponent.created).toBe('function')
})
// 원시 컴포넌트 옵션에서 함수 결과를 테스트합니다.
it('sets the correct default data', () => {
expect(typeof MyComponent.data).toBe('function')
const defaultData = MyComponent.data()
expect(defaultData.message).toBe('hello!')
})
// 마운트 할 때 컴포넌트 인스턴스를 검사합니다.
it('correctly sets the message when created', () => {
const vm = new Vue(MyComponent).$mount()
expect(vm.message).toBe('bye!')
})
// 인스턴스를 마운트하고 출력된 결과를 검사합니다.
it('renders the correct message', () => {
const Constructor = Vue.extend(MyComponent)
const vm = new Constructor().$mount()
expect(vm.$el.textContent).toBe('bye!')
})
})
Writing testable components
The render output of many components is mainly determined by the props they receive. In fact, if a component's render output depends solely on its props, it is very easy to test, just like checking the return value of a pure function with different arguments. See the example below.
You can specify the render output with different props using the propsData option.
import Vue from 'vue'
import MyComponent from './MyComponent.vue'
// 렌더링 된 텍스트를 마운트하고 반환하는 헬퍼 함수
function getRenderedText (Component, propsData) {
const Constructor = Vue.extend(Component)
const vm = new Constructor({ propsData: propsData }).$mount()
return vm.$el.textContent
}
describe('MyComponent', () => {
it('renders correctly with different props', () => {
expect(getRenderedText(MyComponent, {
msg: 'Hello'
})).toBe('Hello')
expect(getRenderedText(MyComponent, {
msg: 'Bye'
})).toBe('Bye')
})
})
See also
- vue
- Vue Test Utils (vue-test-utils) - a library for testing Vue