【问题标题】:Test if Element exists Vuejs, Karma, Mocha测试 Element 是否存在 Vuejs, Karma, Mocha
【发布时间】:2017-01-19 06:26:39
【问题描述】:

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

我有一个名为 my-input.vue 的 vuejs 组件,它生成以下 HTML。

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

<script>
  export default {

  }
</script>

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

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
  })
})

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

这似乎是一个非常简单的测试。

如何正确测试元素是否存在?

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

【问题讨论】:

    标签: javascript unit-testing phantomjs vue.js karma-mocha


    【解决方案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)
      })
    })
    

    【讨论】:

      【解决方案2】:

      expect(vm.$el.querySelector('input.test-focused') !== null).to.be.true

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-13
        • 1970-01-01
        相关资源
        最近更新 更多