1

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

0

1 Answer 1

0
+100

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
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.