Back to Repositories

Testing Vue Component Rendering and Props Implementation in vue-cli

This test suite demonstrates unit testing for Vue.js components using Mocha and Chai assertions. It focuses on verifying component rendering and prop handling in both basic and router-enabled Vue applications.

Test Coverage Overview

The test suite provides essential coverage for Vue component rendering and prop management.

  • Tests component message prop rendering
  • Verifies text content inclusion
  • Handles both basic and router-integrated scenarios
  • Covers Vue 2 and Vue 3 compatibility

Implementation Analysis

The implementation utilizes Vue Test Utils for component mounting and interaction. It employs conditional logic to handle different Vue versions and project configurations.

  • Uses shallowMount for isolated component testing
  • Implements createLocalVue for router integration
  • Supports both propsData and props syntax

Technical Details

  • Testing Framework: Mocha
  • Assertion Library: Chai
  • Test Utils: @vue/test-utils
  • Component Testing: HelloWorld.vue and App.vue
  • Router Integration: Vue Router when enabled

Best Practices Demonstrated

The test suite exemplifies Vue.js testing best practices with clean, focused test cases.

  • Isolated component testing
  • Proper prop passing methodology
  • Clear test descriptions
  • Modular test organization
  • Framework-specific configuration handling

vuejs/vue-cli

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

            
<%_ if (!hasTS) { _%>
import { expect } from 'chai'
<%_ 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()).to.include(msg)
  })
})
<%_ } else { _%>
import App from '@/App.vue'
<%_ if (!hasRouter) { _%>

describe('App', () => {
  it('should work', () => {
    const wrapper = shallowMount(App)
    expect(wrapper.text()).to.include(`Welcome to Your Vue.js App`)
  })
})

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

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

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

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