2016-11-28 37 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财产。