/
watch-run.js
107 lines (94 loc) · 2.05 KB
/
watch-run.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
'use strict';
const utils = require('../utils');
const Context = require('../context');
const Mocha = require('../mocha');
/**
* Exports the `watchRun` function that runs mocha in "watch" mode.
* @see module:lib/cli/run-helpers
* @module
* @private
*/
/**
* Run Mocha in "watch" mode
* @param {Mocha} mocha - Mocha instance
* @param {Object} opts - Options
* @param {string[]} opts.extension - List of extensions to watch
* @param {string|RegExp} opts.grep - Grep for test titles
* @param {string} opts.ui - User interface
* @param {string[]} opts.files - Array of test files
* @private
*/
module.exports = (mocha, {extension, grep, ui, files}) => {
let runner;
console.log();
hideCursor();
process.on('SIGINT', () => {
showCursor();
console.log('\n');
// By UNIX/Posix convention this indicates that the process was
// killed by SIGINT which has portable number 2.
process.exit(128 + 2);
});
const watchFiles = utils.files(process.cwd(), extension);
let runAgain = false;
const loadAndRun = () => {
try {
mocha.files = files;
runAgain = false;
runner = mocha.run(() => {
runner = null;
if (runAgain) {
rerun();
}
});
} catch (e) {
console.log(e.stack);
}
};
const purge = () => {
watchFiles.forEach(Mocha.unloadFile);
};
loadAndRun();
const rerun = () => {
purge();
eraseLine();
if (!grep) {
mocha.grep(null);
}
mocha.suite = mocha.suite.clone();
mocha.suite.ctx = new Context();
mocha.ui(ui);
loadAndRun();
};
utils.watch(watchFiles, () => {
runAgain = true;
if (runner) {
runner.abort();
} else {
rerun();
}
});
};
/**
* Hide the cursor.
* @ignore
* @private
*/
const hideCursor = () => {
process.stdout.write('\u001b[?25l');
};
/**
* Show the cursor.
* @ignore
* @private
*/
const showCursor = () => {
process.stdout.write('\u001b[?25h');
};
/**
* Erases the line on stdout
* @private
*/
const eraseLine = () => {
process.stdout.write('\u001b[2K');
};