我看了其他关于这个问题的答案,似乎是由于尝试将 vue-router
导入测试引起的。但是,我的问题并非如此。这是我的测试代码:
import { mount, shallowMount, createLocalVue } from '@vue/test-utils'
import ListDetails from '../components/homepage/ListDetails'
import EntityList from '../components/homepage/EntityList'
import BootstrapVue from 'bootstrap-vue'
import Vuex from 'vuex'
import faker from 'faker'
const localVue = createLocalVue()
localVue.use(Vuex)
localVue.use(BootstrapVue)
describe('ListDetails.vue', () => {
it('gets the correct page list when router list id param present', () => {
const selected_list = {
id: faker.random.number(),
name: faker.lorem.words(),
entries: []
}
testRouteListIdParam(selected_list)
})
})
然后在 testRouteListIdParam
中,我有:
function testRouteListIdParam(selected_list) {
// just assume this sets up a mocked store properly.
const store = setUpStore(selected_list, true)
const $route = {
path: `/homepage/lists/${selected_list.id}`
}
const wrapper = mount(ListDetails, {
mocks: {
$route
},
store,
localVue
})
}
一旦 mount()
发生,我就会得到错误:
[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
知道为什么会发生这种情况吗?同样,我没有在单元测试中的任何地方使用 VueRouter,所以我不确定为什么会出现错误。是不是 BootstrapVue 或 Vuex 把事情搞砸了?
最佳答案
所以这是 vue-test-utils 的一个错误。如果你在 anywhere 使用 VueRouter(即使它没有在任何单元测试中使用),你也会得到上面的错误。
解决方法是在单元测试中使用 process.env.NODE_ENV 并将其设置为“测试”,无论您在何处使用 VueRouter,都像这样检查 process.env.NODE_ENV:
if (!process || process.env.NODE_ENV !== 'test') {
Vue.use(VueRouter)
}
至少在修复 vue-test-utils 错误之前,这应该可以解决这个问题
关于javascript - vue-test-utils: could not overwrite property $route, 这通常是由于插件将属性添加为只读值引起的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55523639/