UNPKG

2.45 kBJavaScriptView Raw
1'use strict';
2const path = require('path');
3const arrify = require('arrify');
4const PluginError = require('plugin-error');
5const through = require('through2');
6const Jasmine = require('jasmine');
7const Reporter = require('jasmine-terminal-reporter');
8
9function deleteRequireCache(id) {
10 if (!id || id.includes('node_modules')) {
11 return;
12 }
13
14 const files = require.cache[id];
15
16 if (files !== undefined) {
17 for (const file of Object.keys(files.children)) {
18 deleteRequireCache(files.children[file].id);
19 }
20
21 delete require.cache[id];
22 }
23}
24
25module.exports = options => {
26 options = options || {};
27
28 const jasmine = new Jasmine();
29
30 if (options.timeout) {
31 jasmine.jasmine.DEFAULT_TIMEOUT_INTERVAL = options.timeout;
32 }
33
34 if (options.config) {
35 jasmine.loadConfig(options.config);
36 }
37
38 const errorOnFail = options.errorOnFail === undefined ? true : options.errorOnFail;
39 const color = process.argv.indexOf('--no-color') === -1;
40 const reporter = options.reporter;
41
42 // Default reporter behavior changed in 2.5.2
43 if (jasmine.env.clearReporters) {
44 jasmine.env.clearReporters();
45 }
46
47 if (reporter) {
48 for (const el of arrify(reporter)) {
49 jasmine.addReporter(el);
50 }
51 } else {
52 jasmine.addReporter(new Reporter({
53 isVerbose: options.verbose,
54 showColors: color,
55 includeStackTrace: options.includeStackTrace
56 }));
57 }
58
59 return through.obj((file, enc, cb) => {
60 if (file.isNull()) {
61 cb(null, file);
62 return;
63 }
64
65 if (file.isStream()) {
66 cb(new PluginError('gulp-jasmine', 'Streaming not supported'));
67 return;
68 }
69
70 // Get the cache object of the specs.js file,
71 // delete it and its children recursively from cache
72 const resolvedPath = path.resolve(file.path);
73 const modId = require.resolve(resolvedPath);
74 deleteRequireCache(modId);
75
76 jasmine.addSpecFile(resolvedPath);
77
78 cb(null, file);
79 }, function (cb) {
80 const self = this;
81
82 try {
83 if (jasmine.helperFiles) {
84 for (const helper of jasmine.helperFiles) {
85 const resolvedPath = path.resolve(helper);
86 const modId = require.resolve(resolvedPath);
87 deleteRequireCache(modId);
88 }
89 }
90
91 jasmine.onComplete(passed => {
92 if (errorOnFail && !passed) {
93 cb(new PluginError('gulp-jasmine', 'Tests failed', {
94 showStack: false
95 }));
96 } else {
97 self.emit('jasmineDone', passed);
98 cb();
99 }
100 });
101
102 jasmine.execute();
103 } catch (err) {
104 cb(new PluginError('gulp-jasmine', err, {showStack: true}));
105 }
106 });
107};