0

I am fairly new to vue, and I have created a router-link with a VueRouter to navigate to a certain page.

<router-link
  @click.native="onRouteClicked(index)"
/>

Now I need to mock this click.native function. I know there is a trigger function for vue components available from vue-test-utils.

But how am I to click.native from a trigger ?

my onRouteClicked looks like this

methods: {
 onRouteClicked: function (index) {
   this.routedIndex = index;
 }

}

my test look like this

const myRouteWrapper = navBar.find('[to="/myroute"]');
myRouteWrapper.trigger('click')
expect(myComp.vm.routedIndex).equal(1);

the routedIndex is not changing at all

Prasanna
  • 4,125
  • 18
  • 41
  • Did you define the `onRouteClicked` function on `methods` object? I believe that should trigger the click event. – Yom T. Jan 06 '19 at 11:15
  • @jom I have updated my question. and yes the onRouteClicked is indeed inside methods object – Prasanna Jan 06 '19 at 11:21
  • TBH, I'm not very familiar with vue-test-utils but I did notice that the [`find`](https://vue-test-utils.vuejs.org/api/wrapper/find.html#find-selector) method expects [3 different types of selectors](https://vue-test-utils.vuejs.org/api/selectors.html#selectors). In this case, perhaps I would check if the library actually transforms the individual `router-link`s into HTML anchor tag with `#/myroute` as the `href` attribute, where we could instead do `navBar.find('[href="#/myroute"]')`. – Yom T. Jan 06 '19 at 13:45
  • 1
    @jom hi, I found the problem. I was not using the VueRouter with a localVue on my tests. And hence the router-link was never trasformed to which inturn never actually triggered the click event. It took a lot of time to find that out though. Should I answer my own question or leave the solution as a comment so that people who are bothered by the problem will find about the solution. – Prasanna Jan 06 '19 at 13:48
  • I would say answer your own question with this solution, people might find this useful in the future, like I did ;) – Yom T. Jan 06 '19 at 13:49

1 Answers1

1

Yeah so after an entire day of effort I guess I should make this a Q&A.

The problem was that I was not using VueRouter. Importing VueRouter and my routes and using them with a localVue did the trick for me.

import VueRouter from 'vue-router'
import { mount, createLocalVue } from '@vue/test-utils'

var localVueInstance = createLocalVue()
localVueInstance.use(VueRouter)

var router = new VueRouter({
   routes: [],
   mode: 'history'
})

And on my tests

var wrapper = mount(navBarComp, {
    propsData,
    localVue: localVueInstance,
    router 
});
var myRouteWrapper = wrapper.find('[href="/myroute"]');
myRouteWrapper.trigger('click')
Prasanna
  • 4,125
  • 18
  • 41