はじめに
Vue.jsのメソッドのテストのみしています。
本当は描画部分もするべきなのでしょうが徐々にしていく予定です。
もし間違いがあったら教えていただけると嬉しいです。
テスト対象
export default {
data() {
return {
age: 0,
};
},
methods: {
greeting(name) {
return `Hello!!${name}`;
},
ageCheck() {
if (this.age < 20) {
return "20歳未満";
} else {
return "20歳以上";
}
},
},
};
name
を引数の取って挨拶を返すgreeting
メソッドとage
に入った値をチェックして
条件分岐したのち値を返すメソッド
テストコード
import {createLocalVue, shallowMount} from '@vue/test-utils'
import test2 from '../test2.vue'
describe('test2.vueのテスト', () => {
const wrapper =shallowMount(test2)//wrapperでコンポーネントをラップする
const vm = wrapper.vm
it('methods-greeting', () => {
expect(vm.greeting("Jon")).toBe("Hello!!Jon")
})
it('methods-ageCheck', () => {//component内のdataを使ってる場合
expect(vm.ageCheck()).toBe("20歳未満")//初期値は0になっている
vm.age = 19//this.ageの部分に代入
expect(vm.ageCheck()).toBe("20歳未満")
vm.age = 20
expect(vm.ageCheck()).toBe("20歳以上")
})
})
こんな感じでテストできます。
wrapper.vm
とすることでラップしたコンポーネントにアクセスできる。
なのでwrapper.vm.greeting('Jon')
としたらコンポーネント内でthis.greeting('Jon')
としているのと同じ様な感じになる。
data
のage
にアクセスする場合もwrapper.vm.age
で値を入れたりできる。
Vuexを使用してる場合
import { createLocalVue, shallowMount } from '@vue/test-utils'
import Vuex from 'vuex'
import { state, mutations, actions, getters } from '@/store/index.js'//使用する部分だけでOK
import Component from '@components/Component.vue'
const localVue = createLocalVue()
localVue.use(Vuex)
describe('Componentのテスト', () => {
beforeEach(() => {
store = new Vuex.Store({
state,
mutations,
actions,
getters
})
const wrapper = shallowMount(Component, { store, localVue })
const vm = wrapper.vm
})
it('テスト', () => {
//テスト項目
})
})
Vuex(store)
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export const state = {}
export const mutations = {}
export const actions = {}
export const getters = {}
export default new Vuex.Store({
state,
mutations,
actions,
getters
})
こんな感じになるのかなと
store
の値とかメソッド
を使う場合はwrapper.vm.$store
とします。
仮にstate
にname
という値があったとして何かする場合は
wrapper.vm.$store.state.name
となります。
getters
を使う場合wrapper.vm.$store.getters.メソッド名(引数)
になります。
以上です。