CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-vue--cli-plugin-unit-mocha

Mocha unit testing plugin for Vue CLI that integrates mochapack with webpack configuration and JSDOM browser environment simulation.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

@vue/cli-plugin-unit-mocha

@vue/cli-plugin-unit-mocha is a Vue CLI plugin that adds Mocha unit testing capabilities to Vue.js projects. It provides a complete testing solution using mochapack with webpack integration, Chai assertions, and JSDOM browser environment simulation.

Package Information

  • Package Name: @vue/cli-plugin-unit-mocha
  • Package Type: npm
  • Language: JavaScript
  • Installation: vue add unit-mocha or npm install --save-dev @vue/cli-plugin-unit-mocha

Core Imports

The plugin is automatically registered when installed via Vue CLI and does not require manual imports for basic usage. However, the core exports are:

// Main plugin function (for Vue CLI)
const plugin = require("@vue/cli-plugin-unit-mocha");

// Generator functions (for advanced usage)
const { applyESLint, applyTS } = require("@vue/cli-plugin-unit-mocha/generator");

Basic Usage

After installation, the plugin provides the test:unit command:

# Run all unit tests
vue-cli-service test:unit

# Run tests in watch mode
vue-cli-service test:unit --watch

# Run specific test files
vue-cli-service test:unit tests/unit/MyComponent.spec.js

# Run tests matching a pattern
vue-cli-service test:unit --grep "user login"

Example test file structure:

// tests/unit/example.spec.js
import { expect } from 'chai'
import { shallowMount } from '@vue/test-utils'
import HelloWorld from '@/components/HelloWorld.vue'

describe('HelloWorld.vue', () => {
  it('renders props.msg when passed', () => {
    const msg = 'new message'
    const wrapper = shallowMount(HelloWorld, {
      propsData: { msg }
    })
    expect(wrapper.text()).to.include(msg)
  })
})

Architecture

The plugin consists of several key components:

  • Main Plugin Function: Configures webpack for testing and registers the test:unit command
  • Generator System: Scaffolds test files and configures project dependencies during installation
  • Test Environment Setup: Configures JSDOM browser simulation and global polyfills
  • Vue CLI UI Integration: Provides graphical interface for running tests through Vue CLI UI
  • Webpack Integration: Automatically configures webpack for optimal test performance

Capabilities

Plugin Configuration

Main plugin function that configures webpack and registers the test command.

/**
 * Main Vue CLI plugin function
 * @param {Object} api - Vue CLI Plugin API instance
 */
function plugin(api);

The plugin automatically:

  • Configures webpack target as 'node' in test environment
  • Sets up inline source maps for debugging
  • Optimizes Vue loader for SSR/CSR based on Vue version (2 vs 3)
  • Registers the test:unit command with comprehensive options

Test Command

The test:unit command provides comprehensive testing functionality with mochapack integration.

// Command registration (internal)
api.registerCommand('test:unit', {
  description: 'run unit tests with mochapack',
  usage: 'vue-cli-service test:unit [options] [...files]',
  options: CommandOptions
}, commandHandler);

interface CommandOptions {
  '--watch, -w': 'run in watch mode';
  '--grep, -g': 'only run tests matching <pattern>';
  '--slow, -s': '"slow" test threshold in milliseconds';
  '--timeout, -t': 'timeout threshold in milliseconds';
  '--bail, -b': 'bail after first test failure';
  '--require, -r': 'require the given module before running tests';
  '--include': 'include the given module into test bundle';
  '--inspect-brk': 'Enable inspector to debug the tests';
}

Command Usage Examples:

# Watch mode for development
vue-cli-service test:unit --watch

# Filter tests by pattern
vue-cli-service test:unit --grep "authentication"

# Set timeout for slow tests
vue-cli-service test:unit --timeout 10000

# Debug tests with Chrome DevTools
vue-cli-service test:unit --inspect-brk

# Run specific test files
vue-cli-service test:unit tests/unit/components/*.spec.js

Default Modes

The plugin defines default execution modes for commands.

const defaultModes = {
  'test:unit': 'test'
};

Project Generator

Main generator function that scaffolds test configuration and files.

/**
 * Vue CLI generator plugin function
 * @param {Object} api - Vue CLI Generator API instance
 * @param {Object} options - Plugin options
 * @param {Object} rootOptions - Root project options
 * @param {boolean} invoking - Whether plugin is being invoked
 */
function generator(api, options, rootOptions, invoking);

The generator automatically:

  • Renders test file templates based on project configuration
  • Adds test dependencies (@vue/test-utils, chai) to package.json
  • Adds test:unit npm script
  • Configures ESLint for test files if ESLint plugin is present
  • Configures TypeScript types if TypeScript plugin is present

ESLint Integration

Configures ESLint to recognize Mocha test environment and is exported as a standalone function.

/**
 * Apply ESLint configuration for test files
 * @param {Object} api - Vue CLI Generator API instance
 */
function applyESLint(api);

