Back to Repositories

Testing Vue Component Rendering and Props in vue-cli

This test suite demonstrates basic Vue.js component testing using Jest and Vue Test Utils. It focuses on validating component rendering and prop handling for both standard and router-enabled Vue applications.

Test Coverage Overview

The test suite provides coverage for fundamental Vue component functionality, including prop passing and text rendering.

  • Tests component mounting and rendering
  • Validates prop message passing
  • Handles router integration scenarios
  • Covers both bare and full application setups

Implementation Analysis

The testing approach utilizes Vue Test Utils’ shallowMount and mount functions for component isolation and integration testing.

  • Uses shallow rendering for isolated component testing
  • Implements localVue for router testing
  • Supports both Vue 2 and Vue 3 prop handling
  • Configures test environment based on application structure

Technical Details

  • Jest as the test runner
  • @vue/test-utils for component testing
  • Vue Router integration testing support
  • Conditional template logic for TypeScript compatibility
  • Dynamic import handling based on project configuration

Best Practices Demonstrated

The test suite exemplifies Vue.js testing best practices with clean, focused test cases and proper component isolation.

  • Component isolation through shallow mounting
  • Explicit test descriptions
  • Proper setup of testing environment
  • Clear expectations and assertions
  • Modular test organization

vuejs/vue-cli

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

            
<%_ 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 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`)
})

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