1
0

More than 3 years have passed since last update.

Vuexのmutations/actionsが実行された事をテストする方法を調べたメモ

Posted at

Store側のテストについては言及があっても、コンポーネント側のテストについてはあまり見かけなかったので調べた内容をメモ。

結論コード

概要

  • Vuex Storeを用意するよ
  • mutationsのStubを用意するよ
  • 上2つをセットしたwrapperでcalledを見るよ

コード

ButtonStuff.vue
<template>
  <button
    type='button'
    @click='doSomething'
  >
    Do something
  </button>
</template>

<script>
export default {
  name: 'ButtonStuff',
  props: {
    // some properties 
  },
  methods: {
    doSomething () {
      // Mutation 
      this.$store.commit('doStoreMutation', {
        hoge: 'hoge',
        foo: 'foo'
      })

    }
  }
}
</script>

ButtonStuff.spec.js
import Vuex from 'vuex'
import chai, { expect, assert } from 'chai'
import sinon from 'sinon'
import sinonChai from 'sinon-chai'
import { shallowMount, createLocalVue } from '@vue/test-utils'
import Component from '@/components/Atoms/ButonStuff.vue'

chai.use(sinonChai)

const localVue = createLocalVue()
localVue.use(Vuex)

describe('ButtonStuff.vue', () => {
    describe('Events', () => {
      describe('Click', () => {
        let store

        // 実際のMutationと同じ名前にする。
        const mutations = {
          doStoreMutationA: sinon.stub(),
          doStoreMutationB: sinon.stub(),
          doStoreMutationC: sinon.stub()
        }

        beforeEach(() => {
          store = new Vuex.Store({
            state: {},
            mutations
          })
        })

        it('should be triggered the mutation', () => {
          const wrapper = shallowMount(Component, { store, localVue })
          wrapper.find('button').trigger('click')
          assert(mutations.doStoreMutationA.called)
        })
      })
    })
  })
})

※ mutationsを例に書いていますが、actionsも同じ方法でいけるはず。

ハマった所

  • テストコード側のmutationsオブジェクトに用意したmutationの名前は実際のstoreにあるmutation名と合わせるところ。あまり意識せずに doStoreMutationMock みたいにしたらキックされなくて悩んだ
  • JestとMocha&chaiでの書き方の違い、それぞれの記法でもう片方はどうするか、実際できるのかがわからず調べるのに時間がかかった。
  • assertを使ってるけど、本当はexpectでやりたいが、書き方がまだわかってない(何パターンか試したがコケる)のでこの項目に関してassertで妥協している
1
0
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
1
0