【Jest】Vueのテストを書こう!
11496 ワード
Vueのテストを書こう!
Vue.jsのコンポーネントのテストについてナレッジを貯めていきます。(随時追加)
テキスト表示についてのテスト
import { mount } from '@vue/test-utils'
import HelloWorld from '@/components/HelloWorld.vue'
describe('HelloWorld.vue', () => {
it('renders a HelloWorld', () => {
const wrapper = mount(HelloWorld)
expect(wrapper.text()).toMatch("HelloWorld!!")
})
})
DOM要素についてのテスト
import { mount } from '@vue/test-utils'
import HelloWorld from '@/components/HelloWorld.vue'
describe('HelloWorld.vue', () => {
it('renders a HelloWorld', () => {
const wrapper = mount(HelloWorld)
expect(wrapper.html()).toMatch("<div><p>HelloWorld!!</p></div>")
})
})
子コンポーネントをスタブにしてテスト
shallowMount
メソッドで子コンポーネントをスタブ(代替えの偽物)としてマウントします。
※mount
だと子コンポーネントまですべてマウントされます。
const shallowWrapper = shallowMount(Parent)
console.log(shallowWrapper.html())
- ログの結果
子コンポーネントが<vuecomponent-stub />
とスタブとなって出力されています。
<div><vuecomponent-stub></vuecomponent-stub></div>
コンポーネントのfactory関数を定義する
一番上にvalues
オブジェクトをまとめてdata
にして、新しいwrapper
インスタンスを返すファクトリ関数を宣言します。
このようにすると、すべてのテストでconst wrapper = shallowMount(Foo)
を複製する必要がありません
import { shallowMount } from '@vue/test-utils'
import Foo from './Foo'
const factory = (values = {}) => {
return shallowMount(Foo, {
data () {
return {
...values
}
}
})
}
describe('Foo', () => {
it('welcome メッセージを描画する', () => {
const wrapper = factory()
expect(wrapper.find('.message').text()).toEqual("Welcome to the Vue.js cookbook")
})
it('usernameが7未満のときエラーを描画する', () => {
const wrapper = factory({ username: '' })
expect(wrapper.find('.error').exists()).toBeTruthy()
})
it('usernameが空白のときエラーを描画する', () => {
const wrapper = factory({ username: ' '.repeat(7) })
expect(wrapper.find('.error').exists()).toBeTruthy()
})
it('usernameが7文字かそれ以上のとき、エラーが描画されない', () => {
const wrapper = factory({ username: 'Lachlan' })
expect(wrapper.find('.error').exists()).toBeFalsy()
})
})
参考URL
vue-testing-handbook
➡︎より実践的な使い方がわかる
Author And Source
この問題について(【Jest】Vueのテストを書こう!), 我々は、より多くの情報をここで見つけました https://qiita.com/kottyan/items/9b1b3b25209d426ad501著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .