Skip to content

Latest commit

 

History

History
71 lines (47 loc) · 1.68 KB

using-with-vue-router.md

File metadata and controls

71 lines (47 loc) · 1.68 KB

Using with Vue Router

Installing Vue Router in tests

You should never install Vue Router on the Vue base constructor in tests. Installing Vue Router adds $route and $router as read-only properties on Vue prototype.

To avoid this, we can create a localVue, and install Vue Router on that.

import VueRouter from 'vue-router'
const localVue = createLocalVue()

localVue.use(VueRouter)

shallow(Component, {
  localVue
})

Testing components that use router-link or router-view

When you install Vue Router, the router-link and router-view components are registered. This means we can use them anywhere in our application without needing to import them.

When we run tests, we need to make these vue-router components available to the component we're mounting. There are two methods to do this.

Using stubs

shallow(Component, {
  stubs: ['router-link', 'router-view']
})

Installing Vue Router with localVue

import VueRouter from 'vue-router'
const localVue = createLocalVue()

localVue.use(VueRouter)

shallow(Component, {
  localVue
})

Mocking $route and $router

Sometimes you want to test that a component does something with parameters from the $route and $router objects. To do that, you can pass custom mocks to the Vue instance.

const $route = {
  path: '/some/path'
}

const wrapper = shallow(Component, {
  mocks: {
    $route
  }
})

wrapper.vm.$router // /some/path

Common gotchas

Installing Vue Router adds $route and $router as read-only properties on Vue prototype.

This means any future tests that try to mock $route or $router will fail.

To avoid this, never install Vue Router when you're running tests.