Difference between mount and shallowMount in Vue test utils
In this tutorial, we are going to learn about the difference between mount and shallowMount methods in vue test utils.
checkout my Vue unit testing tutorial.
mount method
The mount
method takes the Vue component as a first argument and returns its vue instance along with some helper which is used to interact with a component instance like set props, trigger clicks, etc.
shallowMount method
The shallowMount
method also works similar to the mount
method the main difference is shallowMount
doesn’t render child components so that it allows us to test the component in isolation to make sure that child components are not included in the test.
Let’s see an example.
consider we have two files in our Vue app which are Home.vue
and App.vue
.
<template>
<h1>Home</h1>
</template>
<script>
export default {};
</script>
<template>
<div id="app">
<h1>{{msg}}</h1>
<Home /> //child component
</div>
</template>
<script>
import Home from "./components/Home";
export default {
data: function() {
return {
msg: "Hello"
};
},
components: {
Home
}
};
</script>
Inside the App.vue
we imported Home
component and added to the App
component template
.
Let’s test an App
component now.
import App from '../src/App.vue'
import { mount } from '@vue/test-utils';
describe('Testing App component', () => {
it('checks textcontent to Hello ', () => {
const wrapper = mount(App); expect(wrapper.text()).toBe('Hello');
})
})
Now run the test and you can see the test is failed.
Jest is clearly showing Received value Hello Home
but the expected value is Home
.
Our test is failed because of mount
method is rendered App
component along with Home
component
so that we are receiving text content values from both components, we can solve this problem by using
shallowMount
method.
import App from '../src/App.vue'
import { mount, shallowMount } from '@vue/test-utils';
describe('Testing App component', () => {
it('checks textcontent to Hello ', () => {
const wrapper = shallowMount(App); expect(wrapper.text()).toBe('Hello');
})
})
Now no children have been rendered and our test is passed.