我在尝试运行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')
无法读取属性'state'的undefined,但我不明白为什么,有什么明显的我错过了这里?
2条答案
按热度按时间o75abkj41#
在没有初始化Vuex存储的情况下尝试
mapState
(或其他mapXXX
Vuex实用程序)时会发生这种情况。解决方案
解决这个问题的一种方法是通过
global.plugins
挂载选项传入商店:demo
bbmckpt72#
或者,您可以在测试设置中初始化Vuex商店。