【问题标题】:how to mock this.$refs.form.resetValidation()?如何模拟 this.$refs.form.resetValidation()?
【发布时间】:2020-03-08 02:18:58
【问题描述】:

component1.vue

 <template>
    <div>
        <v-form
        ref="form">
            <v-text-field
                v-model="name"
                :counter="10"
                :rules="nameRules"
                label="Name"
                required
            ></v-text-field>
        </v-form>
    </div>
</template>

<script>
  export default {
    data: () => ({
      name: 'Test',
      nameRules: [
        v => !!v || 'Name is required',
        v => (v && v.length <= 10) || 'Name must be less than 10 characters',
      ]
    }),

    mounted() {
        this.$refs.form.resetValidation();
    }
  }
</script>

test.spec.js

import { shallowMount, mount, createLocalVue } from '@vue/test-utils'
import Vuex from "vuex"
import Vuetify from 'vuetify'
import component1 from '@/components/component1.vue'

const localVue = createLocalVue()
localVue.use(Vuex)
localVue.use(Vuetify)
const vuetify = new Vuetify()

test('test1', () => {
    const wrapper = shallowMount(component1, {
        localVue,
        vuetify
    })
    expect(3).toBe(3);
})

错误 - TypeError: this.$refs.form.resetValidation 不是函数

如果我使用 mount 而不是 shallowMount,测试将通过。但我想知道如何模拟 $ref.form.resetValidation。

【问题讨论】:

  • 尝试将其包装在一个函数中

标签: unit-testing vue.js vuetify.js vue-test-utils


【解决方案1】:

您可以创建一个手动存根来替换原本用于 v-form 的存根:

test('test1', () => {
  const wrapper = shallowMount(component1, {
    localVue,
    stubs: {
      VForm: {
        render: () => {},
        methods: {
          resetValidation: () => ()
        }
      }
   }
})
....

})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    • 2019-08-05
    • 2023-03-20
    相关资源
    最近更新 更多