Javascript 为Vue webapp运行单元测试时出错

Javascript 为Vue webapp运行单元测试时出错,javascript,unit-testing,vue-component,vue.js,vuejs2,Javascript,Unit Testing,Vue Component,Vue.js,Vuejs2,我正在用VueJs编写一个webapp,我正在尝试为它设置单元测试,我从单元测试中得到了灵感。但是我的代码的测试没有正常运行,我得到了vm.$el作为未定义的,因此根本无法前进 这是我要测试的组件: 确认。vue <template> <div> Your order has been confirmed with the following details. </div> </template> <scri

我正在用VueJs编写一个webapp,我正在尝试为它设置单元测试,我从单元测试中得到了灵感。但是我的代码的测试没有正常运行,我得到了
vm.$el
作为
未定义的
,因此根本无法前进

这是我要测试的组件:

确认。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>
utils.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
  })
})
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
作为入口点加载到应用程序中,而是加载要测试的单个组件;因此,您无权访问
文档
或html元素,并且永远不会装入该组件。我建议使用:

如果未提供ElementSelector参数,则模板将作为文档外元素呈现

您可以将上面的行更改为如下内容

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

您的测试现在应该可以访问$el属性。

utils中的
vueTest
函数正在尝试将Vue实例加载到
主体
标记中:

const vm = new Class({
  replace: false,
  el: 'body'
})
return vm
单元测试不会将
index.html
作为入口点加载到应用程序中,而是加载要测试的单个组件;因此,您无权访问
文档
或html元素,并且永远不会装入该组件。我建议使用:

如果未提供ElementSelector参数,则模板将作为文档外元素呈现

您可以将上面的行更改为如下内容

const vm = new Class();
vm.$mount();
return vm;
您的测试现在应该可以访问$el属性