vue-router在运行测试期间不会重置

时间:2017-08-02 07:51:24

标签: unit-testing vuejs2 vue-router

目前我正在为Vue.js app编写测试并遇到问题:如果有一些路由测试,href中的路径会根据之前的路径在每次下一次测试中被修改。

例如,如果在第一个测试中我模拟了点击href='document/123'的链接并检查vm.$router.history.path,它会正确显示document/123,但如果在下一次测试中我会尝试执行相同的操作,vm.$router.history.path将显示document/document/123,并在每次下一次测试时继续在路径中添加“文档”。

奇怪的是,routerdescribe块中的所有测试期间保持存在,即使我有beforeEach挂钩,我重新初始化 Vue 和使用所有插件以及 Vue-router afterEach挂钩我在 Vue 实例上调用$destroy()方法。

有没有办法在vm.$router.history挂钩中修改或重置afterEach对象或其属性,还是我错过了其他内容?

以下是测试代码:

import Vue from 'vue'
import Search from '../../../src/Search.vue';
import router from '../../../src/router';

describe('Search', () => {
   let vm;

   beforeEach((done) => {
     const container = document.createElement('div');
     vm = new Vue({
        router,
        render: h => h(Search),
     }).$mount(container);
     done();
   });

   afterEach((done) => {
     vm.$destroy();
     done();
   });

   it('should navigate to single page when user clicks on "More" button', (done) => {
     let moreButton = vm.$el.querySelector('.btn');
     let clickEvent = new window.Event('click');
     moreButton.dispatchEvent(clickEvent);
     Vue.nextTick().then(() => {
       expect(vm.$router.history.current.path).to.equal('/document/1548'); // passes
       done();
     });
   });

  it('should navigate to single page when user clicks on document title', (done) => {
     let link = vm.$el.querySelector('h6 a');
     let clickEvent = new window.Event('click');
     link.dispatchEvent(clickEvent);
     Vue.nextTick().then(() => {
       expect(vm.$router.history.current.path).to.equal('/document/1548'); // fails, actual path is /document/document/1548
       done();
     });
   });
});

1 个答案:

答案 0 :(得分:0)

老问题,但如果其他人遇到同样的问题,解决方法如下:https://github.com/vuejs/vue-test-utils/issues/1681

特别将测试套件中的“mode”参数更改为“abstract”。否则,路由将基于在测试之间保留的 window.location。 'abstract' 将导航配置为基于使用 vue-router 的新实例实例化的 'stack'。

在本地,我必须参数化我的 vue-router 实例,以便在生产模式下使用“history”并在运行测试套件时使用“abstract”。