javascript - vue-test-utils: could not overwrite property $route, 这通常是由于插件将属性添加为只读值引起的

标签 javascript vue.js vuejs2 vue-test-utils

我看了其他关于这个问题的答案,似乎是由于尝试将 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/

相关文章:

JavaScript:pushState 替换搜索字符串中的静态值

javascript - 将日期从毫秒转换为 ISODate 对象

javascript - 如何在回发javascript后保留下拉列表选定的值?

javascript - 从 javascript 中的 xml 文件在谷歌地图上添加标记

php - 如何在 PHP Laravel 中验证复杂的 JSON 数组

vue.js - 在 vue 组件中添加内容

javascript - Vue 本地数据使用 Getter

laravel - 如何将数组从 Controller 传递到 vue.js v-for?

javascript - Vue.js - 在悬停时添加删除按钮并在按下按钮时将其删除

javascript - Vue.js 缓存方法结果?