How to unit test VueJS watcher on $route
Asked Answered
N

5

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?

Napkin answered 15/12, 2017 at 15:32 Comment(0)
N
-1

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

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

Napkin answered 15/12, 2017 at 17:32 Comment(1)
It doesn't seem to trigger anything for me .. do you have a full code example for your test ?Calamander
V
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')
  })
})
Vitavitaceous answered 16/7, 2018 at 4:49 Comment(0)
L
2

Tested with [email protected] and [email protected].

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

Lieutenant answered 5/5, 2020 at 15:58 Comment(0)
L
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();
})
Logarithmic answered 23/4, 2021 at 1:0 Comment(0)
P
0

Having "await router.isReady()" sets up the router and then listens to watchers.

wrapper.vm.router.push('/')
    
// After this line, router is ready
await wrapper.vm.router.isReady()

https://test-utils.vuejs.org/guide/advanced/vue-router

Parricide answered 2/10 at 18:43 Comment(0)
N
-1

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

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

Napkin answered 15/12, 2017 at 17:32 Comment(1)
It doesn't seem to trigger anything for me .. do you have a full code example for your test ?Calamander

© 2022 - 2024 — McMap. All rights reserved.