测试元素是否存在Vuejs,Karma,Mocha

nu *_*est 7 javascript unit-testing phantomjs karma-mocha vue.js

我是Javascript和Vue.js的新手.我通过vue-cli和内置了Karma,Mocha和PhantomJS的完整webpack模板安装了vue.我运行了hello world组件测试并且它通过了.

我有一个vuejs组件调用my-input.vue生成以下HTML.

<template>
  <div>
    <input class="test-focused">
  </div>
</template>

<script>
  export default {

  }
</script>
Run Code Online (Sandbox Code Playgroud)

我有一个看起来像这样的组件的测试.

import Vue from 'vue'
import { default as MyInput } from 'src/components/my-input.vue'

describe('my-input.vue', () => {
  it('should display an input element', () => {
    const expected = "<input class='test-focused'>"

    const vm = new Vue({
      template: '<div><my-input></my-input></div>',
      components: { 'my-input': MyInput }
    }).$mount()

    // I tried these separately.
    expect(vm.$el.querySelector('input.test-focused').isPresent()).to.be.true

    expect(document.getElementsByTagName('input').indexOf(expected) != -1).to.be.true
  })
})
Run Code Online (Sandbox Code Playgroud)

当我分别运行每个expect()语句时,我得到了undefined is not a constructor.

这似乎是一个简单的测试.

如何正确测试元素的存在?

此外,如果您可以向我指出有关可用方法的文档vm.$el.querySelector('input.test-focused'),以及expect()它会有所帮助.消除Jasmine,Mocha和其他饮料的语法似乎使测试变得比它需要的更难toBe()或者not.to.be.

gur*_*het 1

试试这个: http: //jsfiddle.net/9mdqw53b/

const MyInput = { template: '<input class="test-focused">' }

describe('my-input.vue', () => {
  it('should display an input element', () => {
    const vm = new Vue({
      template: '<div><my-input></my-input></div>',
      components: { MyInput }
    }).$mount()

    // I tried these separately.
    expect(vm.$el.querySelectorAll('input.test-focused').length).toBe(1)
  })
})
Run Code Online (Sandbox Code Playgroud)