渲染子组件以在 vue-test-utils 中获取其 html

Render child component to get its html in vue-test-utils

我有一个名为 SuggestiveInput 的父组件,它有一个名为 VueSimpleSuggest 的子组件。我在测试中得到的是子组件的存根,而不是它的内容。

所以 SuggestiveInput 组件就像:

<template >
  <div class="suggestive-input">
    <vue-simple-suggest ...>
    </vue-simple-suggest>
  </div>
</template>

<script>
import VueSimpleSuggest from "vue-simple-suggest";
import "vue-simple-suggest/dist/styles.css";

export default {
  name: "suggestive-input",

  props: {
    ...
  },

  components: {
    VueSimpleSuggest
  },
...

和我的测试文件:

import chai from "chai";
import { createLocalVue, shallowMount } from "@vue/test-utils";
import SuggestiveInput from "@/components/input/SuggestiveInput";
import * as VueTestUtils from "@vue/test-utils";

const expect = chai.expect;

describe("SuggestiveInput", function() {
  let wrapper;
  const localVue = createLocalVue();

  beforeEach(function() {
    wrapper = shallowMount(SuggestiveInput, {
      localVue,
      propsData: {
        suggestionList: ["Client One", "Client Two"],
        value: ""
      }
    });
  });

  it("shows input element with Bootstrap style", function() {
    expect(wrapper.html()).contains("input.form-control").to.be.true;
  });
});

@vue/test-utils版本^1.0.0-beta.20

vue版本^2.5.19

我得到以下输出:

 AssertionError: expected '<div data-v-6aad8d64="" class="suggestive-input"><vue-simple-suggest-stub data-v-6aad8d64=""></vue-simple-suggest-stub></div>' to include 'input.form-control'

它呈现子组件的存根。如何渲染子组件以获得父组件的纯 HTML?

要获取子组件的内容,需要使用mount(),而不是shallowMount()

来自 Vue Test Utils 文档:

  • mount(): "Creates a Wrapper that contains the mounted and rendered Vue component."

  • shallowMount(): "Like mount, it creates a Wrapper that contains the mounted and rendered Vue component, but with stubbed child components."

我尝试了 mount()shallowMount() 但没有得到我想要的。我使用了 render() 方法,该方法在后台使用 vue-server-renderer 将组件呈现为静态 HTML。 render 包含在 @vue/server-test-utils 包中。可以找到文档 here.

另一种方法是使用shallowMount,但在测试中,使用wrapper.find(ChildComponent)访问子组件。

两种方法我都试过了,效果都不错。