尝试运行 JEST 单元测试时,我有一个奇怪的行为。
import { shallowMount } from '@vue/test-utils'
import communicationPreferences from '@/pages/account/communication-preferences'
describe('Communication Preferences Page', () => {
it('should render page', () => {
const wrapper = shallowMount(communicationPreferences)
expect(wrapper.exists()).toBe(true)
})
})
页面:communication-preferences.vue
computed: {
...mapState('account', ['communicationPreferences']),
// communicationPreferenceTypeEmail() {
// return this.communicationPreferences.filter((e) => e.type === 'EMAIL')
// },
// communicationPreferenceTypeNotEmail() {
// return this.communicationPreferences.filter((e) => e.type !== 'EMAIL')
// },
},
当我运行
npm run test
并取消注释上面的计算行时,我收到下面的错误,但是当我注释掉它们时,我成功通过了测试。
TypeError: Cannot read property 'state' of undefined
127 | ...mapState('account', ['communicationPreferences']),
128 | communicationPreferenceTypeEmail() {
> 129 | return this.communicationPreferences.filter((e) => e.type === 'EMAIL')
| ^
130 | },
131 | communicationPreferenceTypeNotEmail() {
132 | return this.communicationPreferences.filter((e) => e.type !== 'EMAIL')
无法读取未定义的属性“状态”,但我不明白为什么,我在这里缺少任何明显的东西吗?
在没有初始化 Vuex 存储的情况下尝试
mapState
(或其他 mapXXX
Vuex 实用程序)时会发生这种情况。
global.plugins
安装选项传入商店:
import { shallowMount } from '@vue/test-utils'
import communicationPreferences from '@/pages/account/communication-preferences'
import store from '@/store'
describe('Communication Preferences Page', () => {
it('should render page', () => {
const wrapper = shallowMount(communicationPreferences,
{ 👇
global: {
plugins: [store],
},
}
)
expect(wrapper.exists()).toBe(true)
})
})
或者,您可以在测试设置中初始化 Vuex 存储。
import Vuex from 'vuex';
beforeEach(() => {
const localVue = createLocalVue();
localVue.use(Vuex);
})