Skip to content

Commit

Permalink
feat: support jasmine out of the box
Browse files Browse the repository at this point in the history
  • Loading branch information
3cp committed Jun 14, 2019
1 parent d68e596 commit 16e69db
Show file tree
Hide file tree
Showing 6 changed files with 266 additions and 46 deletions.
26 changes: 25 additions & 1 deletion ACKNOWLEDGEMENT.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
This software borrowed code from [karma-chrome-launcher](https://github.com/karma-runner/karma-chrome-launcher), [karma-firefox-launcher](https://github.com/karma-runner/karma-firefox-launcher), [karma-safari-launcher](https://github.com/karma-runner/karma-safari-launcher), [karma-ie-launcher](https://github.com/karma-runner/karma-ie-launcher), [jslegers/karma-edge-launcher](https://github.com/jslegers/karma-edge-launcher), [karma-electron](https://github.com/twolfson/karma-electron), [browser-run](https://github.com/juliangruber/browser-run), [tape-run](https://github.com/juliangruber/tape-run), [browser-launcher](https://github.com/substack/browser-launcher).
This software borrowed code from [karma-chrome-launcher](https://github.com/karma-runner/karma-chrome-launcher), [karma-firefox-launcher](https://github.com/karma-runner/karma-firefox-launcher), [karma-safari-launcher](https://github.com/karma-runner/karma-safari-launcher), [karma-ie-launcher](https://github.com/karma-runner/karma-ie-launcher), [jslegers/karma-edge-launcher](https://github.com/jslegers/karma-edge-launcher), [karma-electron](https://github.com/twolfson/karma-electron), [browser-run](https://github.com/juliangruber/browser-run), [tape-run](https://github.com/juliangruber/tape-run), [browser-launcher](https://github.com/substack/browser-launcher), [jasmine-reporters](https://github.com/larrymyers/jasmine-reporters).

Below are required notices from them.

Expand Down Expand Up @@ -82,3 +82,27 @@ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

====

The MIT License

Copyright (c) 2010 Larry Myers

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
43 changes: 9 additions & 34 deletions bin/browser-do.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

const run = require('../index');
const optimist = require('optimist');
const TapParser = require('tap-parser');
const through = require('through');
const {Writable} = require('stream');
const tapFinished = require('../lib/tap-finished');

const argv = optimist
.usage(
Expand All @@ -29,9 +29,14 @@ const argv = optimist
.describe('mock', 'Path to code to handle requests for mocking a dynamic back-end')
.alias('m', 'mock')

.describe('keep-open', 'Leave the browser open for debugging after running tests. This is only needed for dealing with TAP test result.')
.describe('tap', 'Treat output as TAP test result, automatically exit when TAP finishes')
.alias('t', 'tap')

.describe('jasmine', 'Support jasmine test, convert jasmine output into TAP result, implicitly turns on option "tap", automatically exit when TAP finishes')
.alias('j', 'jasmine')

.describe('keep-open', 'Only for --tap and --jasmine, leave the browser open for debugging after running tests')
.alias('k', 'keep-open')
.alias('keepOpen', 'keep-open')

.describe('help', 'Print help')
.alias('h', 'help')
Expand Down Expand Up @@ -59,39 +64,9 @@ readInput.on('finish', () => {

const browserDo = run(argv, input, holdOutput);

const parser = new TapParser(results => {
if (!argv.keepOpen) {
process.exit(results.ok ? 0 : 1);
}
});

parser.on('bailout', m => {
console.error(m); // eslint-disable-line no-console
process.exit(1);
});

let count, done = 0;
parser.on('plan', p => {
count = p.end - p.start + 1;
check();
});

parser.on('assert', () => {
done++;
check();
});

let finished = false;
function check() {
if (finished) return;
if (!count || done < count) return;
finished = true;
setTimeout(() => parser.end(), 1000);
}

// note output stream is piped to two different destinations.
// 1. tap-parser to deal with tap results
holdOutput.pipe(parser);
if (argv.tap || argv.jasmine) holdOutput.pipe(tapFinished(argv['keep-open']));
// 2. to stdout
holdOutput.pipe(process.stdout);

Expand Down
67 changes: 56 additions & 11 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const kebabCase = require('lodash.kebabcase');
const getBrowser = require('./lib/get-browser');

const reporterPath = path.join(__dirname, 'dist', 'reporter.js');
const jasmineTapReporterPath = path.join(__dirname, 'jasmine-tap-reporter.js');
try {
fs.statSync(reporterPath);
} catch (_) {
Expand All @@ -34,6 +35,16 @@ function runner (opts, data, output) {

const isHtmlData = data.match(/^\s*</);

let jasminePath;
if (!isHtmlData && opts.jasmine) {
try {
jasminePath = path.dirname(require.resolve('jasmine-core/lib/jasmine-core/jasmine.js'));
} catch (e) {
console.error('To use -j/--jasmine, you need "npm i -D jasmine-core"');
process.exit(1);
}
}

var mockHandler = opts.mock && require(path.resolve('./', opts.mock));

var server = http.createServer(function (req, res) {
Expand All @@ -52,17 +63,19 @@ function runner (opts, data, output) {
}

if (req.url == '/') {
res.write(`<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script src="/reporter.js"></script>
<script src="/bundle.js"></script>
</body>
</html>`);
res.end();
res.write('<!DOCTYPE html><html><head><meta charset="utf-8">');
res.write('<script src="/reporter.js"></script>');

if (opts.jasmine) {
res.write('<link rel="stylesheet" href="/jasmine-core/jasmine.css">');
res.write('<script src="/jasmine-core/jasmine.js"></script>');
res.write('<script src="/jasmine-core/jasmine-html.js"></script>');
res.write('<script src="/jasmine-core/boot.js"></script>');
res.write('<script src="/jasmine-tap-reporter.js"></script>');
}

res.write('<script src="/bundle.js"></script>');
res.end('</head><body></body></html>');
return;
}
}
Expand All @@ -80,6 +93,38 @@ function runner (opts, data, output) {
return;
}

if (req.url == '/jasmine-tap-reporter.js') {
res.setHeader('content-type', 'application/javascript');
fs.createReadStream(jasmineTapReporterPath).pipe(res);
return;
}

const m = req.url.match(/^\/jasmine-core\/(.+)/);

if (m) {
const fn = m[1];
if (path.extname(fn) === '.js') {
res.setHeader('content-type', 'application/javascript');
} else if (path.extname(fn) === '.css') {
res.setHeader('content-type', 'text/css');
}

fs.createReadStream(path.join(jasminePath, fn)).pipe(res);
return;
}

if (req.url == '/jasmine-core/jasmine-html.js') {
res.setHeader('content-type', 'application/javascript');
fs.createReadStream(jasmineHtmlPath).pipe(res);
return;
}

if (req.url == '/jasmine-core/boot.js') {
res.setHeader('content-type', 'application/javascript');
fs.createReadStream(jasmineBootPath).pipe(res);
return;
}

if (opts.static) {
serveStatic(opts.static)(req, res, finalhandler(req, res));
return;
Expand Down
141 changes: 141 additions & 0 deletions jasmine-tap-reporter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
// https://github.com/larrymyers/jasmine-reporters/blob/master/src/tap_reporter.js
(function(global) {
function trim(str) { return str.replace(/^\s+/, "").replace(/\s+$/, ""); }
function elapsed(start, end) { return (end - start)/1000; }
function isFailed(obj) { return obj.status === "failed"; }
function isSkipped(obj) { return obj.status === "pending"; }
function isDisabled(obj) { return obj.status === "disabled"; }
function extend(dupe, obj) { // performs a shallow copy of all props of `obj` onto `dupe`
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
dupe[prop] = obj[prop];
}
}
return dupe;
}
function log(str) {
var con = global.console || console;
if (con && con.log) {
con.log(str);
}
}

/**
* TAP (http://en.wikipedia.org/wiki/Test_Anything_Protocol) reporter.
* outputs spec results to the console.
*/
var TapReporter = function() {
var self = this;
self.started = false;
self.finished = false;

var startTime,
endTime,
currentSuite = null,
totalSpecsExecuted = 0,
totalSpecsSkipped = 0,
totalSpecsDisabled = 0,
totalSpecsFailed = 0,
totalSpecsDefined,
// when use use fit, jasmine never calls suiteStarted / suiteDone, so make a fake one to use
fakeFocusedSuite = {
id: "focused",
description: "focused specs",
fullName: "focused specs"
};

var __suites = {}, __specs = {};
function getSuite(suite) {
__suites[suite.id] = extend(__suites[suite.id] || {}, suite);
return __suites[suite.id];
}
function getSpec(spec, suite) {
__specs[spec.id] = extend(__specs[spec.id] || {}, spec);
var ret = __specs[spec.id];
if (suite && !ret._suite) {
ret._suite = suite;
}
return ret;
}

self.jasmineStarted = function(summary) {
log("TAP version 13");
self.started = true;
totalSpecsDefined = summary && summary.totalSpecsDefined || NaN;
startTime = new Date();
};
self.suiteStarted = function(suite) {
suite = getSuite(suite);
currentSuite = suite;
};
self.specStarted = function() {
if (!currentSuite) {
// focused spec (fit) -- suiteStarted was never called
self.suiteStarted(fakeFocusedSuite);
}
totalSpecsExecuted++;
};
self.specDone = function(spec) {
spec = getSpec(spec, currentSuite);
var resultStr = "ok " + totalSpecsExecuted + " - " + spec._suite.description + " : " + spec.description;
if (isFailed(spec)) {
totalSpecsFailed++;
resultStr = "not " + resultStr;
for (var i = 0, failure; i < spec.failedExpectations.length; i++) {
failure = spec.failedExpectations[i];
resultStr += "\n # Failure: " + trim(failure.message);
if (failure.stack && failure.stack !== failure.message) {
resultStr += "\n # === STACK TRACE ===";
resultStr += "\n # " + failure.stack.replace(/\n/mg, "\n # ");
resultStr += "\n # === END STACK TRACE ===";
}
}
}
if (isSkipped(spec)) {
totalSpecsSkipped++;
resultStr += " # SKIP disabled by xit or similar";
}
if (isDisabled(spec)) {
totalSpecsDisabled++;
resultStr += " # SKIP disabled by xit, ?spec=xyz or similar";
}
log(resultStr);
};
self.suiteDone = function(suite) {
suite = getSuite(suite);
if (suite._parent === undefined) {
// disabled suite (xdescribe) -- suiteStarted was never called
self.suiteStarted(suite);
}
currentSuite = suite._parent;
};
self.jasmineDone = function() {
if (currentSuite) {
// focused spec (fit) -- suiteDone was never called
self.suiteDone(fakeFocusedSuite);
}
endTime = new Date();
var dur = elapsed(startTime, endTime),
totalSpecs = totalSpecsDefined || totalSpecsExecuted,
disabledSpecs = totalSpecs - totalSpecsExecuted + totalSpecsDisabled;

if (totalSpecsExecuted === 0) {
log("1..0 # All tests disabled");
} else {
log("1.." + totalSpecsExecuted);
}
var diagStr = "#";
diagStr = "# " + totalSpecs + " spec" + (totalSpecs === 1 ? "" : "s");
diagStr += ", " + totalSpecsFailed + " failure" + (totalSpecsFailed === 1 ? "" : "s");
diagStr += ", " + totalSpecsSkipped + " skipped";
diagStr += ", " + disabledSpecs + " disabled";
diagStr += " in " + dur + "s.";
log(diagStr);
log("# NOTE: disabled specs are usually a result of xdescribe.");

self.finished = true;
};
};

global.jasmine.getEnv().addReporter(new TapReporter());
})(this);
34 changes: 34 additions & 0 deletions lib/tap-finished.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const TapParser = require('tap-parser');

module.exports = function(keepOpen) {
const parser = new TapParser(results => {
if (keepOpen) return;
process.exit(results.ok ? 0 : 1);
});

parser.on('bailout', m => {
console.error(m); // eslint-disable-line no-console
process.exit(1);
});

let count, done = 0;
parser.on('plan', p => {
count = p.end - p.start + 1;
check();
});

parser.on('assert', () => {
done++;
check();
});

let finished = false;
function check() {
if (finished) return;
if (!count || done < count) return;
finished = true;
setTimeout(() => parser.end(), 1000);
}

return parser;
};
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
"ava": "^2.0.0",
"browserify": "^16.2.3",
"eslint": "^5.16.0",
"jasmine-core": "^3.4.0",
"source-map-support": "^0.5.12",
"standard-changelog": "^2.0.11",
"utf8-stream": "0.0.0"
Expand Down

0 comments on commit 16e69db

Please sign in to comment.