Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if Element exists Vuejs, Karma, Mocha

I'm new to testing in Javascript and Vue.js. I installed vue via vue-cli and the full webpack template that has Karma, Mocha, and PhantomJS built in. I ran the hello world component test and it passes.

I have a vuejs component called my-input.vue that generates the following HTML.

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

<script>
  export default {

  }
</script>

I have a test for the component that looks like this.

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

When I run the each of the expect() statements separately I get undefined is not a constructor.

It seems like this is a dirt simple test.

How do I properly test for the existence of an element?

Also, if you can point me to documentation about what methods are available for vm.$el.querySelector('input.test-focused'), as well as, expect() it would help. Disambiguating syntax for Jasmine, Mocha, and other beverages seems to make testing harder than it needs toBe() or not.to.be.

like image 340
nu everest Avatar asked Sep 11 '16 19:09

nu everest


2 Answers

Try this: 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)
  })
})
like image 174
gurghet Avatar answered Oct 07 '22 06:10

gurghet


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

like image 34
AlexS Avatar answered Oct 07 '22 04:10

AlexS