I have a component that contains statement like this.$route.fullPath
, how should I mock value of fullPath
of $route
object if I want to test that component?
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: '/', component: Component } ] const router = new VueRouter({ routes }) const wrapper = mount(ComponentWithRouter, { localVue, router }) expect(wrapper.vm.$route).to.be.an('object')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With