无法测试 Vue 组件,因为未定义 Vue 实例

Can't Test Vue Component because Vue instance not defined

我有一个使用 Vue Analytics 的 Vue 应用程序,它创建了一个 this.$ga.page 方法来进行页面跟踪。现在,我需要使用 Jest 测试我的组件,但它说 this.$ga.page 未定义。我正在 main.js.

中初始化 Vue Analytics

如何在测试文件中的组件前包含 main.js?我知道我们需要在 beforeEach 方法中添加它,但我不知道具体怎么做。

Vue Analytics 在 main.js

中初始化
import VueAnalytics from 'vue-analytics'

Vue.use(VueAnalytics, {
  id: 'UA-150437966-1'
})

我的主页测试

import { mount } from '@vue/test-utils'
import Homepage from '../../src/Pages/Homepage'


describe('Homepage', () => {
    const wrapper = mount(Homepage)

    it('has a button', () => {
        expect(wrapper.contains('button')).toBe(true)
    })
})

Homepage.vue 节选

created: function() {
    //analytics

    this.$ga.page({
      page: "/",
      title: "Home page",
      location: window.location.href
    });
  }
};

我收到错误

Homepage › encountered a declaration exception

    TypeError: Cannot read property 'page' of undefined

      67 |     //analytics
      68 | 
    > 69 |     this.$ga.page({

Vue Test Utils 建议在 localVue 中设置您的插件以避免污染全局 Vue。这就是它的样子:

import { localVue, mount } from '@vue/test-utils'
import Homepage from '@/components/Homepage'

localVue.use(VueAnalytics, { id: 'UA-150437966-1' })

describe('Homepage', () => {
  let wrapper = null

  beforeEach(() => {
    wrapper = mount(Homepage, {
      localVue,
    })
  })

  // ...
})

另一方面,如果在您的测试中修改全局 Vue 无关紧要,您可以使用 setupTestFrameworkScriptFile:

设置 Jest 23.x 环境
// jest.config.js
module.exports = {
  setupTestFrameworkScriptFile: '<rootDir>/tests/jest-setup.js',
}

并且在您的设置文件中,您可以初始化 Vue Analytics:

// <rootDir>/tests/jest-setup.js
import Vue from 'vue'
import VueAnalytics from 'vue-analytics'

Vue.use(VueAnalytics, {
  id: 'UA-150437966-1'
})