无法在vue-test-utils中使用$ route设置模拟

时间:2019-03-14 08:06:17

标签: javascript unit-testing vue.js

我正在尝试练习引用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

1 个答案:

答案 0 :(得分: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', () => {

  })
})

这就是我的工作方式。

简单但非常重要的区别是routes导入router.js 。在routes中导入Router的{​​{1}}中使用的router.js的某些方式,它会中断test.sepec.js的过程,即仅导入路由,在全局路由器中,测试规范会污染测试的localVue。

所以,删除

localVue
来自import {routes} from '@/router.js'

将解决此问题。