LoginSignup
0
0

VuexでStoreの値をモックするときに躓いたメモ

Posted at

はじめに

最近コンポーネントテストに力を入れていきたいと思い始めてVueのテストを書くようになったのですが、躓いた箇所があったので個人用にまとめます

問題

コード上で以下のようにstoreの値を参考にしている箇所がありました

$route.getters.isAdmin

ここで、amindtrueにテストでする必要があったので以下のようなコードをかきました

test.spec.ts
import { createLocalVue, mount, shallowMount } from '@vue/test-utils'
import Vuex from 'vuex'

describe('NewsSearch', () => {
  test.only('てすと', () => {
    const wrapper = shallowMount(NewsSearch, {
      localVue,
      store: new Vuex.Store({
        getters: {
            isAdmin: () => {
                return true
            }
        }
      })
    })

    テストのコード
  })
})

しかし、うまくテストが通らず、state周りがモックで来ていないようでした

解決方法

stateをよく確認したところい可能構造になっていました

mainStore.ts
state = new Vuex.Store({
    modules: {
        groups: {
            user,
            hoge,
            fuga
        }
    }
}

user.ts
const getters = {
    isAdmin: (state) => state.isAdmin
}

export defautl {
    hoge,
    getters
}
test.spec.ts
import { createLocalVue, mount, shallowMount } from '@vue/test-utils'
import Vuex from 'vuex'

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

describe('NewsSearch', () => {
  test.only('てすと', () => {
    const wrapper = shallowMount(NewsSearch, {
      localVue,
      store: new Vuex.Store({
        modules: {
          user: {
            getters: {
              isEarlyAccess: () => {
                return true
              }
            }
          }
        }
      })
    })

    テストコード
  })
})

Vuexがモジュールになっていたのでモジュールを正しく指定しました
そしてlocalValueも必要とのことだったので追加をしたところうまく動きました

おわりに

Vuexがテストするの難しくてあまり私の周りではコンポーネントテストが書かれていないのかなと思いました
ですが、慣れたら普通にテスト書く速さまで持っていけそうなのでがんばりたいです

0
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
0
0