我目前正在使用 mochajs 为项目编写单元测试
我在用着
"@vue/cli-plugin-typescript": "~4.5.15",
"vuex": "~4.0",
"vue": "^3.2.26",
我的商店在商店文件夹中,我有一个 index.js 文件,其中导入了我的所有模块,我用它们创建了一个商店,最后我像这样导出它
export function useStore(): Store<RootState>{
return store as Store<RootState>
}
问题是如果我在组件文件夹中有一个看起来像这样的组件
<template>
<div>TEST</div>
</template>
<script lang="ts" setup>
import {useStore} from "@/store";
const store = useStore()
</script>
你可以注意到我使用的是setup标签而不是 setup 方法
如果我把在我的单元测试文件中
import {shallowMount } from '@vue/test-utils'
import test from '@/components/test.vue'
describe('test.vue', () => {
it('test', () => {
const wrapper = shallowMount(test,)
})
})
我会收到这个错误
MOCHA Testing...
RUNTIME EXCEPTION Exception occurred while loading your tests
ReferenceError: Cannot access 'store' before initialization
at useStore (/Users/user/x/y/dist/assets/js/webpack:/src/store/index.ts:25:1)
我也尝试创建一个新商店并像这样的插件一样传递它,但我遇到了同样的错误
import {shallowMount, } from '@vue/test-utils'
import test from '@/components/test.vue'
import {createStore, Store} from "vuex";
describe('test.vue', () => {
let store: Store<any>
beforeEach(()=>{
store = createStore<any>({
state:{
test: 'test'
}
})
})
it('test', () => {
const wrapper = shallowMount(test,{
global: {plugins:[store]}
})
})
})