Vue.js vue-router anyway to test the navigation guards? Vue.js vue-router anyway to test the navigation guards? vue.js vue.js

Vue.js vue-router anyway to test the navigation guards?


I found a way to do it, importing the router and using simply router.push) to navigate. I also need to stub the vueAuthInstance to authenticate or not the request

    import VueRouter from 'vue-router'    import Vue from 'vue'    import sinon from 'sinon'    import router from '@/router/index'    import vueAuthInstance from '@/services/auth.js'    Vue.use(VueRouter)    describe('Router', () => {      let sandbox      beforeEach(() => {        sandbox = sinon.sandbox.create()        router      })      afterEach(() => {        sandbox.restore()      })      it('should be in history mode', () => {        sandbox.stub(vueAuthInstance, 'isAuthenticated').returns(false)        expect(router.mode).to.eql('history')      })      it('should be able to navigate without authentication', () => {        sandbox.stub(vueAuthInstance, 'isAuthenticated').returns(false)        router.push('/')        expect(router.history.current.path).to.eql('/')        expect(router.getMatchedComponents('/')[0].name).to.eql('HomePage')        router.push('/login')        expect(router.history.current.path).to.eql('/login')        expect(router.getMatchedComponents('/login')[0].name).to.eql('LoginPage')      })      it('should not be able to navigate to protected page when not authenticated', () => {        sandbox.stub(vueAuthInstance, 'isAuthenticated').returns(false)        router.push('/shoppinglists')        expect(router.history.current.path).to.eql('/login')        expect(router.getMatchedComponents('/login')[0].name).to.eql('LoginPage')      })      it('should be able to navigate to protected page when authenticated', () => {        sandbox.stub(vueAuthInstance, 'isAuthenticated').returns(true)        router.push('/shoppinglists')        expect(router.history.current.path).to.eql('/shoppinglists')        expect(router.getMatchedComponents('/shoppinglists')[0].name).to.eql('ShoppingListPage')      })      it('should be able to navigate to unprotected page when authenticated', () => {        sandbox.stub(vueAuthInstance, 'isAuthenticated').returns(true)        router.push('/home')        expect(router.history.current.path).to.eql('/home')        expect(router.getMatchedComponents('/')[0].name).to.eql('HomePage')      })    })