// Also available as export from generator
module.exports.applyESLint = applyESLint;

Adds ESLint overrides for test file patterns:

  • **/__tests__/*.{j,t}s?(x)
  • **/tests/unit/**/*.spec.{j,t}s?(x)

ESLint configuration added:

interface ESLintConfig {
  overrides: [{
    files: string[];
    env: {
      mocha: boolean;
    };
  }];
}

TypeScript Integration

Configures TypeScript support for Mocha and Chai, and is exported as a standalone function.

/**
 * Apply TypeScript configuration for test files
 * @param {Object} api - Vue CLI Generator API instance
 * @param {boolean} invoking - Whether plugin is being invoked
 */
function applyTS(api, invoking);

// Also available as export from generator
module.exports.applyTS = applyTS;

Automatically:

  • Adds @types/mocha and @types/chai to devDependencies from plugin's own package.json
  • Updates tsconfig.json to include 'mocha' and 'chai' types when invoking
  • Reads and modifies tsconfig.json compilerOptions.types array

TypeScript types added:

interface TypeScriptTypes {
  '@types/mocha': string;  // Version from plugin devDependencies
  '@types/chai': string;   // Version from plugin devDependencies
}

Vue CLI UI Integration

Provides graphical interface integration for Vue CLI UI with interactive prompts.

/**
 * Vue CLI UI plugin function
 * @param {Object} api - Vue CLI UI API instance
 */
function uiPlugin(api);

interface UITaskConfig {
  match: RegExp;  // /vue-cli-service test:unit/
  description: string;  // 'org.vue.mocha.tasks.test.description'
  link: string;  // Plugin documentation URL
  prompts: UIPrompt[];
  onBeforeRun: (context: { answers: any; args: string[] }) => void;
}

interface UIPrompt {
  name: string;        // 'watch'
  type: string;        // 'confirm'
  default: boolean;    // false
  description: string; // 'org.vue.mocha.tasks.test.watch'
}

Registers a task description with:

  • Task matching pattern: /vue-cli-service test:unit/
  • Watch mode confirm prompt with default false
  • Documentation link: https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-unit-mocha#injected-commands
  • Pre-run handler that adds --watch flag when watch mode is enabled

Test Environment Setup

The setup module configures the test environment with browser simulation and required polyfills.

// Global JSDOM setup with browser environment simulation
require('jsdom-global')(undefined, { 
  pretendToBeVisual: true, 
  url: 'http://localhost' 
});

// Global polyfills for browser APIs and Vue compatibility
window.Date = Date;                    // Vue Test Utils compatibility
global.ShadowRoot = window.ShadowRoot; // Vue 3 compatibility
global.SVGElement = window.SVGElement; // SVG element support
global.XMLSerializer = window.XMLSerializer; // Vue Test Utils serialization

The setup automatically provides:

  • JSDOM environment with visual rendering simulation (pretendToBeVisual: true)
  • Browser API polyfills for Vue.js compatibility
  • Date object fix for Vue Test Utils (issue #936)
  • ShadowRoot support for Vue 3 (PR #2943)
  • XMLSerializer for Vue Test Utils (issue #1253)
  • Global objects required for Vue Test Utils and component testing

Test File Templates

The plugin includes template files for generating initial test structures.

JavaScript Template

// Template variables available during generation
interface TemplateContext {
  hasTS: boolean;           // TypeScript plugin present
  hasRouter: boolean;       // Router plugin present  
  isVue3: boolean;         // Vue 3 project (from rootOptions.vueVersion === '3')
  rootOptions: {
    bare?: boolean;         // Bare project structure (optional)
    vueVersion?: string;    // Vue version ('2' or '3')
  };
}

Template generation logic:

  • Uses conditional EJS syntax (<%_ if (condition) { _%>)
  • Supports different imports based on Vue version and router presence
  • Generates different test structures for bare vs full projects
  • Handles Vue 2 vs Vue 3 API differences (propsData vs props)

TypeScript Template

Similar structure with TypeScript type annotations and imports.

Dependencies

Runtime Dependencies

interface RuntimeDependencies {
  '@vue/cli-shared-utils': '^5.0.9';  // Vue CLI utilities
  'jsdom': '^18.0.1';                 // DOM implementation
  'jsdom-global': '^3.0.2';           // Global JSDOM setup
  'mocha': '^8.3.0';                  // Test framework
  'mochapack': '^2.1.0';              // Webpack integration
}

Development Dependencies Added

interface AddedDevDependencies {
  '@vue/test-utils': string;  // Vue component testing utilities (version varies by Vue version)
  'chai': '^4.2.0';          // Assertion library
  '@types/mocha'?: string;   // TypeScript definitions (if TypeScript present)
  '@types/chai'?: string;    // TypeScript definitions (if TypeScript present)
}

Peer Dependencies

interface PeerDependencies {
  '@vue/cli-service': '^3.0.0 || ^4.0.0 || ^5.0.0-0';  // Vue CLI service
}

docs

index.md

tile.json