我如何为我的组件编写测试,该组件在 Nuxt2 和 Vue 测试实用程序(VTU)中使用 Vuex with Typescript 和 Composition Api?

How can i write test for my component which is use Vuex with Typescript and Composition Api in Nuxt2 and Vue test util(VTU)?

我很难找到一个很好的资源来为我的组件编写测试,该组件在 Nuxt2 中使用 Vuex with Typescript 和 Composition Api,我该怎么做?

这是我的组件代码:

<template>
  <div>
    <div data-test="open-sidebar" @click="openSidebar">
      Sidebar
      <hr>
      <div v-show="getSidebarStatus">Sidebar data</div>
    </div>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, useStore } from '@nuxtjs/composition-api'

export default defineComponent({
  name: 'Index',
  setup() {
    const store = useStore()
    const getSidebarStatus = computed((): any => {
      return store.getters.getSidebarStatus
    })
    const openSidebar = (): void => {
      store.dispatch('openSidebar')
    }
    return {
      getSidebarStatus,
      openSidebar,
    }
  },
})
</script>

这是我的 Vuex 模块:

export const state = () => ({
  isSidebarOpen: false,
})

export const getters = {
  getSidebarStatus(state: any) {
    return state.isSidebarOpen
  },
}

export const mutations = {
  openSidebar: (state: any) => (state.isSidebarOpen = true),
}

export const actions = {
  openSidebar: (context: any) => context.commit('openSidebar'),
}

最后,我找到了解决这个问题的办法:

首先,安装 vuex 如果没有默认安装,然后,在 test/unit 目录中创建一个文件夹,里面有你想要的所有东西,我命名为 __mocks__,然后是store.ts 文件,并将这些代码放在上面:

import { state, getters, mutations, actions } from '~/store/index'

export default function storeConfig() {
  return {
    modules: {
      index: { state, getters, mutations, actions },
    },
  }
}

然后在你的测试文件中 sidebar.spec.ts 放入这些代码:

import { shallowMount, createLocalVue } from '@vue/test-utils'
import Vuex from 'vuex'
import Sidebar from '~/components/layouts/Sidebar/index.vue'
import storeConfig from '~/test/unit/__mocks__/store'

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

// eslint-disable-next-line import/no-named-as-default-member
const store = new Vuex.Store({
  state: storeConfig().modules.index.state,
  getters: storeConfig().modules.index.getters,
  mutations: storeConfig().modules.index.mutations,
  actions: storeConfig().modules.index.actions,
})

describe('layouts/Sidebar.vue', () => {
  test('checks if the sidebar is open', async () => {
    const wrapper = shallowMount(Sidebar, {
      store,
      localVue,
      stubs: {
        NuxtLink: true,
      },
    })
    const openSidebar = wrapper.find('[data-test="open-sidebar"]')

    await openSidebar.trigger('mouseover')

    expect(store.getters.getSidebarStatus).toBe(true)
  })
})

重要说明:您应该从 useStore 中获取 store 而不是组件 useContext 中的

import {useStore} from '@nuxtjs/composition-api'
const store=useStore() // correct
-----------
import {useContext} from '@nuxtjs/composition-api'
const {store}=useContext() // incorrect