运行Vue webapp的单元测试时出错

时间:2016-11-28 10:27:03

标签: javascript unit-testing vue-component vue.js vuejs2

我正在和VueJs一起编写一个webapp,我正在尝试为它设置单元测试,我从vue-mdl单元测试中获得灵感。但是我的代码测试运行不正常,我的vm.$elundefined,因此无法继续前进。

这是组件,我正在尝试测试:

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,包含所有测试配置,我试图多次更改,但无法弄清楚如何使其工作。如果你在某个地方看到某些错误,请告诉我。

1 个答案:

答案 0 :(得分: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属性。

相关问题