6

I'm testing a Single file component that uses vue router to watch $route. The problem is that I can't get the test to both change the route and trigger the watcher's function.

The test file:

import { createLocalVue, shallow } from 'vue-test-utils';

import Vue from 'vue';
import Vuex from 'vuex';
const localVue = createLocalVue();
localVue.use(Vuex);

const $route = {
  path: '/my/path',
  query: { uuid: 'abc' },
}

wrapper = shallow({
  localVue,
  store,
  mocks: {
   $route,
  }
});

it('should call action when route changes', () => {
    // ensure jest has a clean state for this mocked func
    expect(actions['myVuexAction']).not.toHaveBeenCalled();
    vm.$set($route.query, 'uuid', 'def');
    //vm.$router.replace(/my/path?uuid=def') // tried when installing actual router
    //vm.$route.query.uuid = 'def'; // tried
    //vm.$route = { query: { uuid: 'def'} }; // tried
    expect(actions['myVuexAction']).toHaveBeenLastCalledWith({ key: true });
});

My watch method in the SFC:

  watch: {
    $route() {
      this.myVuexAction({ key: true });
    },
  },

How do you mock router in such a way that you can watch it and test the watch method is working as you expect?

Brandon Deo
  • 4,195
  • 4
  • 25
  • 42

4 Answers4

2

This is how I'm testing a watch on route change that adds the current route name as a css class to my app component:

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

import MyApp from './MyApp'

describe('MyApp', () => {
  it('adds current route name to css classes on route change', () => {
    // arrange
    const localVue = createLocalVue()
    localVue.use(VueRouter)
    const router = new VueRouter({ routes: [{path: '/my-new-route', name: 'my-new-route'}] })
    const wrapper = shallowMount(MyApp, { localVue, router })

    // act
    router.push({ name: 'my-new-route' })

    // assert
    expect(wrapper.find('.my-app').classes()).toContain('my-new-route')
  })
})
Jason Watmore
  • 4,521
  • 2
  • 32
  • 36
2

Tested with vue@2.6.11 and vue-router@3.1.3.

I checked how VueRouter initializes $route and $router and replicated this in my test. The following works without using VueRouter directly:

const localVue = createLocalVue();

// Mock $route
const $routeWrapper = {
    $route: null,
};
localVue.util.defineReactive($routeWrapper, '$route', {
    params: {
        step,
    },
});
Object.defineProperty(localVue.prototype, '$route', {
    get() { return $routeWrapper.$route; },
});

// Mock $router
const $routerPushStub = sinon.stub();
localVue.prototype.$router = { push: $routerPushStub };

const wrapper = shallowMount(TestComponent, {
    localVue,
});

Updating $route should always be done by replacing the whole object, that is the only way it works without using a deep watcher on $route and is also the way VueRouter behaves:

$routeWrapper.$route = { params: { step: 1 } };
await vm.wrapper.$nextTick(); 

Source: install.js

Frederik Claus
  • 574
  • 4
  • 15
0

Its working for me

let $route = {
  name: 'any-route',
};

We defined a $route and we called like

  wrapper = mount(YourComponent, {
    mocks: {
      $route,
    },
  });

and my componente is like this

  @Watch('$route', { deep: true, immediate: true, })
  async onRouteChange(val: Route) {
    if (val.name === 'my-route') {
      await this.getDocumentByUrl();
      await this.allDocuments();
    }
   };

pd: I use typescript, but this work with the another format

and finally my test

it('my test', ()=>{
    const getDocumentByUrl = jest.spyOn(wrapper.vm, 'getDocumentByUrl');
    const allDocuments = jest.spyOn(wrapper.vm, 'allDocuments');
    wrapper.vm.$route.name = 'my-route';
    await flushPromises();
    expect(getDocumentByUrl).toHaveBeenCalled();
    expect(allDocuments).toHaveBeenCalled();
})
Kevin Mendez
  • 651
  • 5
  • 10
-1

The way to do this actually is to use vue-test-utils wrapper method, setData.

wrapper.setData({ $route: { query: { uuid: 'def'} } });

Brandon Deo
  • 4,195
  • 4
  • 25
  • 42