←  Archives

Vuex(Store)を使ったComponentのテストでActionをDispatchで書いた時のMockの書き方


vue-test-utilsのドキュメントにやり方は書いてあるんだけど、Storeのアクションを dispatch で呼んだ時にどう書くかちょっと悩んだのでメモ。

要はこういうやつ。

<script>
export default {
  mounted() {
    this.$store.dispatch('users/fetch')
  }
}
</script>

Actionのmock定義する際のメソッド名を、dispatchを書く時みたいに 'storename/actionname' みたいにして定義すればよい。

describe('Users', () => {
  let actions
  let store

  beforeEach(() => {
    actions = {
      'users/fetch': jest.fn(),
    }
    store = new Vuex.Store({
      state: {
        users: {
          users: [],
        },
      },
      actions,
    })
  })
...