我正在使用element-plus的<el-buton>测试一个组件
我不直接使用,<el-button>在我的连接组件中
import { shallowMount } from '@vue/test-utils'
import { createApp } from 'vue'
import { createStore } from 'vuex'
import App from '@/components/connect'
const store = createStore({
state() {
return {
user: {},
}
},
mutations: {},
})
let wrapper
const app = createApp(App)
app.use(store)
beforeEach(() => {
wrapper = shallowMount(App, {
propsData: {},
global: {
plugins: [store],
},
})
})在对我的组件的所有测试中,我都得到了这个警告:
如果这是一个本机自定义元素,请确保通过compilerOptions.isCustomElement将其排除在组件解析之外。
在github上也被问到:https://github.com/element-plus/element-plus/issues/5830
发布于 2022-02-08 07:09:37
我不知道您所说的“我不直接使用”是什么意思,但是警告告诉您,Jest在浅层安装过程中遍历组件的DOM时找到了这个标记,它也不知道如何解析它,因为它既不是原生DOM标记,也不是已知的组件。
重要注意事项:当浅层安装时Jest存根是子组件并不意味着它不能解决它们。
如果
小丑:“但我不知道<el-button>是什么!”
<el-button>与测试无关,但警告会让您感到烦恼,或者通过遵循警告中显示的链接和指令,将<el-button>声明为web组件(这是假的,但它告诉Jest忽略它);或者在此测试套件中手动将其存根(用空的<div />替换):。
import { config } from '@vue/test-utils'
config.stubs['el-button'] = '<div />'如果
这将使您的包装器知道每个ElementUI的组件和指令是什么。这并不意味着他们不会被绊倒。他们会的,但是Jest会知道它的顽固之处,最重要的是,它将解决他们的dependencies:
import ElementUI from 'element-ui';
beforeEach(() => {
wrapper = shallowMount(App, {
propsData: {},
global: {
plugins: [store, ElementUI],
},
});
});事实上,这是提供它们的正确方法,因为当您使用app.use(SomePlugin)在根实例上安装它们时,它是如何提供给实际应用程序中的实例的。
您应该为应用程序中使用的所有其他插件执行此操作。如果太重复,创建一个助手函数,将当前测试的组件及其设置作为参数传递,返回一个wrapper,其中包含应用程序的所有功能。
一些纯粹主义者可能会说:“但是我不想用所有的全局插件来测试我的组件,我只想用它使用的插件来测试它。”
IMHO,这是错误的。即使组件只使用了几个全局提供的插件,它也(在现场)在提供全部插件的上下文中运行。因此,如果某个全局插件与当前组件之间有任何冲突,您可能希望从这个测试中了解它,而不是从github问题上了解它。
通用包装工厂示例:
import { shallowMount, mount } from '@vue/test-utils'
import SomePlugin from 'some-library';
import SomeOtherPlugin from 'some-other-library';
import { createStore } from 'vuex'
export const useWrapper = (component, setup, shallow = true) => {
const store = createStore({ /* ... */ });
return (shallow ? shallowMount : mount)(component, {
globals: {
plugins: [SomePlugin, SomeOtherPlugin, store]
},
...setup,
})
}Note --这甚至允许您通过setup覆盖globals,如果您愿意的话,但是,IMHO,出于上述原因,这不是一个好主意。
现在,您可以在所有测试中导入useWrapper,这些测试更没有样板:
import { useWrapper } from '../path-to-helpers';
import SomeComponent from '@/components/SomeComponent.vue'
//...
describe('SomeComponent', () => {
let wrapper;
beforeEach(() => {
wrapper = useWrapper(SomeComponent, {
propsData: {} // extend as needed
});
});
it('should do stuff...', () => {
// expect it does stuff...
})
});当您需要mount而不是shallowMount时,将false作为第三个参数传递给useWrapper。
https://stackoverflow.com/questions/71028201
复制相似问题