在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ Vue+Mocha+Vue-test-utils進(jìn)行單元測試, 如何在測試用例中

Vue+Mocha+Vue-test-utils進(jìn)行單元測試, 如何在測試用例中添加params到router

我使用mocha+vue-test-utils進(jìn)行單元測試, 在測試的組件中使用到了this.$route.params.appId.我使用了vue-test-utils提供的createLocalVuemocks對VueRouter在測試腳本中進(jìn)行安/裝, 因為我不知道如何將appId這個參數(shù)在測試腳本中置入到this.$route.params, 所以這時會出現(xiàn)報錯, 所有的測試用例都無法執(zhí)行...
具體代碼如下:

//Counter.vue 測試組件

<template>
  <div>
    <h3>Counter.vue</h3>
    <div>
      <span class="num">{{ count }}</span>
      <button class="sync-button" @click="increment">自增</button>
      <button class="async-button" @click="incrementByAsync">異步自增</button>
    </div>
  </div>
</template>

<script>
  export default {
    data () {
      return {
        count: 0,
        foo: '',
        appid: this.$route.params.appId
      }
    },

    methods: {
      increment () {
        this.count++;
      },
      incrementByAsync () {
        window.setTimeout(() => {
          this.count++;
        }, 1000) 
      }
    }
  }
</script>
//Counter.spec.js -- 測試腳本

import Vue from 'vue'
import Counter from '@/components/Counter'
import VueRouter from 'vue-router'
import Weibo from '@/components/SinaWeibo.vue'
//引入vue-test-utils
import { mount, shallow, createLocalVue } from 'vue-test-utils'


//偽造Vue-Router
const localVue = createLocalVue();
localVue.use(VueRouter);
const $route = new VueRouter({
  mode: 'history',
  routes: [
    {
      //重定向
      path: '/',
      redirect: '/weibo'
    },
    {
      path: '/weibo',
      component: Weibo
    },
    {
      name: 'counter',
      path: '/counter/:appId',
      component: Counter
    }
  ]
});

let wrapper = mount(Counter, {
  mocks: {
    $route
  }
});

describe('Counter.vue', () => {
    //測試用例略
})

測試瀏覽器的報錯信息如下:
clipboard.png

回答
編輯回答
孤酒

樓主你好. 我也有個單元測試的問題. 可以咨詢一下你是否遇見過這個問題. 組件中有個點擊事件 事件中有個異步方法. 在測試用例中觸發(fā)點擊事件 如何能知道異步方法執(zhí)行完畢了呢 我提的問題的地址

2017年5月6日 18:53
編輯回答
局外人

首先我覺得你先要弄清楚在 vue 組件的單元測試中,你想要什么樣的測試數(shù)據(jù),想要得到什么樣的結(jié)果,之后才是怎么注入 vue-router 相關(guān)的內(nèi)容。
比如,你在這里希望在進(jìn)行單元測試的時候,appId=1;那么你可以這么寫:

//偽造Vue-Router
const localVue = createLocalVue();
// 這句話得注釋掉,因為你如果選擇了 mocks 的方式,就不能安裝 VueRouter
// localVue.use(VueRouter);

// $route 是路由信息對象,不是 router vue-router 實例
const $route = {
  path: 'counter/1'
};

let wrapper = mount(Counter, {
  mocks: {
    $route
  }
});

這樣再去測試應(yīng)該可以解決你的問題。

2017年6月29日 18:34