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

5
  • Did you define the onRouteClicked function on methods object? I believe that should trigger the click event. Commented Jan 6, 2019 at 11:15
  • @jom I have updated my question. and yes the onRouteClicked is indeed inside methods object Commented Jan 6, 2019 at 11:21
  • TBH, I'm not very familiar with vue-test-utils but I did notice that the find method expects 3 different types of selectors. In this case, perhaps I would check if the library actually transforms the individual router-links into HTML anchor tag with #/myroute as the href attribute, where we could instead do navBar.find('[href="#/myroute"]'). Commented Jan 6, 2019 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 <a href="" /> 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. Commented Jan 6, 2019 at 13:48
  • I would say answer your own question with this solution, people might find this useful in the future, like I did ;) Commented Jan 6, 2019 at 13:49

1 Answer 1

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')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.