Vue + Jest 全局配置转移到规范文件中

Vue + Jest global config carrying over into spec files

我正在使用 VueJS 和 Jest 对我的组件进行单元测试。

我还在使用 Bootstrap Vue 库进行样式设置。我需要在我的 Jest 测试中使用这个插件,以删除一些关于未知插件的控制台警告。

我已经创建了一个安装文件:

import { createLocalVue } from '@vue/test-utils'
import BootstrapVue from 'bootstrap-vue'

const localVue = createLocalVue()

localVue.use(BootstrapVue)

并配置 Jest 在每次测试前使用它。

setupFiles: ['<rootDir>/tests/unit/setup']

但是,要从控制台中删除警告,我需要在安装组件时使用 localVue 实例:

const wrapper = shallowMount(MyComponent, {
      localVue,
      propsData: { value: 'someVal }
    })

但是,我无法将在 setup.js 中创建的 localVue 实例放入测试规范文件中。

如果我这样做:

import Vue from 'vue'
import BootstrapVue from 'bootstrap-vue'

Vue.use(BootstrapVue)

它工作正常,但这很糟糕,因为我们不应该在 Jest 测试中使用 Global Vue 实例。

有没有办法做我想做的事,或者我是否必须将 Bootstrap Vue 插件(以及其他出现的插件...)构建到每个测试文件?

您可以尝试将 localVue 变量分配为 setupFiles 中的全局变量。这将允许您在每个测试中访问 localVue 变量,如下所示:

import { createLocalVue } from '@vue/test-utils'
import BootstrapVue from 'bootstrap-vue'

global.localVue = createLocalVue()

global.localVue.use(BootstrapVue)

然后在你的测试中像这样使用它:

const localVue = global.localVue

const wrapper = shallowMount(MyComponent, {
  localVue,
  propsData: { value: 'someVal' }
})