Nuxt에서 Vuex(엔클로저 분할)에 종속된 구성 요소 테스트

개시하다


Nuxt에서 스토리지를 모듈로 분할하는 Vuex를 테스트하면 어셈블리 측 호출mapGetters('counter', ['count']) 등 네임스페이스를 인식하지 못하는 현상이 발생합니다.
Nuxt는 자동으로 Vuex 모듈을 가져와 Vuex 인스턴스를 생성하지만 테스트할 때는 자동으로 가져오지 않으므로 네임스페이스를 인식할 수 없습니다.
다음은 대책의 기술입니다. 또 다른 좋은 방법이 있다면 댓글로 남겨주세요.

전제 조건


이 문서에서는 Vuex의 페이지 구성 요소에 대한 테스트를 수행합니다.
또한 테스트jest와 Vue가 있습니다.js를 위한 테스트 라이브러리vue-test-utils를 설치한 전제에서 기술하였다.
https://github.com/vuejs/vue-test-utils

테스트 대상


Vuex store


먼저 Vuex 모듈의 예입니다.
위에서 설명한 대로 Nuxt는 다음 코드를 통해서만 자동으로 네임스페이스가 있는 모듈로 해석됩니다.
store/counter.js
const state = () => ({
  count: 0
})

const getters = {
  count: state => state.count
}

const mutations = {
  increment(state) {
    state.count++
  }
}

const actions = {
  increment({ commit }) {
    commit('increment')
  }
}

export default {
  state,
  getters,
  mutations,
  actions
}

Pages


다음은 페이지 구성 요소입니다.Vuex에서 수치와 동작을 추출하고 표시하는 간단한 내용만 있습니다.이번 테스트에서 이 구성 요소는
pages/counter.vue
<template>
  <div>
    <p>Count: {{ count }}</p>
    <button type="button" @click="increment">Increment</button>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'

export default {
  computed: {
    ...mapGetters('counter', ['count'])
  },

  methods: {
    ...mapActions('counter', ['increment'])
  }
}
</script>

테스트 코드


간단하게 store/counter.jsimport에 Vuex 실례를 생성하더라도 counter 모듈은 명명 공간으로 등록되지 않았기 때문에 다음과 같은 오류가 발생할 수 있습니다.
 [vuex] module namespace not found in mapGetters(): counter/
모듈 대상(본 예시에서 복제 대상)에 속성namespaced을 추가합니다.이렇게 하면 Nuxt에 의존하지 않고 Vuexcounter에 명칭 공간을 등록할 수 있고 페이지 구성 요소mapGetters('counter', ['count'])도 테스트에서 작업할 수 있다.
test/pages/counter.test.js
import Vuex from 'vuex'
import { shallowMount, createLocalVue } from '@vue/test-utils'
import cloneDeep from 'lodash.clonedeep'
import counterPage from '~/pages/counter'
import counterStore from '~/store/counter'

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

describe('pages/counter.vue', () => {
  let store

  beforeEach(() => {
    const clone = cloneDeep(counterStore)

    // ※モジュールを名前空間として登録する為の設定
    clone.namespaced = true

    // ※モックのVuexインスタンスを生成
    store = new Vuex.Store({
      modules: {
        counter: clone
      }
    })
  })

  it('ボタンのクリックでカウントの値が「+1」される', () => {
    const wrapper = shallowMount(counterPage, { store, localVue })
    expect(wrapper.vm.count).toBe(0)
    wrapper.find('button').trigger('click')
    expect(wrapper.vm.count).toBe(1)
  })
})

참고 자료


https://vuex.vuejs.org/ja/guide/modules.html
https://vue-test-utils.vuejs.org/ja/guides/#테스트 구성 요소의 - vuex -

좋은 웹페이지 즐겨찾기