Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock $parent for vue-components

How am i able to mock $parent for my specs? When using shallowMount with my component i always get clientWidth/clientHeight of undefined. I already tried mocking $parent as an object with an $el as a key and two more nested keys for clientWidth and clientHeight, but that's not working as expected. I cannot figure out the right usage of parentComponent.

I've got a single file component as seen below:

<template>
  <img :src="doSomething">
</template>

<script>
export default {
  name: "Foobar",
  data() {
    return {
      size: null
    };
  },
  computed: {
    doSomething() {
      # here is some string concatenation etc.
      # but not necessary for example
      return this.size;
    }
  },
  created() {
    let parent = this.$parent.$el;
    this.size = `size=${parent.clientWidth}x${parent.clientHeight}`;
  }
};
</script>

creating the vue app looks like this:

import Vue from "vue";
import Foobar from "./Foobar";

const vueEl = "[data-vue-app='foobar']";
if (document.querySelector(vueEl)) {
  new Vue({
    el: vueEl,
    components: {
      "foo-bar": Foobar
    }
  });
}

and the combination of using slim with my component looks like this:

div data-vue-app="foobar"
  foo-bar

This is my test setup:

import { shallowMount } from "@vue/test-utils";
import Foobar from "@/store/Foobar";

describe("Foobar.vue", () => {
  let component;

  beforeEach(() => {
    component = shallowMount(Foobar, {});
  });
like image 781
Gbeschbacher Avatar asked Jan 29 '19 17:01

Gbeschbacher


1 Answers

The parentComponent mounting option expects a component object:

import Parent from "../Parent.vue";
...
beforeEach(() => {
  component = shallowMount(Foobar, {
   parentComponent: Parent
  });
});

Also, try pinning the version of vue-test-utils to "^1.0.0-beta.28". This should allow your tests to complete, but the clientWidth/Height will still be 0x0

ref: https://vue-test-utils.vuejs.org/api/options.html#parentcomponent

like image 117
chrismarx Avatar answered Nov 21 '22 01:11

chrismarx