LoginSignup
0
1

More than 3 years have passed since last update.

Vue.js~Vuex~JestでTest~

Posted at

はじめに

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')
としているのと同じ様な感じになる。
dataageにアクセスする場合も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とします。
仮にstatenameという値があったとして何かする場合は
wrapper.vm.$store.state.nameとなります。
gettersを使う場合wrapper.vm.$store.getters.メソッド名(引数)
になります。

以上です。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1