我对使用VueJS开发和使用Mocha进行测试(无头使用)相对较新,我故意不使用vue-cli来更好地理解一切是如何工作的 . 我有一套功能相当好的单元测试(获取请求,获取/设置道具等),直到我需要检查DOM中的某些内容 . 看起来组件已成功创建,但它们未安装到元素上 .

我正在使用JSDom为无头测试创建DOM上下文,如我的_setup.js中所示:

global.Vue = require('vue/dist/vue');
require('jsdom-global')('<html><head></head><body><main id="MyApp"></main></body>');

在这些情况下,$ el是未定义的,尽管可以找到上面定义的DOM元素:

app.spec.js

import assert from 'assert';
import app    from '../src/js/app.vue';

describe('app.vue', function() {
  describe('#created', function() {
    it('should initialize the application', function() {  
      const vEl = document.getElementById('MyApp');
      const vm = new Vue({el: vEl}).$mount();

      console.log(vEl);    // HTMLElement {}
      console.log(vm.$el); // undefined

      assert(true); // pass anyway for now
    });
  });
});

myComp.spec.js:

import assert from 'assert';
import header from '../src/js/components/myComp.vue';

describe('myComp.vue', function() {
  describe('#created', function() {
    it('should initialize the component', function() {
      const Constructor = Vue.extend(myComp);
      const comp = new Constructor({
        propsData: {
          someProp: 'hello world'
        }
      }).$mount();

      console.log(document.getElementById('MyApp')); // HTMLElement {}
      console.log(comp.$el)                          // undefined

      assert(true);
    });
  });
});

请注意,如果我在执行getElementById时将元素的ID更改为不存在的内容,则会出现以下错误 - 对我而言,这意味着在使用正确的ID时它在元素上有句柄:

// document.getElementById('IDontExist'); [Vue警告]:无法安装组件:模板或渲染函数未定义 .

请注意,我的组件定义有点不同,因为我要采用简单的方法而不使用vue-cli . 示例(为简洁起见,省略了一些代码):

app.vue

import myComp from './components/myComp.vue';

let app = new Vue({
  el: '#MyApp',
  data: {
    someProp: 'hello world'
  },
  created: function() {},
  methods: {}
});

export {app};

myComp.vue

export default Vue.component('my-comp', {
  props: ['someProp'],
  data: function() {},
  created: {},
  watch: {},
  methods: {},
  template: `<div>{{someProp}}</div>`
});

我有一种感觉,我忽略了一些非常简单的事情,关于如何将组件安装到DOM或访问组件(但它似乎与docs一致) . 有任何想法吗?