7
7
*/
8
8
9
9
var Base = require ( './base' ) ;
10
+ var fs = require ( 'fs' ) ;
11
+ var path = require ( 'path' ) ;
12
+ const createUnsupportedError = require ( '../errors' ) . createUnsupportedError ;
13
+ const utils = require ( '../utils' ) ;
10
14
var constants = require ( '../runner' ) . constants ;
11
15
var EVENT_TEST_PASS = constants . EVENT_TEST_PASS ;
16
+ var EVENT_TEST_PENDING = constants . EVENT_TEST_PENDING ;
12
17
var EVENT_TEST_FAIL = constants . EVENT_TEST_FAIL ;
13
18
var EVENT_TEST_END = constants . EVENT_TEST_END ;
14
19
var EVENT_RUN_END = constants . EVENT_RUN_END ;
15
- var EVENT_TEST_PENDING = constants . EVENT_TEST_PENDING ;
16
20
17
21
/**
18
22
* Expose `JSON`.
@@ -30,14 +34,22 @@ exports = module.exports = JSONReporter;
30
34
* @param {Runner } runner - Instance triggers reporter actions.
31
35
* @param {Object } [options] - runner options
32
36
*/
33
- function JSONReporter ( runner , options ) {
37
+ function JSONReporter ( runner , options = { } ) {
34
38
Base . call ( this , runner , options ) ;
35
39
36
40
var self = this ;
37
41
var tests = [ ] ;
38
42
var pending = [ ] ;
39
43
var failures = [ ] ;
40
44
var passes = [ ] ;
45
+ var output ;
46
+
47
+ if ( options . reporterOption && options . reporterOption . output ) {
48
+ if ( utils . isBrowser ( ) ) {
49
+ throw createUnsupportedError ( 'file output not supported in browser' ) ;
50
+ }
51
+ output = options . reporterOption . output ;
52
+ }
41
53
42
54
runner . on ( EVENT_TEST_END , function ( test ) {
43
55
tests . push ( test ) ;
@@ -66,7 +78,20 @@ function JSONReporter(runner, options) {
66
78
67
79
runner . testResults = obj ;
68
80
69
- process . stdout . write ( JSON . stringify ( obj , null , 2 ) ) ;
81
+ var json = JSON . stringify ( obj , null , 2 ) ;
82
+ if ( output ) {
83
+ try {
84
+ fs . mkdirSync ( path . dirname ( output ) , { recursive : true } ) ;
85
+ fs . writeFileSync ( output , json ) ;
86
+ } catch ( err ) {
87
+ console . error (
88
+ `${ Base . symbols . err } [mocha] writing output to "${ output } " failed: ${ err . message } \n`
89
+ ) ;
90
+ process . stdout . write ( json ) ;
91
+ }
92
+ } else {
93
+ process . stdout . write ( json ) ;
94
+ }
70
95
} ) ;
71
96
}
72
97
0 commit comments