Comments (5)
Thanks, I was able to get it working. I expanded the router-link-stub
above to render the link and the to
property. There may be a better way, but this works for me.
import util from 'util';
export const RouterLinkStub = {
name: 'router-link-stub',
render(h) {
return h(
'router-link',
{
attrs: Object.keys(this._props).reduce((attrs, key) => {
attrs[key] = util.inspect(this._props[key]);
return attrs;
}, {})
},
this.$slots.default
);
},
props: ['to']
};
And my test becomes:
import { shallow } from 'vue-test-utils';
import { compileToFunctions } from 'vue-template-compiler';
import { createRenderer } from 'vue-server-renderer';
import GoHome from '@/components/GoHome.vue';
import { RouterLinkStub } from '../utils';
describe('GoHome.vue', () => {
it('renders a router-link with a path', () => {
const wrapper = shallow(GoHome, {
stubs: { 'router-link': RouterLinkStub },
propsData: { path: 'helloworld' },
slots: { default: compileToFunctions('<div>Hello World</div>') }
});
// make sure the `to` attribute exists.
expect(wrapper.element.getAttribute('to'));
const renderer = createRenderer();
renderer.renderToString(wrapper.vm, (err, str) => {
if (err) throw new Error(err);
expect(str).toMatchSnapshot();
});
});
});
which renders the following snapshot:
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`GoHome.vue reners a router-link with a path 1`] = `
<router-link to="{ name: 'Home', params: { path: 'helloworld' } }">
<div>Hello World</div>
</router-link>
`;
from vue-test-utils.
We now include a RouterLink component. You can stub RouterLink like this:
import { mount, RouterLinkStub } from '@vue/test-utils'
const wrapper = mount(Component, {
stubs: {
RouterLink: RouterLinkStub
}
})
wrapper.find(RouterLinkStub)
from vue-test-utils.
I'd love an answer and a good example for doing exactly this. This is the top search result for vue-test-utils router-link
, so I'm going to ask here.
I'm trying to test a simple component that has a <router-link>
in it, and I'm having troubles getting it to work at all. To test my setup, which is using jest, I copied the List.vue
file and test from the jest example. This test runs fine.
My component, GoHome.vue
:
<template>
<router-link :to="{name: 'Home', params: { path: this.path }}"><slot></slot></router-link>
</template>
<script>
export default {
name: 'GoHome',
props: ['path']
};
</script>
and my test GoHome.spec.js
import { shallow } from 'vue-test-utils';
import { compileToFunctions } from 'vue-template-compiler';
import GoHome from '@/components/GoHome.vue';
describe('GoHome.vue', () => {
it('displays default message', () => {
const wrapper = shallow(GoHome, {
stub: ['router-link'],
propsData: { to: 'helloworld' },
slots: { default: compileToFunctions('<div>Hello World</div>') }
});
var bar = wrapper.find('router-link').hasProp('to', 'helloworld');
var foo = wrapper.find('router-link').vm.$attrs.to === 'helloworld';
console.log('foobar', foo, bar);
});
});
First issue was that the slots
do not accept text, only components, which need a root element.
Next, the shallow
wrapper can't mount the component, seemingly it cant find router-link
.
FAIL test\unit\specs\GoHome.spec.js
● Console
console.error node_modules\vue\dist\vue.runtime.c
ommon.js:477
[Vue warn]: Unknown custom element: <router-lin
k> - did you register the component correctly? For re
cursive components, make sure to provide the "name" o
ption.
(found in <Root>)
● GoHome.vue › displays default message
[vue-test-utils]: wrapper.hasProp() must be calle
d on a Vue instance
at throwError (node_modules/vue-test-utils/dist
/vue-test-utils.js:12:9)
at Wrapper.hasProp (node_modules/vue-test-utils
/dist/vue-test-utils.js:605:5)
at Object.<anonymous> (test/unit/specs/GoHome.s
pec.js:12:43)
at Promise (<anonymous>)
at Promise.resolve.then.el (node_modules/p-map/
index.js:42:16)
at <anonymous>
at process._tickCallback (internal/process/next
_tick.js:188:7)
I'm not sure if I'm calling wrapper
correctly or not, or if wrapper.find
is wrong. Does anyone have some examples on testing a component with router-link
.
I'm using vue-test-utils 1.0.0-beta.1
from vue-test-utils.
Sorry, the example in my original post is wrong. I've updated it. If you're still having issues, can you ask a question on stubbing router-link on StackOverflow.
from vue-test-utils.
@eddyerburgh I know I'm late to the discussion, but I believe the method for testing if a stubbed component has been passed the correct prop deserves a small recap. Do you agree with my implementation to test the value of a to
prop on a router-link
element?
import { shallowMount, RouterLinkStub } from '@vue/test-utils';
import ButtonLink from '@/components/ButtonLink.vue';
describe('ButtonLink.vue', () => {
const to = '/companies';
const wrapper = shallowMount(ButtonLink, {
stubs: { RouterLink: RouterLinkStub },
propsData: { to },
});
it('use route provided in props.to as href', () => {
// If you stub a component, the stub copies component props to the stub.
// This means you can check a stubbed component is passed the correct prop
const href = wrapper.find(RouterLinkStub).props('to');
expect(to).toEqual(href);
});
from vue-test-utils.
Related Issues (20)
- `RouterLink.useLink` is missing when using `RouterLinkStub`. HOT 3
- Test child component, which is the root element HOT 3
- Computed value does not update when data updates
- isVisible() not seeing display: none using vitest with jsdom HOT 4
- Testing component with onBeforeRouteLeave hook raising "No active route record was found" warning HOT 1
- vue2 引入 element2. 页面存在table 表格 jest 测试报错 HOT 1
- *.svg?inline issues
- Errors in `setup()` are silent if `render()` throws an error HOT 6
- Check style changes on hover HOT 1
- setData on writable computed property does not seem to work as it does in VTU.1
- classes documentation
- Support Vue 2.7.16 HOT 2
- Vue test utils not updating template when testing composables
- TypeError: $setup.mergeProps is not a function
- Data property is already defined in Props. HOT 1
- Unable to use vitest spy within vue/nuxt 3 component methods. HOT 3
- `findComponent` doesn't find anything when using `@vue/compat` HOT 1
- Components with TS generic HOT 1
- event.keyCode is deprecated
- Change mocks mid-test
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from vue-test-utils.