Skip to content

Commit 032fe20

Browse files
committed
docs: add using with vue router
1 parent 03e2a37 commit 032fe20

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
# Using with vue-router
2+
3+
## Installing vue-router in tests
4+
5+
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.
6+
7+
To avoid this, we can create a localVue, and install vue-router on that.
8+
9+
```js
10+
import VueRouter from 'vue-router'
11+
const localVue = createLocalVue()
12+
13+
localVue.use(VueRouter)
14+
15+
shallow(Component, {
16+
localVue
17+
})
18+
```
19+
20+
## Testing components that use router-link or router-view
21+
22+
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.
23+
24+
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.
25+
26+
### Using stubs
27+
28+
```js
29+
shallow(Component, {
30+
stubs: ['router-link', 'router-view']
31+
})
32+
```
33+
34+
### Installing vue-router with localVue
35+
36+
```js
37+
import VueRouter from 'vue-router'
38+
const localVue = createLocalVue()
39+
40+
localVue.use(VueRouter)
41+
42+
shallow(Component, {
43+
localVue
44+
})
45+
```
46+
47+
## Mocking $route and $router
48+
49+
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.
50+
51+
```js
52+
const $route = {
53+
path: '/some/path'
54+
}
55+
56+
const wrapper = shallow(Component, {
57+
mocks: {
58+
$route
59+
}
60+
})
61+
62+
wrapper.vm.$router // /some/path
63+
```
64+
65+
## Common gotchas
66+
67+
Installing vue-router adds `$route` and `$router` as read-only properties on Vue prototype.
68+
69+
This means any future tests that try to mock $route or `$router` will fail.
70+
71+
To avoid this, never install vue-router when you're running tests.

0 commit comments

Comments
 (0)