Skip to content

Mock $parent when mounting/shallow a component #560

@Mweydert

Description

@Mweydert

What problem does this feature solve?

Enable a component that calls a method of its parent (for example this.$parent.$emit) in the "mounted" hook to be shallowed or mounted without any issue.

Use case:

I have a component ("VueDetail.vue") that is mounted by a third party library (let's name the main component ThirdParty.vue). I can't listen for the events emitted by VueDetail.vue as I don't instantiate the component myself (instanciated by ThirdParty.vue, therefore event should be handled in ThirdParty.vue).

As an alternative, I decided to emit an event from VueDetail's parent (i.e. call this.$parent.$emit("my-event") in VueDetail.vue). By doing that, the event is emited from ThirdParty.vue and I can handle this event in my component that mount ThirdParty.vue.

A consequence is that I need to mock the wrapper's parent (this.$parent or wrapper.vm.$parent in tests). I achieve doing so pretty easily by shallowing a second component and define it as the parent of the component I am testing.

const parentWrapper = shallow(ParentComponent);
const wrapper = shallow(ComponentIAmTesting);
wrapper.vm.$parent = parentWrapper.vm;

Here comes the tricky part: I now want to call this.$parent.$emit from the "mounted" hook of VueDetail.

<script>
export default {
  props: {
    ...,
  },
  mounted(){
    this.$parent.$emit('my-event")
  }
}
</script>

My code run as expected, but all my tests break. All my tests failed when executing the "mounted" hook because this.$parent is not defined at the moment.
Indeed there is no mean (or at least not I am aware of) to mock $parent WHEN mounting a wrapper.

What does the proposed API look like?

I know it is already possible to add additional property to the instance using the mocks property. I think this could be used for the feature I proposed.

const $parent = somethingMockingParent;
const wrapper = shallow(Foo, {
  mocks: {
    $parent
  }
});

Thanks for the library !
Michael

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions