Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a component that contains statement like this.$route.fullPath, how should I mock value of fullPathof $route object if I want to test that component?

like image 598
Jerry Zhang Avatar asked Jan 04 '17 07:01

Jerry Zhang


1 Answers

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') 
like image 135
Edward Avatar answered Sep 21 '22 23:09

Edward