Search code examples
vue.jsvue-test-utils

Uncaught TypeError: Cannot read property 'firstname' of undefined. on loading a component that has an inner component


create.vue

<template>
  <div class="content">
    <base-input type="text" id="firstname" v-model="firstname"/>
  </div>
</template>

<script> 
import BaseInput from 'BaseInput.vue'
export default {
    data () {
        return {
            firstname: ''
        }   
    }
}   
</script>

create.spec.js

import { shallowMount, createLocalVue } from '@vue/test-utils'
import Create from '/Create.vue'
import VueI18n from 'vue-i18n'

const wrapper = shallowMount(Create)
const vm = wrapper.vm
console.log(vm)

As you see, while loading the template using shallow Mount. it throws the error,

Uncaught TypeError: Cannot read property 'firstname' of undefined at webpack:///node_modules/@vue/test-utils/dist/vue-test-utils.js:5652:0 <- index.6fc62f9fc7f0f4a43161.js:9693


Solution

  • You need to add your BaseInput component to your export default. Now vue don't know what BaseInput is (info, if you are using such as Babel or Webpack) . I also changed the data line because there need to be a : after data and function before the () (example). If you do it like this it should work:

    <script> 
    import BaseInput from 'BaseInput.vue'
    export default {
        components: {
           BaseInput 
        }
        data: function() {
            return {
                firstname: ''
            }   
        }
    }   
    </script>