Vue-Test-Utils Unknown custom element: <router-link>
With Vue 3 and Vue Test Utils Next (v4), it seems you just have to add your router
(the return object from createRouter
) as a plugin to your mountOptions
:
import router from "@/router";
const mountOptions = {
global: {
plugins: [router],
},
};
https://next.vue-test-utils.vuejs.org/api/#global
Or a more full example:
import router from "@/router";
import Button from "@/components/Button.vue";
const mountOptions = {
global: {
mocks: {
$route: "home",
$router: {
push: jest.fn(),
},
},
plugins: [router],
},
};
it("Renders", () => {
const wrapper = shallowMount(Button, mountOptions);
expect(wrapper.get("nav").getComponent({ name: "router-link" })).toExist();
});
Note, in the example above I'm using a project setup with Vue CLI.
Add the router-link
stub to the shallow
(or shallowMount
) method options like this:
const wrapper = shallow(TempComponent, {
propsData: { temp },
stubs: ['router-link']
})
or this way:
import { RouterLinkStub } from '@vue/test-utils';
const wrapper = shallow(TempComponent, {
propsData: { temp },
stubs: {
RouterLink: RouterLinkStub
}
})
The error should go away after you do this.
Worked for me:
[ Package.json ] file
...
"vue-jest": "^3.0.5",
"vue-router": "~3.1.5",
"vue": "~2.6.11",
"@vue/test-utils": "1.0.0-beta.29",
...
[ Test ] file
import App from '../../src/App';
import { mount, createLocalVue } from '@vue/test-utils';
import VueRouter from 'vue-router';
const localVue = createLocalVue();
localVue.use(VueRouter);
const router = new VueRouter({
routes: [
{
name: 'dashboard',
path: '/dashboard'
}
]
});
describe('Successful test', ()=>{
it('works', ()=>{
let wrapper = mount(App, {
localVue,
router
});
// Here is your assertion
});
});
Or you can try this: