Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have one Parent Component called SuggestiveInput and it has Child Component called VueSimpleSuggest. I am getting stub of child component on the test instead of its content.

So SuggestiveInput component is like:

<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
  },
...

and my test file:

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 version ^1.0.0-beta.20

vue version ^2.5.19

I am getting the following output:

 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'

It renders the stub of the child component. How can I render the child component to get pure HTML of the parent component?


2 Answers

I tried both mount() and shallowMount() but didn't get what I wanted. I used the render() method which uses vue-server-renderer under the hood to render a component to static HTML. render is included in the @vue/server-test-utils package. The documentation could be found here.

Another approach is to use shallowMount but in the test, access the child component using wrapper.find(ChildComponent).

I tried both methods and they worked properly.

To get the content of child components, you need to use mount(), not shallowMount().

From the Vue Test Utils docs:

  • 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."

like image 36
Metalmi Avatar answered Oct 31 '25 07:10

Metalmi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!