0
0
Vueframework~5 mins

Mounting components (mount vs shallowMount) in Vue

Choose your learning style9 modes available
Introduction

Mounting components lets you test how Vue components behave. mount renders the full component with all children, while shallowMount renders only the component itself, skipping child components.

You want to test a component including its child components to see full behavior.
You want to test a component alone without running child components to isolate issues.
You want faster tests by skipping rendering of child components.
You want to check if a component renders correctly without worrying about children.
You want to mock child components to focus on the parent component's logic.
Syntax
Vue
import { mount, shallowMount } from '@vue/test-utils'

const wrapper = mount(Component)
const shallowWrapper = shallowMount(Component)

mount renders the component and all its child components fully.

shallowMount renders the component but replaces child components with placeholders.

Examples
This mounts MyComponent fully, including all child components.
Vue
import { mount } from '@vue/test-utils'
import MyComponent from './MyComponent.vue'

const wrapper = mount(MyComponent)
This mounts MyComponent but replaces child components with stubs.
Vue
import { shallowMount } from '@vue/test-utils'
import MyComponent from './MyComponent.vue'

const wrapper = shallowMount(MyComponent)
Sample Program

This example shows the difference between mount and shallowMount. The full mount renders the Child component inside Parent. The shallow mount replaces Child with a stub, so you only see the placeholder.

Vue
import { mount, shallowMount } from '@vue/test-utils'
import { defineComponent } from 'vue'

// Child component
const Child = defineComponent({
  name: 'Child',
  template: '<div>Child content</div>'
})

// Parent component uses Child
const Parent = defineComponent({
  name: 'Parent',
  components: { Child },
  template: '<div>Parent content <Child /></div>'
})

// Full mount
const fullWrapper = mount(Parent)
console.log('Full mount HTML:', fullWrapper.html())

// Shallow mount
const shallowWrapper = shallowMount(Parent)
console.log('Shallow mount HTML:', shallowWrapper.html())
OutputSuccess
Important Notes

Use shallowMount to isolate the component you want to test and avoid testing child components.

Use mount when you want to test the full component tree and interactions between components.

Shallow mounting can speed up tests and reduce complexity.

Summary

mount renders the component and all its children fully.

shallowMount renders the component but replaces children with placeholders.

Choose based on whether you want to test the full component tree or isolate the component.