This recipe utilizes routes of application under test and enables assertions on navigation redirects.
Steps to mock Vue Router:
- Separate router creation from route declarations
- Helper function to create router for unit testing
This separation will enable helper functions in vue-test-utils-helper
library to discover and mock all routes.
// src/routes.js
import Todos from './views/Todos.vue';
import About from './views/About.vue';
export default [
{
path: '/',
name: 'todos',
component: Todos,
},
{
path: '/about',
name: 'about',
component: About,
},
];
// tests/unit/helpers/mockRouter.js - create router for unit testing
import routes from '@/routes'
import VueRouter from 'vue-router'
import { mockRouterComponents } from 'vue-test-utils-helpers'
export default {
mock () {
const clearedRoutes = mockRouterComponents(routes)
return new VueRouter({
mode: 'abstract',
routes: clearedRoutes
})
}
}