嗨,我正在使用 vue-test-utils 测试 vue 项目。
我想做的是测试路由器(我的项目使用的是 VueRouter)。
我知道如果我从路由器文件或 VueRouter 导入路由并将其用于 localVue,$route 和 $router 属性是只读的,因此我无法模拟它。
但是当我尝试的时候
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
出现。
实际上,我真正想做的不是模拟路由而是使用真正的路由器,但还有另一个问题..
'Route with name 'something' does not exist' vue-router console.warn when using vue-test-utils
如果您知道这些问题的解决方案,请告诉我!提前感谢您。
答案 0 :(得分:0)
我当然用这个问题的第一个答案解决了这个问题!
似乎在任何地方(甚至在非测试代码中)使用 VueRouter 都会影响模拟 $route。
if (!process || process.env.NODE_ENV !== 'test') {
Vue.use(VueRouter)
}
我在链接问题的第一个答案中使用此代码解决了问题。将此代码用于使用 VueRouter 的地方!