Rendering a component

Tram Ho

Two ways to represent (render)

vue-test-utils provides two ways to render, or mount a component – mount and shallowMount . A component mounted by one of two methods returns a wrapper , an object containing the Vue component, along with a number of methods for testing.

We start with two simple components:

We start rendering Child and call the html method that vue-test-utils provides to check markup.

Both mountWrapper.html() and shallowWrapper.html() will produce the following result:

There is no difference, so we will try to do the same test against Parent ?

mountWrapper.html() is now:

Parent and Child both render the same. On the other hand, shallowWrapper.html() produces the following result:

In <Child /> is replaced by <vuecomponent-stub /> . shallowMount renders normal html elements, but replaces Vue components with stub.

A stub is a type of “fake” object that represents an actual object.

Imagine you want to test your App.vue , which looks like this:

And we want to test that <h1>My Vue App</h1> will be rendered correctly. We also have a component <fetch-data> , will request external API calls in mounted the hook lifecycle.

If we use mount , even though all we want to do is check the rendered text comparison, <fetch-data /> will invoke the request API. This will make our testing process slow and easily fail due to too many things that are difficult to control. So we use stub to create as a real object. By using shallowMount , <fetch-data /> will be replaced with a <vuecomponent-stub /> , and the call to API request will not need to use it.

Reference

Translated from: https://lmiller1990.github.io/vue-testing-handbook/rendering-a-component.html

Share the news now

Source : Viblo