Search code examples
javascriptvue.jsvue-routerroutervue-test-utils

(vue-test-utils) 'could not overwrite property $route,...'


Hi I'm testing vue project using vue-test-utils.

What I wanna do is to test router (my project is using VueRouter).

I know that if I import routes from router file or VueRouter and use it to localVue, $route and $router properties are read-only so I can't mock it.

But when I tried like

transfers.test.js

import { createLocalVue, shallowMount } from '@vue/test-utils'
// import VueRouter from 'vue-router'
// import routes from '../../router/Routes'
import ElementUI from 'element-ui'
...
const localVue = createLocalVue()
// localVue.use(VueRouter)
localVue.use(ElementUI)
localVue.use(Vuex)
localVue.component('DefaultLayout', DefaultLayout)
// const router = new VueRouter({ routes })
...

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

  const wrapper = shallowMount(Transfers, {
    localVue,
    store,
    mocks: {
      $route: {
        params: { processing: 'failed' }
      }
    },
    // router,
    attachTo: '#root'
  })

  afterAll(() => {
    wrapper.destroy()
  })
...
console.error
      [vue-test-utils]: could not overwrite property $route, this is usually caused by a plugin that has added the property as a read-only value

appears.

Actually, what I truly wanna do is not to mock route but to use real router but there is another issue..

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

If you know the solutions for these issues, please let me know! Thank you for in advance.


Solution

  • I certainly solved this problem with the first answer of this question!

    vue-test-utils: could not overwrite property $route, this is usually caused by a plugin that has added the property as a read-only value

    It seems like using VueRouter in anywhere(even in non-test codes) affects mocking $route.

    if (!process || process.env.NODE_ENV !== 'test') {
        Vue.use(VueRouter)
    }
    

    I solved with this code in the first answer of question linked. Use this code to where VueRouter is used!