【问题标题】:How to mock $parent for vue-components如何为 vue-components 模拟 $parent
【发布时间】:2019-06-22 21:10:49
【问题描述】:

我怎样才能为我的规格模拟 $parent?当我的组件使用 shallowMount 时,我总是得到未定义的 clientWidth/clientHeight。我已经尝试将 $parent 模拟为一个对象,其中一个 $el 作为键,另外两个嵌套键分别用于 clientWidth 和 clientHeight,但这并没有按预期工作。我无法弄清楚 parentComponent 的正确用法。

我有一个文件组件,如下所示:

<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>

创建 vue 应用如下所示:

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
    }
  });
}

将 slim 与我的组件结合使用如下所示:

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

这是我的测试设置:

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

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

  beforeEach(() => {
    component = shallowMount(Foobar, {});
  });

【问题讨论】:

  • 我怀疑这将涉及手动定义这些属性,但是是的,我似乎无法让 $parent 成为 undefined 以外的任何东西 - github.com/jsdom/jsdom/issues/1729
  • 我现在有这个工作,你使用的是什么版本的 vue-test-utils,你可以更新你的代码示例来展示你如何使用“parentComponent”
  • @chrismarx 我已将 vue-test-utils 固定在 "^1.0.0-beta.25" 上;我会尽快更新我的代码,但我不知道这周我什么时候能找到时间;无论哪种方式,我都尝试通过两种方式使用 parentComponent:第一种方式是使用纯 html 字符串作为给定参数,第二种方式是使用带有 document.createElement 的纯 JS 创建一个 div 并将其传递给 parentComponent 选项

标签: vue.js jestjs vue-test-utils


【解决方案1】:

parentComponent 挂载选项需要一个组件对象:

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

另外,尝试将 vue-test-utils 的版本固定到“^1.0.0-beta.28”。这应该可以让您的测试完成,但 clientWidth/Height 仍将是 0x0

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

【讨论】:

  • 感谢您的评论;但是我的 parentComponent 实际上不是 vue 组件。相反,它是纯 html,我只是将我的组件安装在 html 元素上。在我的规范中使用父级 vue 组件感觉不对,因为它不反映实际使用情况
  • 如果你愿意,你可以在测试中创建一个组件,即使像这样简单的东西也可以: let parentComponentStub = { name:"parentStub", template:'
    ' };
猜你喜欢
  • 2015-03-29
  • 2018-03-06
  • 2011-03-29
  • 1970-01-01
  • 2020-09-19
  • 2019-12-17
  • 2021-02-19
  • 1970-01-01
  • 2022-11-11
相关资源
最近更新 更多