Reputation: 2164
I'm trying to practice of test referencing Using a Mock Router. Here is my code.
NestedRoute.vue
<template>
<div>
<div>Nested Route</div>
<div class="username">
{{ $route.params.username }}
</div>
</div>
</template>
<script>
export default {
}
</script>
<style>
</style>
router.js
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue';
import NestedRoute from './views/NestedRoute.vue';
Vue.use(Router)
export const routes = [
{ path: '/', name: 'home', component: Home },
{ path: '/nested-route', name: 'nroute', component: NestedRoute }
];
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes
})
test.spec.js
import NestedRoute from '@/views/NestedRoute.vue';
import VueRouter from 'vue-router';
import {routes} from '@/router.js'
const localVue = createLocalVue();
localVue.use(VueRouter);
describe('NestedRoute', () => {
it('renders a username from query string', () => {
const username = 'tom';
const $route = {
params: { username }
};
const wrapper = mount(NestedRoute, {
mocks: {
$route
}
});
expect(wrapper.find('.username').text()).toBe(username);
});
});
When I run test it, the error [vue-test-utils]: could not overwrite property $route, this is usually caused by a plugin that has added the property as a read-only value
is occurred.
I tried to reference a issue 'Cannot use mocks with localVue', but I couldn't resolve my issue. How can I use a mock to use $route
Upvotes: 3
Views: 5891
Reputation: 2536
import { mount, createLocalVue } from '@vue/test-utils'
import MyComponent from '.../../MyComponent'
describe('MyComponent', () => {
let wrapper
beforeEach(() => {
const localVue = createLocalVue()
wrapper = mount(MyComponent, {
localVue,
mocks: {
$route: {
params: {
id: 200000
}
}
}
})
})
it('has $route set', () => {
})
})
This is how it works for me.
The simple but very important difference is that importing routes
from router.js
. Some how the routes
used in Router
of router.js
is imported at the test.sepec.js
and it interrupt the process of localVue
i.e, just importing routes, which is used in global router, in the test spec pollute localVue of the test.
So, remove
import {routes} from '@/router.js'
from the test.spec.js
will resolve this problem.
Upvotes: 3