VUE WebApp的运行单元测试错误



我正在使用Vuejs编写WebApp,我正在尝试为其设置单元测试,我从VUE-MDL单元测试中得到了启发。但是测试无法正确运行我的代码,我将vm.$el作为undefined,因此根本无法前进。

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

cresence.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>

这是对此的测试,失败

cresence.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
}

我的完整代码可在此处可用,所有测试配置都可以进行多次更改,但无法弄清楚如何使其正常工作。如果您在某处看到一些错误,请告诉我。

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属性。

最新更新