简体   繁体   中英

Error in running unit test for Vue webapp

I am writing a webapp with VueJs, I am trying to setup unit test for it, I got inspired from vue-mdl unit-tests. But the tests are not running properly for my code and I am getting vm.$el as undefined , so not able to move forward at all.

Here is the component, I am trying to test:

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>

and here is test for it, which fails

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
}

My complete code is available here , with all the test config, which I have tried to change many times, but could not figure out how to make it work. Please let me know if you see some error somewhere.

The vueTest function in utils is trying to load the Vue instance into the body tag:

const vm = new Class({
  replace: false,
  el: 'body'
})
return vm

The unit tests do not load index.html as an entry point into the app, but rather the individual components that you want to test; Therefore, you do not have access to document or html elements and the component is never mounted. I'd suggest using vm.$mount() :

If elementOrSelector argument is not provided, the template will be rendered as an off-document element.

You could change the above lines to something like the following

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

Your tests should now have access to the $el property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM