grunt-contrib-jasmine/tasks/jasmine.js

424 lines
12 KiB
JavaScript
Raw Normal View History

2012-11-02 13:03:09 +08:00
/*
* grunt-contrib-jasmine
* http://gruntjs.com/
*
2015-01-02 03:30:19 +08:00
* Copyright (c) 2015 GruntJS Team
2012-11-02 13:03:09 +08:00
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// node api
var fs = require('fs'),
path = require('path');
// npm lib
var phantomjs = require('grunt-lib-phantomjs').init(grunt),
chalk = require('chalk'),
_ = require('lodash');
// local lib
var jasmine = require('./lib/jasmine').init(grunt, phantomjs);
2015-04-24 06:36:23 +08:00
var junitTemplate = path.join(__dirname, '/jasmine/templates/JUnit.tmpl');
var status = {};
2014-03-21 23:15:08 +08:00
var symbols = {
2015-04-24 06:36:23 +08:00
none: {
check: '',
error: '',
splat: ''
2014-03-21 23:15:08 +08:00
},
2015-04-24 06:36:23 +08:00
short: {
check: '.',
error: 'X',
splat: '*'
2014-02-28 06:02:10 +08:00
},
2015-04-24 06:36:23 +08:00
full: {
check: '✓',
error: 'X',
splat: '*'
2014-02-28 06:02:10 +08:00
}
};
//With node.js on Windows: use symbols available in terminal default fonts
//https://github.com/visionmedia/mocha/pull/641
if (process && process.platform === 'win32') {
symbols = {
2015-04-24 06:36:23 +08:00
none: {
check: '',
error: '',
splat: ''
2014-03-21 23:15:08 +08:00
},
2015-04-24 06:36:23 +08:00
short: {
check: '.',
error: '\u00D7',
splat: '*'
2014-02-28 06:02:10 +08:00
},
2015-04-24 06:36:23 +08:00
full: {
check: '\u221A',
error: '\u00D7',
splat: '*'
2014-02-28 06:02:10 +08:00
}
};
}
grunt.registerMultiTask('jasmine', 'Run jasmine specs headlessly through PhantomJS.', function() {
2012-11-02 13:03:09 +08:00
// Merge task-specific options with these defaults.
var options = this.options({
2015-04-24 06:36:23 +08:00
version: '2.0.1',
timeout: 10000,
styles: [],
specs: [],
helpers: [],
vendor: [],
polyfills: [],
outfile: '_SpecRunner.html',
host: '',
template: path.join(__dirname, '/jasmine/templates/DefaultRunner.tmpl'),
templateOptions: {},
junit: {},
ignoreEmpty: grunt.option('force') === true,
2014-02-28 06:06:29 +08:00
display: 'full',
2015-04-24 06:36:23 +08:00
summary: false
});
2013-01-10 13:14:50 +08:00
2012-11-02 13:03:09 +08:00
if (grunt.option('debug')) {
grunt.log.debug(options);
2012-11-02 13:03:09 +08:00
}
setup(options);
// The filter returned no spec files so skip phantom.
if (!jasmine.buildSpecrunner(this.filesSrc, options)) {
return removePhantomListeners();
}
// If we're just building (e.g. for web), skip phantom.
if (this.flags.build) {
removePhantomListeners();
return;
}
var done = this.async();
phantomRunner(options, function(err, status) {
2013-03-11 23:08:43 +08:00
var success = !err && status.failed === 0;
if (err) {
grunt.log.error(err);
}
if (status.failed === 0) {
grunt.log.ok('0 failures');
} else {
grunt.log.error(status.failed + ' failures');
}
2013-03-11 23:08:43 +08:00
teardown(options, function() {
done(success);
});
});
2012-11-02 13:03:09 +08:00
});
2015-04-24 06:36:23 +08:00
function phantomRunner(options, cb) {
var file = options.outfile;
if (options.host) {
2015-02-27 16:11:19 +08:00
if (!(/\/$/).test(options.host)) {
2015-04-24 06:36:23 +08:00
options.host += '/';
2015-02-27 16:11:19 +08:00
}
file = options.host + options.outfile;
}
grunt.verbose.subhead('Testing jasmine specs via phantom').or.writeln('Testing jasmine specs via PhantomJS');
grunt.log.writeln('');
phantomjs.spawn(file, {
2015-04-24 06:36:23 +08:00
failCode: 90,
options: options,
done: function(err) {
cb(err, status);
}
});
}
function teardown(options, cb) {
removePhantomListeners();
if (!options.keepRunner && fs.statSync(options.outfile).isFile()) {
fs.unlink(options.outfile);
}
if (!options.keepRunner) {
jasmine.cleanTemp(cb);
} else {
cb();
}
}
function removePhantomListeners() {
phantomjs.removeAllListeners();
phantomjs.listenersAny().length = 0;
}
function setup(options) {
var indentLevel = 1,
tabstop = 2,
thisRun = {},
suites = {},
currentSuite;
status = {
2015-04-24 06:36:23 +08:00
failed: 0
};
function indent(times) {
return new Array(+times * tabstop).join(' ');
}
2014-10-07 10:36:13 +08:00
phantomjs.on('fail.load', function() {
grunt.log.writeln();
grunt.warn('PhantomJS failed to load your page.', 90);
});
phantomjs.on('fail.timeout', function() {
grunt.log.writeln();
grunt.warn('PhantomJS timed out, possibly due to an unfinished async spec.', 90);
});
phantomjs.on('console', function(msg) {
thisRun.cleanConsole = false;
2015-04-24 06:36:23 +08:00
if (options.display === 'full') {
grunt.log.writeln('\n' + chalk.yellow('log: ') + msg);
}
2013-11-21 08:50:53 +08:00
});
2015-04-24 06:36:23 +08:00
phantomjs.on('error.onError', function(string, trace) {
if (trace && trace.length) {
grunt.log.error(chalk.red(string) + ' at ');
trace.forEach(function(line) {
2015-04-24 06:36:23 +08:00
var file = line.file.replace(/^file:/, '');
var message = grunt.util._('%s:%d %s').sprintf(path.relative('.', file), line.line, line.function);
grunt.log.error(chalk.red(message));
});
} else {
2015-04-24 06:36:23 +08:00
grunt.log.error('Error caught from PhantomJS. More info can be found by opening the Spec Runner in a browser.');
grunt.warn(string);
}
});
phantomjs.onAny(function() {
var args = [this.event].concat(grunt.util.toArray(arguments));
grunt.event.emit.apply(grunt.event, args);
});
phantomjs.on('jasmine.jasmineStarted', function() {
grunt.verbose.writeln('Jasmine Runner Starting...');
thisRun.startTime = (new Date()).getTime();
thisRun.executedSpecs = 0;
thisRun.passedSpecs = 0;
thisRun.failedSpecs = 0;
thisRun.skippedSpecs = 0;
thisRun.summary = [];
});
phantomjs.on('jasmine.suiteStarted', function(suiteMetaData) {
currentSuite = suiteMetaData.id;
suites[currentSuite] = {
2015-04-24 06:36:23 +08:00
name: suiteMetaData.fullName,
timestamp: new Date(suiteMetaData.startTime),
errors: 0,
tests: 0,
failures: 0,
testcases: []
};
2015-04-24 06:36:23 +08:00
if (options.display === 'full') {
grunt.log.write(indent(indentLevel++));
grunt.log.writeln(chalk.bold(suiteMetaData.description));
}
});
phantomjs.on('jasmine.suiteDone', function(suiteMetaData) {
suites[suiteMetaData.id].time = suiteMetaData.duration / 1000;
2014-07-20 20:30:06 +08:00
2015-04-24 06:36:23 +08:00
if (indentLevel > 1) {
indentLevel--;
}
});
phantomjs.on('jasmine.specStarted', function(specMetaData) {
thisRun.executedSpecs++;
thisRun.cleanConsole = true;
2015-04-24 06:36:23 +08:00
if (options.display === 'full') {
grunt.log.write(indent(indentLevel) + '- ' + chalk.grey(specMetaData.description) + '...');
2015-04-24 06:36:23 +08:00
} else if (options.display === 'short') {
grunt.log.write(chalk.grey('.'));
}
});
phantomjs.on('jasmine.specDone', function(specMetaData) {
var specSummary = {
2015-04-24 06:36:23 +08:00
assertions: 0,
classname: suites[currentSuite].name,
name: specMetaData.description,
time: specMetaData.duration / 1000,
failureMessages: []
};
suites[currentSuite].tests++;
var color = 'yellow',
symbol = 'splat';
2015-04-24 06:36:23 +08:00
if (specMetaData.status === 'passed') {
thisRun.passedSpecs++;
color = 'green';
symbol = 'check';
2015-04-24 06:36:23 +08:00
} else if (specMetaData.status === 'failed') {
thisRun.failedSpecs++;
status.failed++;
color = 'red';
symbol = 'error';
suites[currentSuite].failures++;
suites[currentSuite].errors += specMetaData.failedExpectations.length;
2015-04-24 06:36:23 +08:00
specSummary.failureMessages = specMetaData.failedExpectations.map(function(error) {
return error.message;
});
thisRun.summary.push({
2014-02-28 06:06:29 +08:00
suite: suites[currentSuite].name,
name: specMetaData.description,
2015-04-24 06:36:23 +08:00
errors: specMetaData.failedExpectations.map(function(error) {
2014-02-28 06:06:29 +08:00
return {
2014-07-20 20:30:06 +08:00
message: error.message,
stack: error.stack
2014-02-28 06:06:29 +08:00
};
})
});
} else {
thisRun.skippedSpecs++;
}
suites[currentSuite].testcases.push(specSummary);
// If we're writing to a proper terminal, make it fancy.
if (process.stdout.clearLine) {
2015-04-24 06:36:23 +08:00
if (options.display === 'full') {
process.stdout.clearLine();
process.stdout.cursorTo(0);
grunt.log.writeln(
indent(indentLevel) +
2014-03-20 07:20:42 +08:00
chalk[color].bold(symbols.full[symbol]) + ' ' +
chalk.grey(specMetaData.description)
);
2015-04-24 06:36:23 +08:00
} else if (options.display === 'short') {
process.stdout.moveCursor(-1);
2014-02-28 06:02:10 +08:00
grunt.log.write(chalk[color].bold(symbols.short[symbol]));
}
} else {
// If we haven't written out since we've started
if (thisRun.cleanConsole) {
// then append to the current line.
2014-03-21 23:15:08 +08:00
if (options.display !== 'none') {
grunt.log.writeln('...' + symbols[options.display][symbol]);
}
} else {
// Otherwise reprint the current spec and status.
2014-03-21 23:15:08 +08:00
if (options.display !== 'none') {
grunt.log.writeln(
indent(indentLevel) + '...' +
chalk.grey(specMetaData.description) + '...' +
symbols[options.display][symbol]
);
}
}
}
2015-04-24 06:36:23 +08:00
specMetaData.failedExpectations.forEach(function(error, i) {
var specIndex = ' (' + (i + 1) + ')';
if (options.display === 'full') {
grunt.log.writeln(indent(indentLevel + 1) + chalk.red(error.message + specIndex));
}
phantomjs.emit('onError', error.message, error.stack);
});
});
2015-04-24 06:36:23 +08:00
phantomjs.on('jasmine.jasmineDone', function() {
var dur = (new Date()).getTime() - thisRun.startTime;
2015-04-24 06:36:23 +08:00
var specQuantity = thisRun.executedSpecs + (thisRun.executedSpecs === 1 ? ' spec ' : ' specs ');
grunt.verbose.writeln('Jasmine runner finished');
if (thisRun.executedSpecs === 0) {
// log.error will print the message but not fail the task, warn will do both.
2015-04-24 06:36:23 +08:00
var log = options.ignoreEmpty ? grunt.log.error : grunt.warn;
log('No specs executed, is there a configuration error?');
2013-06-16 00:38:39 +08:00
}
2014-03-21 23:15:08 +08:00
2015-04-24 06:36:23 +08:00
if (options.display === 'short') {
grunt.log.writeln();
}
2015-04-24 06:36:23 +08:00
if (options.summary && thisRun.summary.length) {
2014-02-28 06:06:29 +08:00
grunt.log.writeln();
logSummary(thisRun.summary);
2014-02-28 06:06:29 +08:00
}
if (options.junit && options.junit.path) {
writeJunitXml(suites);
}
2015-04-24 06:36:23 +08:00
grunt.log.writeln('\n' + specQuantity + 'in ' + (dur / 1000) + 's.');
});
2014-03-21 23:15:08 +08:00
function logSummary(tests) {
grunt.log.writeln('Summary (' + tests.length + ' tests failed)');
2015-04-24 06:36:23 +08:00
_.forEach(tests, function(test) {
grunt.log.writeln(chalk.red(symbols.options.display.error) + ' ' + test.suite + ' ' + test.name);
_.forEach(test.errors, function(error) {
2014-07-20 20:30:06 +08:00
grunt.log.writeln(indent(2) + chalk.red(error.message));
logStack(error.stack, 2);
});
});
}
2014-07-20 20:30:06 +08:00
function logStack(stack, indentLevel) {
var lines = (stack || '').split('\n');
for (var i = 0; i < lines.length && i < 11; i++) {
2015-04-24 06:36:23 +08:00
grunt.log.writeln(indent(indentLevel) + lines[i]);
2014-07-20 20:30:06 +08:00
}
}
2015-04-24 06:36:23 +08:00
function writeJunitXml(testsuites) {
var template = grunt.file.read(options.junit.template || junitTemplate);
if (options.junit.consolidate) {
var xmlFile = path.join(options.junit.path, 'TEST-' + testsuites.suite1.name.replace(/[^\w]/g, '') + '.xml');
grunt.file.write(xmlFile, grunt.util._.template(template, { testsuites: _.values(testsuites)}));
} else {
2015-04-24 06:36:23 +08:00
_.forEach(testsuites, function(suiteData) {
var xmlFile = path.join(options.junit.path, 'TEST-' + suiteData.name.replace(/[^\w]/g, '') + '.xml');
grunt.file.write(xmlFile, _.template(template, { testsuites: [suiteData] }));
});
}
}
2015-04-24 06:36:23 +08:00
phantomjs.on('jasmine.done', function() {
phantomjs.halt();
});
phantomjs.on('jasmine.done.PhantomReporter', function() {
phantomjs.emit('jasmine.done');
});
phantomjs.on('jasmine.done_fail', function(url) {
grunt.log.error();
grunt.warn('PhantomJS unable to load "' + url + '" URI.', 90);
});
}
};