0
# @vue/cli-plugin-unit-mocha
1
2
@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.
3
4
## Package Information
5
6
- **Package Name**: @vue/cli-plugin-unit-mocha
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `vue add unit-mocha` or `npm install --save-dev @vue/cli-plugin-unit-mocha`
10
11
## Core Imports
12
13
The plugin is automatically registered when installed via Vue CLI and does not require manual imports for basic usage. However, the core exports are:
14
15
```javascript
16
// Main plugin function (for Vue CLI)
17
const plugin = require("@vue/cli-plugin-unit-mocha");
18
19
// Generator functions (for advanced usage)
20
const { applyESLint, applyTS } = require("@vue/cli-plugin-unit-mocha/generator");
21
```
22
23
## Basic Usage
24
25
After installation, the plugin provides the `test:unit` command:
26
27
```bash
28
# Run all unit tests
29
vue-cli-service test:unit
30
31
# Run tests in watch mode
32
vue-cli-service test:unit --watch
33
34
# Run specific test files
35
vue-cli-service test:unit tests/unit/MyComponent.spec.js
36
37
# Run tests matching a pattern
38
vue-cli-service test:unit --grep "user login"
39
```
40
41
Example test file structure:
42
43
```javascript
44
// tests/unit/example.spec.js
45
import { expect } from 'chai'
46
import { shallowMount } from '@vue/test-utils'
47
import HelloWorld from '@/components/HelloWorld.vue'
48
49
describe('HelloWorld.vue', () => {
50
it('renders props.msg when passed', () => {
51
const msg = 'new message'
52
const wrapper = shallowMount(HelloWorld, {
53
propsData: { msg }
54
})
55
expect(wrapper.text()).to.include(msg)
56
})
57
})
58
```
59
60
## Architecture
61
62
The plugin consists of several key components:
63
64
- **Main Plugin Function**: Configures webpack for testing and registers the `test:unit` command
65
- **Generator System**: Scaffolds test files and configures project dependencies during installation
66
- **Test Environment Setup**: Configures JSDOM browser simulation and global polyfills
67
- **Vue CLI UI Integration**: Provides graphical interface for running tests through Vue CLI UI
68
- **Webpack Integration**: Automatically configures webpack for optimal test performance
69
70
## Capabilities
71
72
### Plugin Configuration
73
74
Main plugin function that configures webpack and registers the test command.
75
76
```javascript { .api }
77
/**
78
* Main Vue CLI plugin function
79
* @param {Object} api - Vue CLI Plugin API instance
80
*/
81
function plugin(api);
82
```
83
84
The plugin automatically:
85
- Configures webpack target as 'node' in test environment
86
- Sets up inline source maps for debugging
87
- Optimizes Vue loader for SSR/CSR based on Vue version (2 vs 3)
88
- Registers the `test:unit` command with comprehensive options
89
90
### Test Command
91
92
The `test:unit` command provides comprehensive testing functionality with mochapack integration.
93
94
```javascript { .api }
95
// Command registration (internal)
96
api.registerCommand('test:unit', {
97
description: 'run unit tests with mochapack',
98
usage: 'vue-cli-service test:unit [options] [...files]',
99
options: CommandOptions
100
}, commandHandler);
101
102
interface CommandOptions {
103
'--watch, -w': 'run in watch mode';
104
'--grep, -g': 'only run tests matching <pattern>';
105
'--slow, -s': '"slow" test threshold in milliseconds';
106
'--timeout, -t': 'timeout threshold in milliseconds';
107
'--bail, -b': 'bail after first test failure';
108
'--require, -r': 'require the given module before running tests';
109
'--include': 'include the given module into test bundle';
110
'--inspect-brk': 'Enable inspector to debug the tests';
111
}
112
```
113
114
**Command Usage Examples:**
115
116
```bash
117
# Watch mode for development
118
vue-cli-service test:unit --watch
119
120
# Filter tests by pattern
121
vue-cli-service test:unit --grep "authentication"
122
123
# Set timeout for slow tests
124
vue-cli-service test:unit --timeout 10000
125
126
# Debug tests with Chrome DevTools
127
vue-cli-service test:unit --inspect-brk
128
129
# Run specific test files
130
vue-cli-service test:unit tests/unit/components/*.spec.js
131
```
132
133
### Default Modes
134
135
The plugin defines default execution modes for commands.
136
137
```javascript { .api }
138
const defaultModes = {
139
'test:unit': 'test'
140
};
141
```
142
143
### Project Generator
144
145
Main generator function that scaffolds test configuration and files.
146
147
```javascript { .api }
148
/**
149
* Vue CLI generator plugin function
150
* @param {Object} api - Vue CLI Generator API instance
151
* @param {Object} options - Plugin options
152
* @param {Object} rootOptions - Root project options
153
* @param {boolean} invoking - Whether plugin is being invoked
154
*/
155
function generator(api, options, rootOptions, invoking);
156
```
157
158
The generator automatically:
159
- Renders test file templates based on project configuration
160
- Adds test dependencies (@vue/test-utils, chai) to package.json
161
- Adds `test:unit` npm script
162
- Configures ESLint for test files if ESLint plugin is present
163
- Configures TypeScript types if TypeScript plugin is present
164
165
### ESLint Integration
166
167
Configures ESLint to recognize Mocha test environment and is exported as a standalone function.
168
169
```javascript { .api }
170
/**
171
* Apply ESLint configuration for test files
172
* @param {Object} api - Vue CLI Generator API instance
173
*/
174
function applyESLint(api);
175
176
// Also available as export from generator
177
module.exports.applyESLint = applyESLint;
178
```
179
180
Adds ESLint overrides for test file patterns:
181
- `**/__tests__/*.{j,t}s?(x)`
182
- `**/tests/unit/**/*.spec.{j,t}s?(x)`
183
184
ESLint configuration added:
185
186
```javascript { .api }
187
interface ESLintConfig {
188
overrides: [{
189
files: string[];
190
env: {
191
mocha: boolean;
192
};
193
}];
194
}
195
```
196
197
### TypeScript Integration
198
199
Configures TypeScript support for Mocha and Chai, and is exported as a standalone function.
200
201
```javascript { .api }
202
/**
203
* Apply TypeScript configuration for test files
204
* @param {Object} api - Vue CLI Generator API instance
205
* @param {boolean} invoking - Whether plugin is being invoked
206
*/
207
function applyTS(api, invoking);
208
209
// Also available as export from generator
210
module.exports.applyTS = applyTS;
211
```
212
213
Automatically:
214
- Adds @types/mocha and @types/chai to devDependencies from plugin's own package.json
215
- Updates tsconfig.json to include 'mocha' and 'chai' types when invoking
216
- Reads and modifies tsconfig.json compilerOptions.types array
217
218
TypeScript types added:
219
220
```javascript { .api }
221
interface TypeScriptTypes {
222
'@types/mocha': string; // Version from plugin devDependencies
223
'@types/chai': string; // Version from plugin devDependencies
224
}
225
```
226
227
### Vue CLI UI Integration
228
229
Provides graphical interface integration for Vue CLI UI with interactive prompts.
230
231
```javascript { .api }
232
/**
233
* Vue CLI UI plugin function
234
* @param {Object} api - Vue CLI UI API instance
235
*/
236
function uiPlugin(api);
237
238
interface UITaskConfig {
239
match: RegExp; // /vue-cli-service test:unit/
240
description: string; // 'org.vue.mocha.tasks.test.description'
241
link: string; // Plugin documentation URL
242
prompts: UIPrompt[];
243
onBeforeRun: (context: { answers: any; args: string[] }) => void;
244
}
245
246
interface UIPrompt {
247
name: string; // 'watch'
248
type: string; // 'confirm'
249
default: boolean; // false
250
description: string; // 'org.vue.mocha.tasks.test.watch'
251
}
252
```
253
254
Registers a task description with:
255
- Task matching pattern: `/vue-cli-service test:unit/`
256
- Watch mode confirm prompt with default false
257
- Documentation link: `https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-unit-mocha#injected-commands`
258
- Pre-run handler that adds `--watch` flag when watch mode is enabled
259
260
### Test Environment Setup
261
262
The setup module configures the test environment with browser simulation and required polyfills.
263
264
```javascript { .api }
265
// Global JSDOM setup with browser environment simulation
266
require('jsdom-global')(undefined, {
267
pretendToBeVisual: true,
268
url: 'http://localhost'
269
});
270
271
// Global polyfills for browser APIs and Vue compatibility
272
window.Date = Date; // Vue Test Utils compatibility
273
global.ShadowRoot = window.ShadowRoot; // Vue 3 compatibility
274
global.SVGElement = window.SVGElement; // SVG element support
275
global.XMLSerializer = window.XMLSerializer; // Vue Test Utils serialization
276
```
277
278
The setup automatically provides:
279
- JSDOM environment with visual rendering simulation (`pretendToBeVisual: true`)
280
- Browser API polyfills for Vue.js compatibility
281
- Date object fix for Vue Test Utils (issue #936)
282
- ShadowRoot support for Vue 3 (PR #2943)
283
- XMLSerializer for Vue Test Utils (issue #1253)
284
- Global objects required for Vue Test Utils and component testing
285
286
## Test File Templates
287
288
The plugin includes template files for generating initial test structures.
289
290
### JavaScript Template
291
292
```javascript { .api }
293
// Template variables available during generation
294
interface TemplateContext {
295
hasTS: boolean; // TypeScript plugin present
296
hasRouter: boolean; // Router plugin present
297
isVue3: boolean; // Vue 3 project (from rootOptions.vueVersion === '3')
298
rootOptions: {
299
bare?: boolean; // Bare project structure (optional)
300
vueVersion?: string; // Vue version ('2' or '3')
301
};
302
}
303
```
304
305
Template generation logic:
306
- Uses conditional EJS syntax (`<%_ if (condition) { _%>`)
307
- Supports different imports based on Vue version and router presence
308
- Generates different test structures for bare vs full projects
309
- Handles Vue 2 vs Vue 3 API differences (propsData vs props)
310
311
### TypeScript Template
312
313
Similar structure with TypeScript type annotations and imports.
314
315
## Dependencies
316
317
### Runtime Dependencies
318
319
```javascript { .api }
320
interface RuntimeDependencies {
321
'@vue/cli-shared-utils': '^5.0.9'; // Vue CLI utilities
322
'jsdom': '^18.0.1'; // DOM implementation
323
'jsdom-global': '^3.0.2'; // Global JSDOM setup
324
'mocha': '^8.3.0'; // Test framework
325
'mochapack': '^2.1.0'; // Webpack integration
326
}
327
```
328
329
### Development Dependencies Added
330
331
```javascript { .api }
332
interface AddedDevDependencies {
333
'@vue/test-utils': string; // Vue component testing utilities (version varies by Vue version)
334
'chai': '^4.2.0'; // Assertion library
335
'@types/mocha'?: string; // TypeScript definitions (if TypeScript present)
336
'@types/chai'?: string; // TypeScript definitions (if TypeScript present)
337
}
338
```
339
340
### Peer Dependencies
341
342
```javascript { .api }
343
interface PeerDependencies {
344
'@vue/cli-service': '^3.0.0 || ^4.0.0 || ^5.0.0-0'; // Vue CLI service
345
}
346
```