简体   繁体   中英

Vue Test Utils: how to pass Vuelidate validation rules to child components?

while trying to write a component test by using vue test utils , testing interaction between child components and stuff, I am stuck due to usage of Vuelidate from child components. Below is an example simplified:

// parent component code

<template>
   <div>
      <childA />
   </div>
</template>
//childA code

<template>
   <input v-model="value" />
</template>

<script>
   ...
   validations: {
      value: {
         required
      }
   }
...
</script>
// parent component test
...
const wrapper = mount(MyParentComponent, {
   ...,
   components: {
      childA,
   },
   validations: {
      value: required
   },
   ...
})

I have tried to find a solution out there that I could mount (note here that I WANT to mount also the child components, so shallow-mount is not what I look for) the child component, with it's respective Vuelidate validation rules, but I still haven't found any solution.

Instead, my test gives me errors like:

Cannot read property `value` of undefined

which makes sense, since the test cannot access the child component's $v instance.

Has anyone achieved it so far?

For answering your question and after i've did some test i believe you missed the data part inside your mount

  1. mount : render child components
  2. shallowMount : doesn't render child components

MyParentComponent need to have in the options the structure of you're child component so this is why he is returning the error

And i saw that you're passing the import of your component directly but don't forget that your test folder is outside of your src folder

import ChildA from "@/components/ChildA";

will not work instead i propose to use absolute path directly to import your child component or use a configuration to resolve them

    const wrapper = mount(MyParentComponent, {
      data() {
        return {
          value: null
        }
      },
      components: {
        ChildA: () => import('../../src/components/ChildA'),
      },
      validations: {
        value: required
      },
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM