【问题标题】:Could not set mocks with $route in vue-test-utils无法在 vue-test-utils 中使用 $route 设置模拟
【发布时间】:2019-08-05 01:23:13
【问题描述】:

我正在尝试练习引用Using a Mock Router 的测试。这是我的代码。

NestedRoute.vue

<template>
<div>
    <div>Nested Route</div>
    <div class="username">
        {{ $route.params.username }}
    </div>
</div>
</template>

<script>
export default {

}
</script>

<style>

</style>

router.js

import Vue from 'vue'
import Router from 'vue-router'

import Home from './views/Home.vue';
import NestedRoute from './views/NestedRoute.vue';

Vue.use(Router)

export const routes = [
  { path: '/', name: 'home', component: Home },
  { path: '/nested-route', name: 'nroute', component: NestedRoute }
];

export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

test.spec.js

import NestedRoute from '@/views/NestedRoute.vue';
import VueRouter from 'vue-router';
import {routes} from '@/router.js'

const localVue = createLocalVue();
localVue.use(VueRouter);

describe('NestedRoute', () => {
        it('renders a username from query string', () => {
            const username = 'tom';
            const $route = {
                params: { username }
            };

            const wrapper = mount(NestedRoute, {
                mocks: {
                    $route
                }
            });

            expect(wrapper.find('.username').text()).toBe(username);
        });
});

当我运行测试时,出现错误[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。

我尝试引用a issue 'Cannot use mocks with localVue',但我无法解决我的问题。如何使用模拟来使用$route

【问题讨论】:

  • 只需删除localVue.use(VueRouter);,一切都会正常。如果你模拟它,你不必包含它;)
  • @ThomasKleßen 谢谢你的回答!但是当我这样做时,the same error is thrown 和测试结果是Expected: "tom", Received: ""

标签: javascript unit-testing vue.js


【解决方案1】:
import { mount, createLocalVue } from '@vue/test-utils'
import MyComponent from '.../../MyComponent'

describe('MyComponent', () => {
  let wrapper

  beforeEach(() => {
    const localVue = createLocalVue()
    wrapper = mount(MyComponent, {
      localVue,
      mocks: {
        $route: {
          params: {
            id: 200000
          }
        }
      }
    })
  })

  it('has $route set', () => {

  })
})

这对我来说是这样的。

简单但非常重要的区别是从router.js 导入routes。在router.js 的Router 中使用的routes 是如何在test.sepec.js 导入的,它会中断localVue 的过程,即仅导入用于全局路由器的路由,在测试规范中污染localVue的测试。

所以,删除

import {routes} from '@/router.js'

来自test.spec.js 将解决这个问题。

【讨论】:

  • 谢谢!我按照您的建议编写测试。但是仍然发生错误...以下是我为它所做的但没有帮助... 1. 为router.js 中未使用的仅测试制作附加组件。因为我曾想过“当组件被引用为路由时,Vue 路由器设置了$route。2. 我删除了localVue
  • 不要删除 localVue。重要的是不要继承连接了路由器的 vue 实例!另外:你不必对你的 router.js 做任何事情。在这种情况下不需要它
猜你喜欢
  • 2018-09-01
  • 2019-05-13
  • 2020-01-02
  • 2021-09-22
  • 2018-05-26
  • 2020-06-08
  • 2021-06-12
  • 2018-05-04
  • 2019-01-18
相关资源
最近更新 更多