How to write test that mocks the $route object in vue components

I disagree with the top answer – you can mock $route without any issue.

On the other hand, installing vue-router multiple times on the base constructor will cause you problems. It adds $route and $router as read only properties. Which makes it impossible to overwrite them in future tests.

There are two ways to achieve this with vue-test-utils.

Mocking vue-router with the mocks option

const $route = {
    fullPath: 'full/path'
}
const wrapper = mount(ComponentWithRouter, { 
  mocks: {
    $route
  } 
})

wrapper.vm.$route.fullPath // 'full/path'

You can also install Vue Router safely by using createLocalVue:

Installing vue-router safely in tests with createLocalVue

const localVue = createLocalVue()
localVue.use(VueRouter)
const routes = [
 {
   path: "https://stackoverflow.com/",
   component: Component
 }
]
const router = new VueRouter({
 routes
})
const wrapper = mount(ComponentWithRouter, { localVue, router })
expect(wrapper.vm.$route).to.be.an('object')

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)