How to set grandparent mock data for vue unit test

Viewed 102

I am writing unit test for an existing vue component. The component has a method which runs on mount. The method uses return this.$parent.$parent.someData. I am looking for a way to pass grandparent mock data to the component while writing unit test. I know the way to pass parent component as mock, but looking for a way to pass grand parent.

I am using the following code in my test

const wrapper = shallowMount(MyComponent,{
   parentComponent:ParentComponent
})

Looking for a way to pass grandparent component. I am using vue-test-utils.

PS: I cannot make changes in existing code

1 Answers

This is the most straight-forward way:

import Child from './path/to/Child.vue'

const GP = shalowMount({
  template: '<div />',
  data: () => ({
    foo: 'bar' // mocked data
  })
})

const wrapper = shallowMount(Child, {
  parentComponent: {
    created() {
      this.$parent = GP.vm
    }
  }
})

console.log(wrapper.vm.$parent.$parent.foo) // bar

If you want to test closer to what the user gets in the browser, you could shallowMount the actual ancestors (you'll need their deps in this case: stores, third-party packages, etc...):

import GrandParent from './path/to/GrandParent.vue'
import Parent from './path/to/Parent.vue'
import Child from './path/to/Child.vue'

const GP = shallowMount(GrandParent);
/* set GP data, props, mocks or spies */

const wrapper = shallowMount(Child, {
  parentComponent: shallowMount(Parent, {
    parentComponent: GP.vm
  }).vm
})
Related