How to mock or set value for this.$parent.propertyName

Hi All,

I am using the latest vue-test-utils@v1 and latest vue@2.

I have an SFC I am trying to write a test for. It doesn’t render any template but it has script content. In particular it has a call in its mounted lifecycle hook to this.$set that has an argument which I’m not able to set or mock in my current attempts.

  mounted() {
   this.$set(this, 'columns', this.$parent.displayHeaders.length)
  }

I am shallow-mounting this component and passing any required props. I am not currently passing any mocks.

It would appear in the application that this component has a parent component ‘Table’ which has the displayHeaders data which is an array by default.

data() {
  return {
    displayHeaders: []
  }
}

When I run the test and shallowMount attempts to mount the component, I receive an error.

[Vue warn]: Error in mounted hook: "TypeError: Cannot read properties of undefined (reading 'length')"

I have narrowed this down to the argument to this.$set().

this.$parent.displayHeaders.length

I would like to know how I could set or mock this value to be able to mount this component. Is this possible to be able to test this component?

I have attempted to use mount and shallowMount, localVue, passing a parentComponent option with the parent ‘Table’ component passed in, mocking $parent and trying to set a prop and value directly on wrapper.vm.$parent.

Things get a little better when I pass the parentComponent to the mounting options but then a whole bunch of required prop errors appear which I attempt to specify in the propsData mounting options but that doesn’t seem to work.

This is my component to test:

<script>
export default {
  name: 'table-detail-row',
  props: {
    item: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      columns: 0
    }
  },
  mounted() {
    this.$set(this, 'columns', this.$parent.displayHeaders.length)
  }
}
</script>

Here is my test, so far:

describe('TableDetailRow', () => {
  const propsData = { item: { foo: "bar" } }

  test('should render', () => {
    const wrapper = shallowMount(TableDetailRow, { propsData })
    expect(wrapper.props().item).toBeDefined()
  })
})

Any help would be greatly appreciated.

I now have a solution and for anyone looking to do the same in the future, I solved this per the below:

describe('TableDetailRow', () => {
  const propsData = { item: { foo: "bar" } }

  const Parent = {
    data: () => ({
      displayHeaders: []
    })
  }

  test('should render', () => {
    const wrapper = shallowMount(TableDetailRow, {
      parentComponent: Parent,
      propsData
    })
    expect(wrapper.props().item).toBeDefined()
  })
})