'Route with name 'something' does not exist' vue-router console.warn when using vue-test-utils

Viewed 809

I'm making test codes for vue.js component which uses vue-router using vue-test-utils.

Here are codes related to this.

const Routes = [{
  ...
 }, ...
 {
  ...,
  path: '/transfers',
  name: 'transfers',
  redirect: '/transfers/all',
  ...
 },...]

Routes.ts

export default class Transfers extends Vue {
  ...
  @Watch('$route', { immediate: true })
  async setDataResource (value: any) {
    const routeParams = value.params
    const paramKey: string = Object.keys(routeParams)[0]
    ...
  }
}

Transfers.vue

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

const localVue = createLocalVue()
localVue.use(VueRouter)
...
const router = new VueRouter({ Routes })

...
describe('Elements', () => {
  const div = document.createElement('div')
  div.id = 'root'
  document.body.appendChild(div)

  router.push({ name: 'transfers', params: { processing: 'all' } })

  const wrapper = shallowMount(Transfers, {
    localVue,
    store,
    router,
    attachTo: '#root'
  })
  ...
})

transfers.test.js

What I wanna do is to test watch on $route with params.

It works well with 'params: { processing: 'all' }' but

console.warn
      [vue-router] Route with name 'transfers' does not exist

appears.

I can use router.push({ name: 'transfers' }) in .vue, so I think the name is registered to routes normally. But only for testing, 'Route with name 'transfers'' seems to not found.

The Routes.ts file originally didn't use name options for routes, but I added it since I can push params to router only using name option. I mean, name options are not necessary for our project!

So my question is,

  • Is there any way to push params to router in test code, without using name option in route?
  • If I should use name option, why does this warning only appears when testing?
1 Answers

I did a lot of testing in the last project I was working on. I always mocked my $route and $router (see snippet). I've created a Codepen (includes the whole file) of a page I was testing. It shows my basic setup and some ways I was testing the routing object. ie

let mocks = {
  $route: {
    path: '/some-path',
    query: {
      amount: null,
      loanType: null
    }
  },
  $router: [],
  $validator: {
    validateAll: jest.fn()
  },
  $toast: {
    show: jest.fn(),
    error: jest.fn()
  },
  $withProcessing: jest.fn()
}

It's a little hard to exactly diagnose your prob without jumping into the code but I hope you get something out of the below that helps you out.

https://codepen.io/RuNpiXelruN/pen/XWRKmoE

Related