Back to Repositories

Testing Vue Component Rendering and Router Integration in vue-cli

This test suite demonstrates unit testing of Vue.js components using Jest and TypeScript. It showcases component mounting, props validation, and router integration testing with Vue Test Utils framework.

Test Coverage Overview

The test suite provides comprehensive coverage of Vue component rendering and prop handling.

  • Component rendering validation
  • Props passing and validation
  • Router integration testing
  • Component text content verification

Implementation Analysis

The implementation uses Vue Test Utils’ shallowMount and mount functions for component testing. The approach demonstrates both isolated and integrated testing patterns with TypeScript support.

  • Shallow mounting for isolated component testing
  • Full mounting for router integration
  • TypeScript type checking for props
  • Vue 3 compatibility handling

Technical Details

  • Jest test framework
  • Vue Test Utils for component mounting
  • TypeScript for type safety
  • Vue Router integration testing
  • Conditional template logic for Vue 2/3 compatibility

Best Practices Demonstrated

The test suite exemplifies Vue.js testing best practices through clear test organization and proper component isolation.

  • Component isolation using shallowMount
  • Descriptive test cases
  • Props validation patterns
  • Router integration testing patterns
  • TypeScript integration

vuejs/vue-cli

packages/@vue/cli-plugin-unit-jest/generator/template/tests/unit/example.spec.ts

            
<%_ if (hasTS) { _%>
<%_ if (!rootOptions.bare || !hasRouter) { _%>
import { shallowMount } from '@vue/test-utils'
<%_ } else { _%>
import { mount, createLocalVue } from '@vue/test-utils'
<%_ } _%>
<%_ if (!rootOptions.bare) { _%>
import HelloWorld from '@/components/HelloWorld.vue'

describe('HelloWorld.vue', () => {
  it('renders props.msg when passed', () => {
    const msg = 'new message'
    const wrapper = shallowMount(HelloWorld, {
      <%_ if (isVue3) { _%>
      props: { msg }
      <%_ } else { _%>
      propsData: { msg }
      <%_ } _%>
    })
    expect(wrapper.text()).toMatch(msg)
  })
})
<%_ } else { _%>
import App from '@/App.vue'
<%_ if (!hasRouter) { _%>

test('App should work', () => {
  const wrapper = shallowMount(App)
  expect(wrapper.text()).toMatch(`Welcome to Your Vue.js + TypeScript App`)
})

<%_ } else {_%>
import VueRouter from 'vue-router'
import router from '@/router'

const localVue = createLocalVue()
localVue.use(VueRouter)

test('App should render default route', () => {
  const wrapper = mount(App, {
    localVue,
    router
  })
  expect(wrapper.text()).toMatch(`Welcome to Your Vue.js App`)
})

<%_ } _%>
<%_ } _%>
<%_ } _%>