Vue.js - 在karma / phantomjs测试中数据丢失

时间:2016-04-28 21:33:40

标签: phantomjs karma-jasmine vue.js

我正在为Vue应用程序编写一些单元测试。当我尝试测试DOM内容时,一切都很好,但是我无法访问组件的数据。事实上,如果我console.log我的组件$data属性没有数据,它会打印一个空对象,没有最初定义的数据或任何其他数据。什么都没有。

这是一些代码

某些vue组件

<template>
   <form @submit.prevent="saveAccount">
      <label for="accountType">Tipo de cuenta</label>
        <select class="form-control" id="accountType" v-model="newAccount.type">
          <option v-for="type in accountTypes" v-bind:value="type.value">
            {{type.label}}
          </option>
        </select>
   </form>
</template>
<script>
export default {
  data () {
    return {
      accountTypes: [
        {value: '1', label: 'Activo'},
        {value: '2', label: 'Pasivo'},
        {value: '3', label: 'Patrimonio'},
        {value: '4', label: 'INTO'}
      ]
    }
  }
}
</script>

我的测试

  beforeAll(() => {
    vm = new Vue({
      template: '<div><account></account></div>',
      components: { account }
    }).$mount()
  })

  afterAll(() => {
    vm.$destroy(true)
  })

  it('account type', () => {
    // this pass
    expect(vm.$el.querySelectorAll('#accountType option').length).toBe(4)
    const options = vm.$el.querySelectorAll('#accountType option')
    // here accountTypes is undefined
    const accountValues = vm.accountTypes.map(type => {
      return type.value
    })
    options.forEach(option => {
      expect(accountValues.indexOf(option.value)).not.toBe(-1)
    })
  })

省略了一些代码。那么,为什么我的组件数据是空的,但同时在DOM中正确呈现?

1 个答案:

答案 0 :(得分:1)

经过一些尝试和错误后,我找到了答案,现在很明显了。问题是,我在错误的地方搜索数据。我定义的vm对象

vm = new Vue({
  template: '<div><account></account></div>',
  components: { account }
}).$mount()

是仅具有组件和模板选项的Vue实例,我搜索的数据位于该实例的子项中。所以,我必须用这种方式来访问数据

const accountInstance = vm.$children[0]

这样可行,因为要测试我定义的单个子容易识别。我在使用const accountInstance = new account()之前也尝试过,但是由于vue组件不是构造函数

,因此会抛出错误