vue-test-utils:无法覆盖属性 $route,这通常是由将该属性添加为只读值的插件引起的

2024-03-19

我看过有关此问题的其他答案,这似乎是由于尝试导入引起的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)
    })
})

Then in 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 的一个错误。如果你使用的是VueRouteranywhere(即使它没有在任何单元测试中使用),你会得到上面的错误。

解决方法是在单元测试中使用 process.env.NODE_ENV 并将其设置为“test”,无论您在何处使用 VueRouter,请像这样检查 process.env.NODE_ENV:

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

至少在 vue-test-utils bug 修复之前,这应该可以解决这个问题

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

vue-test-utils:无法覆盖属性 $route,这通常是由将该属性添加为只读值的插件引起的 的相关文章

随机推荐