Vue JS JEST 测试

问题描述 投票:0回答:2

尝试运行 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')

无法读取未定义的属性“状态”,但我不明白为什么,我在这里缺少任何明显的东西吗?

vue.js unit-testing jestjs vuex
2个回答
2
投票

在没有初始化 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)
  })
})

演示


0
投票

或者,您可以在测试设置中初始化 Vuex 存储。

import Vuex from 'vuex';


 beforeEach(() => {
    const localVue = createLocalVue();
    localVue.use(Vuex);
})

© www.soinside.com 2019 - 2024. All rights reserved.