Skip to content

Latest commit

 

History

History
77 lines (51 loc) · 1.93 KB

using-with-vue-router.md

File metadata and controls

77 lines (51 loc) · 1.93 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 { shallow, createLocalVue } from '@vue/test-utils'
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

import { shallow } from '@vue/test-utils'

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

Installing Vue Router with localVue

import { shallow, createLocalVue } from '@vue/test-utils'
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.

import { shallow } from '@vue/test-utils'

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

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

wrapper.vm.$route.path // /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 globally when you're running tests; use a localVue as detailed above.