Vue JS JEST测试

brvekthn  于 12个月前  发布在  Jest
关注(0)|答案(2)|浏览(125)

我在尝试运行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,但我不明白为什么,有什么明显的我错过了这里?

o75abkj4

o75abkj41#

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

demo

bbmckpt7

bbmckpt72#

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

import Vuex from 'vuex';

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

相关问题