【问题标题】:How to set data for the child vue component in vue-test-utils?如何在 vue-test-utils 中为子 vue 组件设置数据?
【发布时间】:2018-03-03 08:59:54
【问题描述】:

我有一个 FileForm.vue 组件:-

<template>
  <div class="file-form">
    <form @submit="submit">
      <input v-model="name" type="text" placeholder="File Name" />
      <button type="submit">
        <i class="fas fa-plus"></i>
      </button>
    </form>
  </div>
</template>

<script>
export default {
  data () {
    return {
      name: ''
    }
  },
  methods: {
    submit () {
      if (!this.name.trim()) {
        return
      }
      this.$emit('submit', this.name)
    }
  }
}
</script>

它包含在 App.vue 组件中:-

<template>
  <div class="main">
      <div class="sidebar">
        <file-form @submit="createFile"></file-form>
        <div class="files-list">

        </div>
      </div>
      <div class="content">
        <editor v-model="content"></editor>
        <renderer :markdown="content"></renderer>
      </div>
  </div>
</template>

现在我正在测试这种行为:-

test('on successfull submit of the FileForm.vue a file object should be pushed to files array of App.vue', () => {
    let appWrapper = mount(App)
    appWrapper.setMethods({
      createFile: jest.fn()
    })
    appWrapper.find('form').trigger('submit')
    expect(appWrapper.vm.createFile).toHaveBeenCalled()
})

它将失败,因为最初 FileForm.vue 的输入为空,因此它是数据名称属性,由于 if 块,它不会触发提交操作。因此模拟的 createFile 没有被调用。

如果我能以某种方式设置数据,在这种情况下是触发提交之前 FileForm.vue 的 name 属性,我的测试将通过。像这样的东西:-

let formWrapper = appWrapper.find('file-form')
formWrapper.setData({
  name: 'New File'
})

但我不能这样做,因为 formWrapper 是 HTMLElement 而不是 Vue 实例。

【问题讨论】:

  • 好的,我可以这样做:- appWrapper.vm.$children[0].$data.name = 'New File',它正在使测试通过。
  • 我从模板中知道 FileForm 将是第一个组件,但我怎么能确定呢?

标签: vue.js vuejs2 vue-test-utils


【解决方案1】:

使用

import FileForm from '@/components/FileForm'

let formWrapper = appWrapper.find(FileForm)

formWrapper.setData({
  // your code here
})

【讨论】:

    猜你喜欢
    • 2021-02-17
    • 2019-07-16
    • 2023-03-31
    • 2019-03-28
    • 2020-06-06
    • 2021-09-19
    • 2018-10-30
    • 2019-11-14
    • 2019-04-17
    相关资源
    最近更新 更多