How to test plain Vue components (not single file components)

强颜欢笑 提交于 2021-02-10 12:22:11

问题


All of these tries are throwing an error:

var testUtils=require('@vue/test-utils'), Vue=require('vue');

require('jsdom-global')();    

testUtils.mount(Vue.component('test', {
  template:'<div>test</div>'
}));

testUtils.mount(Vue.component('test', {
  render:function(el) { return el('div', 'test'); }
}));

testUtils.mount({
  template:'<div>test</div>'
});

@vue/test-utils/dist/vue-test-utils.js:2471

var componentInstance = node.child;

TypeError: Cannot read property 'child' of undefined

I have also tried to use localVue, to use shallowMount instead of mount and tried to pass Vue.options.components.test after registrating it globally (and some other things that came to my mind) but nothing works.

Isn't there any way to test vue components without using single file components, webpack and/or other technologies that are making things unnecessary complicated and require a build process? Or is this just a lack of documentation?


回答1:


You need to load the DOM before requiring @vue/test-utils. Change your code to this:

require('jsdom-global')();    
var testUtils=require('@vue/test-utils'), Vue=require('vue');
// ...

Likely Jest loads JSDOM in some script before Vue is required, which is why it works there.




回答2:


There's a simple guide for that in their GitHub repo.

https://github.com/vuejs/vue-test-utils/pull/1373/files#diff-b64ec6abf844db0ffa41aaf83deb3043f880b0beb988a14e0b2ace310848a335

require('jsdom-global')()

const assert = require('assert')
const Vue = require('vue')
const VueTestUtils = require('@vue/test-utils')

const App = Vue.component('app', {
  data() {
    return {
      msg: 'Hello Vue Test Utils'
    }
  },
  template: `
    <div>{{ msg }}</div>
  `
})
const wrapper = VueTestUtils.shallowMount(App)
assert.strictEqual('Hello Vue Test Utils', wrapper.text())


来源:https://stackoverflow.com/questions/55052983/how-to-test-plain-vue-components-not-single-file-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!