我在运行npm运行测试时遇到问题。错误为
[Vue warn]: Unknown custom element: <nuxt-link> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
边栏CMS.spect.js
import { shallowMount } from "@vue/test-utils";
import SidebarCMS from "../layouts/SidebarCMS";
const factory = () => {
return shallowMount(SidebarCMS, {});
};
describe("SidebarCMS", () => {
test("renders properly", () => {
const wrapper = factory();
expect(wrapper.html()).toMatchSnapshot();
});
});
有人能帮我吗?
您可以在创建实例时stub
子组件。有关存根组件的更多信息,请查看此链接。
这样尝试,这将解决您的警告!。
const factory = () => {
return shallowMount(SidebarCMS, {
stubs: {
'nuxt-link': true,
'any-other-child': true
}
});
};
Naren接受的答案是有效的,但并不能说明所有用例。
用例1:
我不需要访问NuxtLink的内部元素。=>Stubbing是一个很好的选择,所以这导致了Naren的回答:
const wrapper = shallowMount(SidebarCMS, {
props,
global: {
stubs: {
'nuxt-link': true,
},
},
});
用例2:
由于某些原因,我想访问NuxtLink的内部元素。=>Stubbing不起作用,相反,我们可以在测试文件中定义一个自定义组件:
注意:我们仍然需要在存根中列出NuxtLink,并将其设置为false:
wrapper = shallowMount(SidebarCMS, {
props,
global: {
stubs: {
'nuxt-link': false,
},
components: {
'nuxt-link': {
template: '<a><slot/></a>',
},
},
},
});
这样做的目的是用您为其定义的模板替换nuxt链接。内部使用的html元素会被保留,属性(如类或"to"属性(会自动应用。
这意味着,给定nuxt链接的以下用法
<nuxt-link
to="www.example.com"
class="item-class"
><div>ItemContent</div></nuxt-link>
,wrapper.html的输出将是
<a to="www.example.com" class="item-class"><div>ItemContent</div></a>