10

I am currently stuck on unit testing the routing behavior of a vue component with jest. When leaving the component, the 'beforeRouteLeave' navigation guard of Vue-router runs some logic. This guard gets called in my application running in production, but won't gets called when I try to test it.

I use jest as a testing framework and vue-test-utils to mount my component and set up a local Vue instance with vue-router.

Here you can find a minimal working example (test in 'src/components/HelloWorld.spec'):

https://codesandbox.io/s/72536ojvp6?module=%2Fsrc%2Fcomponents%2FHelloWorld.spec.js

Why isn't the router hook called and how can I make it work? Thanks in advance!

skyboyer
  • 22,209
  • 7
  • 57
  • 64
mightyI
  • 101
  • 2
  • 4

1 Answers1

1

For me the following code worked fine for testing vue router navigation guards.

const beforeRouteUpdate = wrapper.vm.$options.beforeRouteUpdate[0];
let nextFun = jest.fn();

// in place wrapper.vm you can send any object you want bcz when we call beforeRouteUpdate it looses this context

beforeRouteUpdate.call(wrapper.vm , "toObj", "fromObj", nextFun); 

beforeRouteEnter route navigation guard github

Pallamolla Sai
  • 2,337
  • 1
  • 13
  • 14