2016-11-28 78 views
1

我正在用VueJs寫一個webapp,我正在嘗試爲它設置單元測試,我從vue-mdl單元測試中獲得靈感。但是測試沒有正確運行我的代碼,我得到vm.$elundefined,所以根本無法前進。Vue webapp運行單元測試時出錯

這裏是分量,我想測試:

Confirmation.vue

<template> 
    <div> 
     Your order has been confirmed with the following details. 
    </div> 
</template> 

<script type="text/javascript"> 
export default { 
    data() { 
    return { 
     data_from_pg: null 
    } 
    } 
} 
</script> 

,這裏是它的測試,從而未能

Confirmation.spec.js

import Confirmation from 'src/components/Confirmation' 
import { vueTest } from '../../utils' 

describe('Confirmation',() => { 
    let vm 
    let confirmation 
    before(() => { 
    vm = vueTest(Confirmation) 
    console.log('vm.$el ' + vm.$el) => this prints undefined 
    confirmation = vm.$el.querySelector('#confirmation') => so this line gives error 
    // confirmation = vm.$('#confirmation') 
    }) 

    it('exists',() => { 
    confirmation.should.exist 
    confirmation.should.be.visible 
    }) 
}) 

utils.js

export function vueTest (Component) { 
    const Class = Vue.extend(Component) 
    Class.prototype.$ = function (selector) { 
    return this.$el.querySelector(selector) 
    } 
    Class.prototype.nextTick = function() { 
    return new Promise((resolve) => { 
     this.$nextTick(resolve) 
    }) 
    } 

    const vm = new Class({ 
    replace: false, 
    el: 'body' 
    }) 

    return vm 
} 

我的完整代碼可以here,所有的測試配置,這是我試圖改變很多次,但無法弄清楚如何使它發揮作用。如果您在某處發現某處錯誤,請告訴我。

回答

0

在utils的的vueTest函數試圖給Vue的實例加載到body標籤:

const vm = new Class({ 
    replace: false, 
    el: 'body' 
}) 
return vm 

單元測試不加載index.html作爲切入點進入應用程序,而是單獨的組件,您想測試;因此,您無權訪問document或html元素,並且組件永遠不會掛載。我建議使用vm.$mount()

如果未提供elementOrSelector參數,則模板將呈現爲非文檔元素。

你可以改變上述行類似下面的

const vm = new Class(); 
vm.$mount(); 
return vm; 

你的測試,現在應該有機會獲得$ EL財產。

相關問題