Rewrite Spec & allow Jasmine to be namespaced

- THere seems to be a performance regression. Large test suites may
  throw
- Regressions: Mock Clock won't install correctly, async specs are
  temporarily not supported.
- Async spec runs/waits interface is gone. Blocks are gone.
- Move most global usage into jasmine.Env constructor.
- Remove optional 'Jasmine running' from HtmlReporter -- caused
  NS_FACTORY_ERROR in firefox when tested
This commit is contained in:
Davis W. Frank & Rajan Agaskar
2012-12-05 09:37:05 -08:00
parent 779dee1211
commit a1011e7748
44 changed files with 1343 additions and 2586 deletions

View File

@@ -1,7 +1,7 @@
source :rubygems
gem "rake"
#gem "jasmine", git: 'https://github.com/pivotal/jasmine-gem.git'
gem "jasmine", path: '~/workspace/jasmine-gem'
gem "jasmine", :git => 'https://github.com/pivotal/jasmine-gem.git', :branch => '2_0'
# gem "jasmine", path: '~/workspace/jasmine-gem'
unless ENV["TRAVIS"]
group :debug do

View File

@@ -27,25 +27,19 @@
},
expect: function(actual) {
return env.currentSpec.expect(actual);
return env.expect(actual);
},
runs: function(func) {
return env.currentSpec.runs(func);
},
waits: function(timeout) {
return env.currentSpec.waits(timeout);
},
waitsFor: function(latchFunction, optional_timeoutMessage, optional_timeout) {
return env.currentSpec.waitsFor.apply(jasmine.getEnv().currentSpec, arguments);
addMatchers: function(matchers) {
return env.addMatchers(matchers);
},
spyOn: function(obj, methodName) {
return env.currentSpec.spyOn(obj, methodName);
return env.spyOn(obj, methodName);
},
jsApiReporter: new jasmine.JsApiReporter()
jsApiReporter: new jasmine.JsApiReporter(jasmine)
};
if (typeof window == "undefined" && typeof exports == "object") {
@@ -54,7 +48,7 @@
jasmine.util.extend(window, jasmineInterface);
}
var htmlReporter = new jasmine.HtmlReporter();
var htmlReporter = new jasmine.HtmlReporter(null, jasmine);
env.addReporter(jasmineInterface.jsApiReporter);
env.addReporter(htmlReporter);

View File

@@ -46,7 +46,7 @@ jasmine.HtmlReporterHelpers.appendToSummary = function(child, childElement) {
if (parent) {
if (typeof this.views.suites[parent.id] == 'undefined') {
this.views.suites[parent.id] = new jasmine.HtmlReporter.SuiteView(parent, this.dom, this.views);
this.views.suites[parent.id] = new this.jasmine.HtmlReporter.SuiteView(parent, this.dom, this.views, this.jasmine);
}
parentDiv = this.views.suites[parent.id].element;
}
@@ -56,13 +56,15 @@ jasmine.HtmlReporterHelpers.appendToSummary = function(child, childElement) {
jasmine.HtmlReporterHelpers.addHelpers = function(ctor) {
//TODO: not really a helper, thus, no this.jasmine
for(var fn in jasmine.HtmlReporterHelpers) {
ctor.prototype[fn] = jasmine.HtmlReporterHelpers[fn];
}
};
jasmine.HtmlReporter = function(_doc) {
jasmine.HtmlReporter = function(_doc, jasmine) {
var self = this;
this.jasmine = jasmine || window.jasmine;
var doc = _doc || window.document;
var reporterView;
@@ -70,7 +72,6 @@ jasmine.HtmlReporter = function(_doc) {
var dom = {};
// Jasmine Reporter Public Interface
self.logRunningSpecs = false;
self.reportRunnerStarting = function(runner) {
var specs = runner.specs() || [];
@@ -83,7 +84,7 @@ jasmine.HtmlReporter = function(_doc) {
doc.body.appendChild(dom.reporter);
setExceptionHandling();
reporterView = new jasmine.HtmlReporter.ReporterView(dom);
reporterView = new self.jasmine.HtmlReporter.ReporterView(dom, self.jasmine);
reporterView.addSpecs(specs, self.specFilter);
};
@@ -96,17 +97,14 @@ jasmine.HtmlReporter = function(_doc) {
};
self.reportSpecStarting = function(spec) {
if (self.logRunningSpecs) {
self.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...');
}
};
self.reportSpecResults = function(spec) {
reporterView.specComplete(spec);
self.reportSpecResults = function(result) {
reporterView.specComplete(result);
};
self.log = function() {
var console = jasmine.getGlobal().console;
var console = self.jasmine.getGlobal().console;
if (console && console.log) {
if (console.log.apply) {
console.log.apply(console, arguments);
@@ -135,7 +133,7 @@ jasmine.HtmlReporter = function(_doc) {
}
var paramMap = [];
var params = jasmine.HtmlReporter.parameters(doc);
var params = self.jasmine.HtmlReporter.parameters(doc);
for (var i = 0; i < params.length; i++) {
var p = params[i].split('=');
@@ -181,7 +179,7 @@ jasmine.HtmlReporter = function(_doc) {
}
i++;
}
if (jasmine.CATCH_EXCEPTIONS) {
if (self.jasmine.CATCH_EXCEPTIONS) {
params.push("catch=false");
}
@@ -193,7 +191,7 @@ jasmine.HtmlReporter = function(_doc) {
if (noTryCatch()) {
chxCatch.setAttribute('checked', true);
jasmine.CATCH_EXCEPTIONS = false;
self.jasmine.CATCH_EXCEPTIONS = false;
}
chxCatch.onclick = function() {
window.location.search = searchWithCatch();
@@ -209,14 +207,14 @@ jasmine.HtmlReporter.parameters = function(doc) {
}
return params;
}
jasmine.HtmlReporter.sectionLink = function(sectionName) {
jasmine.HtmlReporter.sectionLink = function(sectionName, catchExceptions) {
var link = '?';
var params = [];
if (sectionName) {
params.push('spec=' + encodeURIComponent(sectionName));
}
if (!jasmine.CATCH_EXCEPTIONS) {
if (!catchExceptions) {
params.push("catch=false");
}
if (params.length > 0) {
@@ -226,13 +224,14 @@ jasmine.HtmlReporter.sectionLink = function(sectionName) {
return link;
};
jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter);
jasmine.HtmlReporter.ReporterView = function(dom) {
jasmine.HtmlReporter.ReporterView = function(dom, jasmine) {
this.startedAt = new Date();
this.runningSpecCount = 0;
this.completeSpecCount = 0;
this.passedCount = 0;
this.failedCount = 0;
this.skippedCount = 0;
this.jasmine = jasmine || {};
this.createResultsMenu = function() {
this.resultsMenu = this.createDom('span', {className: 'resultsMenu bar'},
@@ -259,21 +258,21 @@ jasmine.HtmlReporter.ReporterView = function(dom) {
for (var i = 0; i < specs.length; i++) {
var spec = specs[i];
this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom, this.views);
this.views.specs[spec.id] = new this.jasmine.HtmlReporter.SpecView(spec, dom, this.views, this.jasmine);
if (specFilter(spec)) {
this.runningSpecCount++;
}
}
};
this.specComplete = function(spec) {
this.specComplete = function(result) {
this.completeSpecCount++;
if (isUndefined(this.views.specs[spec.id])) {
this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom);
}
// if (isUndefined(this.views.specs[result.id])) {
// this.views.specs[result.id] = new this.jasmine.HtmlReporter.SpecView(result, dom);
// }
var specView = this.views.specs[spec.id];
var specView = this.views.specs[result.id];
switch (specView.status()) {
case 'passed':
@@ -284,7 +283,7 @@ jasmine.HtmlReporter.ReporterView = function(dom) {
this.failedCount++;
break;
case 'skipped':
case 'disabled':
this.skippedCount++;
break;
}
@@ -309,14 +308,14 @@ jasmine.HtmlReporter.ReporterView = function(dom) {
// currently running UI
if (isUndefined(this.runningAlert)) {
this.runningAlert = this.createDom('a', { href: jasmine.HtmlReporter.sectionLink(), className: "runningAlert bar" });
this.runningAlert = this.createDom('a', { href: this.jasmine.HtmlReporter.sectionLink(null, this.jasmine.CATCH_EXCEPTIONS), className: "runningAlert bar" });
dom.alert.appendChild(this.runningAlert);
}
this.runningAlert.innerHTML = "Running " + this.completeSpecCount + " of " + specPluralizedFor(this.totalSpecCount);
// skipped specs UI
if (isUndefined(this.skippedAlert)) {
this.skippedAlert = this.createDom('a', { href: jasmine.HtmlReporter.sectionLink(), className: "skippedAlert bar" });
this.skippedAlert = this.createDom('a', { href: this.jasmine.HtmlReporter.sectionLink(null, this.jasmine.CATCH_EXCEPTIONS), className: "skippedAlert bar" });
}
this.skippedAlert.innerHTML = "Skipping " + this.skippedCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all";
@@ -327,7 +326,7 @@ jasmine.HtmlReporter.ReporterView = function(dom) {
// passing specs UI
if (isUndefined(this.passedAlert)) {
this.passedAlert = this.createDom('span', { href: jasmine.HtmlReporter.sectionLink(), className: "passingAlert bar" });
this.passedAlert = this.createDom('span', { href: this.jasmine.HtmlReporter.sectionLink(null, this.jasmine.CATCH_EXCEPTIONS), className: "passingAlert bar" });
}
this.passedAlert.innerHTML = "Passing " + specPluralizedFor(this.passedCount);
@@ -390,10 +389,11 @@ jasmine.HtmlReporter.ReporterView = function(dom) {
jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.ReporterView);
jasmine.HtmlReporter.SpecView = function(spec, dom, views) {
jasmine.HtmlReporter.SpecView = function(spec, dom, views, jasmine) {
this.spec = spec;
this.dom = dom;
this.views = views;
this.jasmine = jasmine || {};
this.symbol = this.createDom('li', { className: 'pending' });
this.dom.symbolSummary.appendChild(this.symbol);
@@ -401,7 +401,7 @@ jasmine.HtmlReporter.SpecView = function(spec, dom, views) {
this.summary = this.createDom('div', { className: 'specSummary' },
this.createDom('a', {
className: 'description',
href: jasmine.HtmlReporter.sectionLink(this.spec.getFullName()),
href: this.jasmine.HtmlReporter.sectionLink(this.spec.getFullName(), this.jasmine.CATCH_EXCEPTIONS),
title: this.spec.getFullName()
}, this.spec.description)
);
@@ -416,16 +416,15 @@ jasmine.HtmlReporter.SpecView = function(spec, dom, views) {
};
jasmine.HtmlReporter.SpecView.prototype.status = function() {
return this.getSpecStatus(this.spec);
return this.spec.status();
};
jasmine.HtmlReporter.SpecView.prototype.refresh = function() {
this.symbol.className = this.status();
switch (this.status()) {
case 'skipped':
case 'disabled':
break;
case 'passed':
this.appendSummaryToSuiteDiv();
break;
@@ -445,7 +444,7 @@ jasmine.HtmlReporter.SpecView.prototype.appendSummaryToSuiteDiv = function() {
jasmine.HtmlReporter.SpecView.prototype.appendFailureDetail = function() {
this.detail.className += ' ' + this.status();
var resultItems = this.spec.results().getItems();
var resultItems = this.spec.failedExpectations;
var messagesDiv = this.createDom('div', { className: 'messages' });
for (var i = 0; i < resultItems.length; i++) {
@@ -469,13 +468,14 @@ jasmine.HtmlReporter.SpecView.prototype.appendFailureDetail = function() {
};
jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SpecView);
jasmine.HtmlReporter.SuiteView = function(suite, dom, views) {
jasmine.HtmlReporter.SuiteView = function(suite, dom, views, jasmine) {
this.suite = suite;
this.dom = dom;
this.views = views;
this.jasmine = jasmine || {};
this.element = this.createDom('div', { className: 'suite' },
this.createDom('a', { className: 'description', href: jasmine.HtmlReporter.sectionLink(this.suite.getFullName()) }, this.suite.description)
this.createDom('a', { className: 'description', href: this.jasmine.HtmlReporter.sectionLink(this.suite.getFullName(), this.jasmine.CATCH_EXCEPTIONS) }, this.suite.description)
);
this.appendToSummary(this.suite, this.element);

View File

@@ -5,6 +5,9 @@
* @namespace
*/
var jasmine = {};
if (typeof window == "undefined" && typeof exports == "object") {
exports.jasmine = jasmine
}
/**
* @private
@@ -431,16 +434,6 @@ jasmine.createSpyObj = function(baseName, methodNames) {
}
return obj;
};
/**
* All parameters are pretty-printed and concatenated together, then written to the current spec's output.
*
* Be careful not to leave calls to <code>jasmine.log</code> in production code.
*/
jasmine.log = function() {
var spec = jasmine.getEnv().currentSpec;
spec.log.apply(spec, arguments);
};
/**
* @namespace
*/
@@ -526,15 +519,18 @@ jasmine.buildExpectationResult = function(params) {
* @constructor
*/
(function() {
function createSpec(env, suite, description) {
return new jasmine.Spec(env, suite, description);
}
jasmine.Env = function() {
var self = this;
var suiteConstructor = jasmine.Suite;
var isSuite = function(thing) {
return thing instanceof suiteConstructor;
}
this.jasmine = jasmine;
this.currentRunner_ = new jasmine.Runner(this, isSuite);
this.spies_ = [];
this.currentSpec = null;
this.currentSuite = null;
this.currentRunner_ = new jasmine.Runner(this);
this.catchExceptions = jasmine.CATCH_EXCEPTIONS;
this.undefined = jasmine.undefined;
this.reporter = new jasmine.MultiReporter();
@@ -556,6 +552,90 @@ jasmine.buildExpectationResult = function(params) {
jasmine.util.inherit(this.matchersClass, jasmine.Matchers);
jasmine.Matchers.wrapInto_(jasmine.Matchers.prototype, this.matchersClass);
var expectationFactory = function(actual, spec) {
var expect = new (self.matchersClass)(self, actual, spec);
expect.not = new (self.matchersClass)(self, actual, spec, true);
return expect;
};
var startCallback = function(spec) {
self.currentSpec = spec;
self.reporter.reportSpecStarting(spec);
};
var beforeFns = function(currentSuite) {
return function() {
var befores = [];
for (var suite = currentSuite; suite; suite = suite.parentSuite) {
befores = befores.concat(suite.before_)
}
return befores.concat(self.currentRunner_.before_).reverse();
}
};
var afterFns = function(currentSuite) {
return function() {
var afters = [];
for (var suite = currentSuite; suite; suite = suite.parentSuite) {
afters = afters.concat(suite.after_)
}
return afters.concat(self.currentRunner_.after_)
}
};
var exceptionFormatter = jasmine.util.formatException;
var specConstructor = jasmine.Spec;
// TODO: this deserves a better name (not a Factory the way others are)
var fullNameFactory = function(spec, currentSuite) {
var descriptions = [];
for (var suite = currentSuite; suite; suite = suite.parentSuite) {
descriptions.push(suite.description)
}
descriptions.push(spec.description);
return descriptions.join(' ') + '.';
};
var buildExpectationResult = jasmine.buildExpectationResult;
var expectationResultFactory = function(attrs) {
return buildExpectationResult(attrs);
};
this.specFactory = function(description, fn, suite) {
var spec = new specConstructor({
id: self.nextSpecId(),
beforeFns: beforeFns(suite),
afterFns: afterFns(suite),
expectationFactory: expectationFactory,
exceptionFormatter: exceptionFormatter,
//TODO: move spec creation to more appropriate level and remove this shim
resultCallback: function(result) { self.currentSpec = null; suite.specComplete(result); },
fullNameFactory: function(spec) { return fullNameFactory(spec, suite) },
startCallback: startCallback,
description: description,
catchExceptions: self.catchExceptions,
expectationResultFactory: expectationResultFactory,
fn: fn
});
if (!self.specFilter(spec)) {
spec.disable();
}
return spec;
};
var queueConstructor = jasmine.Queue;
var queueFactory = function() {
return new queueConstructor(self);
};
this.suiteFactory = function(description, specDefinitions) {
return new suiteConstructor(self, description, specDefinitions, self.currentSuite, queueFactory, isSuite);
};
};
@@ -564,22 +644,69 @@ jasmine.buildExpectationResult = function(params) {
jasmine.Env.prototype.setInterval = jasmine.setInterval;
jasmine.Env.prototype.clearInterval = jasmine.clearInterval;
//TODO: shim Spec addMatchers behavior into Env. Should be rewritten to remove globals, etc.
jasmine.Env.prototype.addMatchers = function(matchersPrototype) {
var parent = this.matchersClass;
var newMatchersClass = function() {
parent.apply(this, arguments);
};
jasmine.util.inherit(newMatchersClass, parent);
jasmine.Matchers.wrapInto_(matchersPrototype, newMatchersClass);
this.matchersClass = newMatchersClass;
};
/**
* @returns an object containing jasmine version build info, if set.
*/
jasmine.Env.prototype.version = function () {
if (jasmine.version_) {
return jasmine.version_;
if (this.jasmine.version_) {
return this.jasmine.version_;
} else {
throw new Error('Version not set');
}
};
jasmine.Env.prototype.expect = function(actual) {
return this.currentSpec.expect(actual);
};
jasmine.Env.prototype.spyOn = function(obj, methodName) {
if (obj == this.undefined) {
throw "spyOn could not find an object to spy upon for " + methodName + "()";
}
if (obj[methodName] === this.undefined) {
throw methodName + '() method does not exist';
}
if (obj[methodName] && obj[methodName].isSpy) {
//TODO?: should this return the current spy? Downside: may cause user confusion about spy state
throw new Error(methodName + ' has already been spied upon');
}
var spyObj = jasmine.createSpy(methodName);
this.spies_.push(spyObj);
spyObj.baseObj = obj;
spyObj.methodName = methodName;
spyObj.originalValue = obj[methodName];
obj[methodName] = spyObj;
return spyObj;
};
jasmine.Env.prototype.removeAllSpies = function() {
for (var i = 0; i < this.spies_.length; i++) {
var spy = this.spies_[i];
spy.baseObj[spy.methodName] = spy.originalValue;
}
this.spies_ = [];
};
/**
* @returns string containing jasmine version build info, if set.
*/
jasmine.Env.prototype.versionString = function() {
if (!jasmine.version_) {
if (!this.jasmine.version_) {
return "version unknown";
}
@@ -619,13 +746,13 @@ jasmine.buildExpectationResult = function(params) {
};
jasmine.Env.prototype.describe = function(description, specDefinitions) {
var suite = new jasmine.Suite(this, description, specDefinitions, this.currentSuite);
var suite = this.suiteFactory(description, specDefinitions);
var parentSuite = this.currentSuite;
if (parentSuite) {
parentSuite.add(suite);
} else {
this.currentRunner_.add(suite);
this.currentRunner_.addSuite(suite);
}
this.currentSuite = suite;
@@ -676,15 +803,9 @@ jasmine.buildExpectationResult = function(params) {
};
};
jasmine.Env.prototype.it = function(description, func) {
var spec = createSpec(this, this.currentSuite, description);
jasmine.Env.prototype.it = function(description, fn) {
var spec = this.specFactory(description, fn, this.currentSuite);
this.currentSuite.add(spec);
this.currentSpec = spec;
if (func) {
spec.runs(func);
}
return spec;
};
@@ -724,7 +845,7 @@ jasmine.buildExpectationResult = function(params) {
b.__Jasmine_been_here_before__ = a;
var hasKey = function(obj, keyName) {
return obj !== null && obj[keyName] !== jasmine.undefined;
return obj !== null && obj[keyName] !== this.undefined;
};
for (var property in b) {
@@ -760,13 +881,13 @@ jasmine.buildExpectationResult = function(params) {
for (var i = 0; i < this.equalityTesters_.length; i++) {
var equalityTester = this.equalityTesters_[i];
var result = equalityTester(a, b, this, mismatchKeys, mismatchValues);
if (result !== jasmine.undefined) return result;
if (result !== this.undefined) return result;
}
if (a === b) return true;
if (a === jasmine.undefined || a === null || b === jasmine.undefined || b === null) {
return (a == jasmine.undefined && b == jasmine.undefined);
if (a === this.undefined || a === null || b === this.undefined || b === null) {
return (a == this.undefined && b == this.undefined);
}
if (jasmine.isDomNode(a) && jasmine.isDomNode(b)) {
@@ -858,38 +979,12 @@ jasmine.Reporter.prototype.reportSpecResults = function(spec) {
jasmine.Reporter.prototype.log = function(str) {
};
/**
* Blocks are functions with executable code that make up a spec.
*
* @constructor
* @param {jasmine.Env} env
* @param {Function} func
* @param {jasmine.Spec} spec
*/
jasmine.Block = function(env, func, spec) {
this.env = env;
this.func = func;
this.spec = spec;
};
jasmine.Block.prototype.execute = function(onComplete) {
if (!jasmine.CATCH_EXCEPTIONS) {
this.func.apply(this.spec);
}
else {
try {
this.func.apply(this.spec);
} catch (e) {
this.spec.fail(e);
}
}
onComplete();
};
/** JavaScript API reporter.
*
* @constructor
*/
jasmine.JsApiReporter = function() {
jasmine.JsApiReporter = function(jasmine) {
this.jasmine = jasmine || {};
this.started = false;
this.finished = false;
this.suites_ = [];
@@ -910,7 +1005,7 @@ jasmine.JsApiReporter.prototype.suites = function() {
};
jasmine.JsApiReporter.prototype.summarize_ = function(suiteOrSpec) {
var isSuite = suiteOrSpec instanceof jasmine.Suite;
var isSuite = suiteOrSpec instanceof this.jasmine.Suite;
var summary = {
id: suiteOrSpec.id,
name: suiteOrSpec.description,
@@ -931,10 +1026,6 @@ jasmine.JsApiReporter.prototype.results = function() {
return this.results_;
};
jasmine.JsApiReporter.prototype.resultsForSpec = function(specId) {
return this.results_[specId];
};
//noinspection JSUnusedLocalSymbols
jasmine.JsApiReporter.prototype.reportRunnerResults = function(runner) {
this.finished = true;
@@ -945,10 +1036,11 @@ jasmine.JsApiReporter.prototype.reportSuiteResults = function(suite) {
};
//noinspection JSUnusedLocalSymbols
jasmine.JsApiReporter.prototype.reportSpecResults = function(spec) {
this.results_[spec.id] = {
messages: spec.results().getItems(),
result: spec.results().failedCount > 0 ? "failed" : "passed"
jasmine.JsApiReporter.prototype.reportSpecResults = function(result) {
this.results_[result.id] = {
messages: result.failedExpectations,
//result is status
result: result.status
};
};
@@ -956,6 +1048,7 @@ jasmine.JsApiReporter.prototype.reportSpecResults = function(spec) {
jasmine.JsApiReporter.prototype.log = function(str) {
};
//TODO: make work with new presenter.
jasmine.JsApiReporter.prototype.resultsForSpecs = function(specIds){
var results = {};
for (var i = 0; i < specIds.length; i++) {
@@ -970,14 +1063,16 @@ jasmine.JsApiReporter.prototype.summarizeResult_ = function(result){
var messagesLength = result.messages.length;
for (var messageIndex = 0; messageIndex < messagesLength; messageIndex++) {
var resultMessage = result.messages[messageIndex];
//TODO: use result presenter here, not a bunch of spec crap
summaryMessages.push({
text: resultMessage.type == 'log' ? resultMessage.toString() : jasmine.undefined,
//TODO: remove text.
text: resultMessage.type == 'log' ? resultMessage.toString() : this.jasmine.undefined,
//TODO: wat? in theory this is saying non-expect results should always be considered passed, but that's weird.
passed: resultMessage.passed || true,
passed: resultMessage.passed || true, //status === 'passed'
type: resultMessage.type,
message: resultMessage.message,
trace: {
stack: !resultMessage.passed ? resultMessage.trace.stack : jasmine.undefined
stack: !resultMessage.passed ? resultMessage.trace.stack : this.jasmine.undefined
}
});
}
@@ -995,6 +1090,7 @@ jasmine.JsApiReporter.prototype.summarizeResult_ = function(result){
* @param {jasmine.Spec} spec
*/
jasmine.Matchers = function(env, actual, spec, opt_isNot) {
//TODO: true dependency: equals, contains
this.env = env;
this.actual = actual;
this.spec = spec;
@@ -1006,6 +1102,7 @@ jasmine.Matchers.pp = function(str) {
throw new Error("jasmine.Matchers.pp() is no longer supported, please use jasmine.pp() instead!");
};
jasmine.Matchers.wrapInto_ = function(prototype, matchersClass) {
for (var methodName in prototype) {
var orig = prototype[methodName];
@@ -1048,7 +1145,7 @@ jasmine.Matchers.matcherFn_ = function(matcherName, matcherFunction) {
actual: this.actual,
message: message
});
this.spec.addMatcherResult(expectationResult);
this.spec.addExpectationResult(result, expectationResult);
return jasmine.undefined;
};
};
@@ -1496,6 +1593,7 @@ jasmine.Clock = {
useMock: function() {
if (!jasmine.Clock.isInstalled()) {
//TODO: this is using an interface that doesn't exist.
var spec = jasmine.getEnv().currentSpec;
spec.after(jasmine.Clock.uninstallMock);
@@ -1826,7 +1924,7 @@ jasmine.Queue = function(env) {
};
jasmine.Queue.prototype.addBefore = function(block, ensure) {
if (ensure === jasmine.undefined) {
if (ensure === this.env.undefined) {
ensure = false;
}
@@ -1835,7 +1933,7 @@ jasmine.Queue.prototype.addBefore = function(block, ensure) {
};
jasmine.Queue.prototype.add = function(block, ensure) {
if (ensure === jasmine.undefined) {
if (ensure === this.env.undefined) {
ensure = false;
}
@@ -1844,7 +1942,7 @@ jasmine.Queue.prototype.add = function(block, ensure) {
};
jasmine.Queue.prototype.insertNext = function(block, ensure) {
if (ensure === jasmine.undefined) {
if (ensure === this.env.undefined) {
ensure = false;
}
@@ -1865,50 +1963,55 @@ jasmine.Queue.prototype.isRunning = function() {
jasmine.Queue.LOOP_DONT_RECURSE = true;
jasmine.Queue.prototype.incrementQueue = function() {
if (this.blocks[this.index].abort) {
this.abort = true;
}
this.offset = 0;
this.index++;
this.next_();
}
jasmine.Queue.prototype.next_ = function() {
var self = this;
var goAgain = true;
// var goAgain = true;
while (goAgain) {
goAgain = false;
// while (goAgain) {
// goAgain = false;
if (self.index < self.blocks.length && !(this.abort && !this.ensured[self.index])) {
var calledSynchronously = true;
var completedSynchronously = false;
// var calledSynchronously = true;
// var completedSynchronously = false;
var onComplete = function () {
if (jasmine.Queue.LOOP_DONT_RECURSE && calledSynchronously) {
completedSynchronously = true;
return;
}
// var onComplete = function () {
// if (jasmine.Queue.LOOP_DONT_RECURSE && calledSynchronously) {
// completedSynchronously = true;
// return;
// }
if (self.blocks[self.index].abort) {
self.abort = true;
}
self.blocks[self.index].execute(function() { self.incrementQueue() });
self.offset = 0;
self.index++;
var now = new Date().getTime();
if (self.env.updateInterval && now - self.env.lastUpdate > self.env.updateInterval) {
self.env.lastUpdate = now;
self.env.setTimeout(function() {
self.next_();
}, 0);
} else {
if (jasmine.Queue.LOOP_DONT_RECURSE && completedSynchronously) {
goAgain = true;
} else {
self.next_();
}
}
};
self.blocks[self.index].execute(onComplete);
// var now = new Date().getTime();
// if (self.env.updateInterval && now - self.env.lastUpdate > self.env.updateInterval) {
// self.env.lastUpdate = now;
// self.env.setTimeout(function() {
// self.next_();
// }, 0);
// } else {
// if (jasmine.Queue.LOOP_DONT_RECURSE && completedSynchronously) {
// goAgain = true;
// } else {
// self.next_();
// }
// }
// };
// self.blocks[self.index].execute(function() { self.next_(); });
calledSynchronously = false;
if (completedSynchronously) {
onComplete();
}
// calledSynchronously = false;
// if (completedSynchronously) {
// onComplete();
// }
} else {
self.running = false;
@@ -1916,21 +2019,23 @@ jasmine.Queue.prototype.next_ = function() {
self.onComplete();
}
}
}
// }
};
//TODO: runner is a special case of suite.
/**
* Runner
*
* @constructor
* @param {jasmine.Env} env
*/
jasmine.Runner = function(env) {
jasmine.Runner = function(env, isSuite) {
var self = this;
self.env = env;
self.queue = new jasmine.Queue(env);
self.before_ = [];
self.after_ = [];
self.suites_ = [];
self.isSuite = isSuite || function() {};
};
jasmine.Runner.prototype.execute = function() {
@@ -1960,13 +2065,18 @@ jasmine.Runner.prototype.finishCallback = function() {
jasmine.Runner.prototype.addSuite = function(suite) {
this.suites_.push(suite);
this.queue.add(suite);
};
//TODO: runner should die a slow unhappy death.
//Nobody should ever call instanceof.
jasmine.Runner.prototype.add = function(block) {
if (block instanceof jasmine.Suite) {
if (this.isSuite(block)) {
this.addSuite(block);
} else {
this.queue.add(block);
}
this.queue.add(block);
};
jasmine.Runner.prototype.specs = function () {
@@ -1991,249 +2101,103 @@ jasmine.Runner.prototype.topLevelSuites = function() {
}
return topLevelSuites;
};
/**
* Internal representation of a Jasmine specification, or test.
*
* @constructor
* @param {jasmine.Env} env
* @param {jasmine.Suite} suite
* @param {String} description
*/
jasmine.Spec = function(env, suite, description) {
if (!env) {
throw new Error('jasmine.Env() required');
jasmine.Spec = function(attrs) {
this.failedExpectations = [];
this.encounteredExpectations = false;
this.expectationFactory = attrs.expectationFactory;
this.resultCallback = attrs.resultCallback || function() {};
this.id = attrs.id;
this.description = attrs.description;
this.fn = attrs.fn;
this.beforeFns = attrs.beforeFns || function() {};
this.afterFns = attrs.afterFns || function() {};
this.catchExceptions = attrs.catchExceptions;
this.startCallback = attrs.startCallback || function() {};
this.exceptionFormatter = attrs.exceptionFormatter || function() {};
this.fullNameFactory = attrs.fullNameFactory;
this.expectationResultFactory = attrs.expectationResultFactory || function() {};
};
jasmine.Spec.prototype.addExpectationResult = function(passed, data) {
this.encounteredExpectations = true;
if (!passed) {
this.failedExpectations.push(data);
}
if (!suite) {
throw new Error('jasmine.Suite() required');
}
var spec = this;
spec.id = env.nextSpecId ? env.nextSpecId() : null;
spec.env = env;
spec.suite = suite;
spec.description = description;
spec.queue = new jasmine.Queue(env);
spec.afterCallbacks = [];
spec.spies_ = [];
spec.results_ = new jasmine.NestedResults();
spec.results_.description = description;
spec.matchersClass = null;
};
jasmine.Spec.prototype.getFullName = function() {
return this.suite.getFullName() + ' ' + this.description + '.';
};
jasmine.Spec.prototype.results = function() {
return this.results_;
};
/**
* All parameters are pretty-printed and concatenated together, then written to the spec's output.
*
* Be careful not to leave calls to <code>jasmine.log</code> in production code.
*/
jasmine.Spec.prototype.log = function() {
return this.results_.log(arguments);
};
jasmine.Spec.prototype.runs = function (func) {
var block = new jasmine.Block(this.env, func, this);
this.addToQueue(block);
return this;
};
jasmine.Spec.prototype.addToQueue = function (block) {
if (this.queue.isRunning()) {
this.queue.insertNext(block);
} else {
this.queue.add(block);
}
};
/**
* @param {jasmine.ExpectationResult} result
*/
jasmine.Spec.prototype.addMatcherResult = function(result) {
this.results_.addResult(result);
};
jasmine.Spec.prototype.expect = function(actual) {
var positive = new (this.getMatchersClass_())(this.env, actual, this);
positive.not = new (this.getMatchersClass_())(this.env, actual, this, true);
return positive;
return this.expectationFactory(actual, this);
};
/**
* Waits a fixed time period before moving to the next block.
*
* @deprecated Use waitsFor() instead
* @param {Number} timeout milliseconds to wait
*/
jasmine.Spec.prototype.waits = function(timeout) {
var waitsFunc = new jasmine.WaitsBlock(this.env, timeout, this);
this.addToQueue(waitsFunc);
return this;
};
/**
* Waits for the latchFunction to return true before proceeding to the next block.
*
* @param {Function} latchFunction
* @param {String} optional_timeoutMessage
* @param {Number} optional_timeout
*/
jasmine.Spec.prototype.waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) {
var latchFunction_ = null;
var optional_timeoutMessage_ = null;
var optional_timeout_ = null;
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
switch (typeof arg) {
case 'function':
latchFunction_ = arg;
break;
case 'string':
optional_timeoutMessage_ = arg;
break;
case 'number':
optional_timeout_ = arg;
break;
}
}
var waitsForFunc = new jasmine.WaitsForBlock(this.env, optional_timeout_, latchFunction_, optional_timeoutMessage_, this);
this.addToQueue(waitsForFunc);
return this;
};
jasmine.Spec.prototype.fail = function (e) {
var expectationResult = jasmine.buildExpectationResult({
passed: false,
message: e ? jasmine.util.formatException(e) : 'Exception',
trace: { stack: e.stack }
});
this.results_.addResult(expectationResult);
};
jasmine.Spec.prototype.getMatchersClass_ = function() {
return this.matchersClass || this.env.matchersClass;
};
jasmine.Spec.prototype.addMatchers = function(matchersPrototype) {
var parent = this.getMatchersClass_();
var newMatchersClass = function() {
parent.apply(this, arguments);
};
jasmine.util.inherit(newMatchersClass, parent);
jasmine.Matchers.wrapInto_(matchersPrototype, newMatchersClass);
this.matchersClass = newMatchersClass;
};
jasmine.Spec.prototype.finishCallback = function() {
this.env.reporter.reportSpecResults(this);
};
jasmine.Spec.prototype.finish = function(onComplete) {
this.removeAllSpies();
this.finishCallback();
if (onComplete) {
onComplete();
}
};
jasmine.Spec.prototype.after = function(doAfter) {
if (this.queue.isRunning()) {
this.queue.add(new jasmine.Block(this.env, doAfter, this), true);
} else {
this.afterCallbacks.unshift(doAfter);
}
};
jasmine.Spec.prototype.execute = function(onComplete) {
var spec = this;
if (!spec.env.specFilter(spec)) {
spec.results_.skipped = true;
spec.finish(onComplete);
jasmine.Spec.prototype.execute = function() {
if (this.disabled) {
resultCallback.call(this);
return;
}
this.env.reporter.reportSpecStarting(this);
spec.env.currentSpec = spec;
spec.addBeforesAndAftersToQueue();
spec.queue.start(function () {
spec.finish(onComplete);
});
};
jasmine.Spec.prototype.addBeforesAndAftersToQueue = function() {
var runner = this.env.currentRunner();
var i;
for (var suite = this.suite; suite; suite = suite.parentSuite) {
for (i = 0; i < suite.before_.length; i++) {
this.queue.addBefore(new jasmine.Block(this.env, suite.before_[i], this));
var befores = this.beforeFns() || [],
afters = this.afterFns() || [];
this.startCallback(this);
try {
for (var i = 0; i < befores.length; i++) {
befores[i].call(this);
}
this.fn.call(this);
for (i = 0; i < afters.length; i++) {
afters[i].call(this);
}
} catch (e) {
//TODO: weird. buildExpectationResult is really a presenter for expectations
//so this should take an expectation object.
this.addExpectationResult(false, this.expectationResultFactory({
matcherName: "",
passed: false,
expected: "",
actual: "",
message: this.exceptionFormatter(e),
trace: e
}));
if (!this.catchExceptions) {
throw e;
}
}
for (i = 0; i < runner.before_.length; i++) {
this.queue.addBefore(new jasmine.Block(this.env, runner.before_[i], this));
finally {
resultCallback.call(this);
}
for (i = 0; i < this.afterCallbacks.length; i++) {
this.queue.add(new jasmine.Block(this.env, this.afterCallbacks[i], this), true);
}
for (suite = this.suite; suite; suite = suite.parentSuite) {
for (i = 0; i < suite.after_.length; i++) {
this.queue.add(new jasmine.Block(this.env, suite.after_[i], this), true);
}
}
for (i = 0; i < runner.after_.length; i++) {
this.queue.add(new jasmine.Block(this.env, runner.after_[i], this), true);
function resultCallback() {
this.resultCallback({
id: this.id,
status: this.status(),
description: this.description,
failedExpectations: this.failedExpectations
});
}
};
jasmine.Spec.prototype.explodes = function() {
throw 'explodes function should not have been called';
jasmine.Spec.prototype.disable = function() {
this.disabled = true;
};
jasmine.Spec.prototype.spyOn = function(obj, methodName, ignoreMethodDoesntExist) {
if (obj == jasmine.undefined) {
throw "spyOn could not find an object to spy upon for " + methodName + "()";
jasmine.Spec.prototype.status = function() {
if (this.disabled) {
return 'disabled';
}
if (!ignoreMethodDoesntExist && obj[methodName] === jasmine.undefined) {
throw methodName + '() method does not exist';
if (!this.encounteredExpectations) {
return null;
}
if (!ignoreMethodDoesntExist && obj[methodName] && obj[methodName].isSpy) {
throw new Error(methodName + ' has already been spied upon');
if (this.failedExpectations.length > 0) {
return 'failed';
} else {
return 'passed';
}
var spyObj = jasmine.createSpy(methodName);
this.spies_.push(spyObj);
spyObj.baseObj = obj;
spyObj.methodName = methodName;
spyObj.originalValue = obj[methodName];
obj[methodName] = spyObj;
return spyObj;
};
jasmine.Spec.prototype.removeAllSpies = function() {
for (var i = 0; i < this.spies_.length; i++) {
var spy = this.spies_[i];
spy.baseObj[spy.methodName] = spy.originalValue;
}
this.spies_ = [];
};
//TODO: remove
jasmine.Spec.prototype.getFullName = function() {
return this.fullNameFactory(this);
}
/**
* Internal representation of a Jasmine suite.
*
@@ -2243,13 +2207,16 @@ jasmine.Spec.prototype.removeAllSpies = function() {
* @param {Function} specDefinitions
* @param {jasmine.Suite} parentSuite
*/
jasmine.Suite = function(env, description, specDefinitions, parentSuite) {
jasmine.Suite = function(env, description, specDefinitions, parentSuite, queueFactory, isSuite) {
var self = this;
//TODO: remove once we unit test Suite
var queueFactory = queueFactory || function() {};
self.id = env.nextSuiteId ? env.nextSuiteId() : null;
self.description = description;
self.queue = new jasmine.Queue(env);
self.queue = queueFactory();
self.parentSuite = parentSuite;
self.env = env;
self.isSuite = isSuite || function() {};
self.before_ = [];
self.after_ = [];
self.children_ = [];
@@ -2283,9 +2250,10 @@ jasmine.Suite.prototype.afterEach = function(afterEachFunction) {
this.after_.unshift(afterEachFunction);
};
//TODO: interface should be addSpec or addSuite methods.
jasmine.Suite.prototype.add = function(suiteOrSpec) {
this.children_.push(suiteOrSpec);
if (suiteOrSpec instanceof jasmine.Suite) {
if (this.isSuite(suiteOrSpec)) {
this.suites_.push(suiteOrSpec);
this.env.currentRunner().addSuite(suiteOrSpec);
} else {
@@ -2294,6 +2262,14 @@ jasmine.Suite.prototype.add = function(suiteOrSpec) {
this.queue.add(suiteOrSpec);
};
jasmine.Suite.prototype.specComplete = function(specResult) {
specResult.fullName = this.getFullName() + ' ' + specResult.description + '.';
specResult.suite = this;
this.env.removeAllSpies();
this.env.reporter.reportSpecResults(specResult);
this.queue.incrementQueue();
};
jasmine.Suite.prototype.specs = function() {
return this.specs_;
};
@@ -2312,75 +2288,6 @@ jasmine.Suite.prototype.execute = function(onComplete) {
self.finish(onComplete);
});
};
jasmine.WaitsBlock = function(env, timeout, spec) {
this.timeout = timeout;
jasmine.Block.call(this, env, null, spec);
};
jasmine.util.inherit(jasmine.WaitsBlock, jasmine.Block);
jasmine.WaitsBlock.prototype.execute = function (onComplete) {
if (jasmine.VERBOSE) {
this.env.reporter.log('>> Jasmine waiting for ' + this.timeout + ' ms...');
}
this.env.setTimeout(function () {
onComplete();
}, this.timeout);
};
/**
* A block which waits for some condition to become true, with timeout.
*
* @constructor
* @extends jasmine.Block
* @param {jasmine.Env} env The Jasmine environment.
* @param {Number} timeout The maximum time in milliseconds to wait for the condition to become true.
* @param {Function} latchFunction A function which returns true when the desired condition has been met.
* @param {String} message The message to display if the desired condition hasn't been met within the given time period.
* @param {jasmine.Spec} spec The Jasmine spec.
*/
jasmine.WaitsForBlock = function(env, timeout, latchFunction, message, spec) {
this.timeout = timeout || env.defaultTimeoutInterval;
this.latchFunction = latchFunction;
this.message = message;
this.totalTimeSpentWaitingForLatch = 0;
jasmine.Block.call(this, env, null, spec);
};
jasmine.util.inherit(jasmine.WaitsForBlock, jasmine.Block);
jasmine.WaitsForBlock.TIMEOUT_INCREMENT = 10;
jasmine.WaitsForBlock.prototype.execute = function(onComplete) {
if (jasmine.VERBOSE) {
this.env.reporter.log('>> Jasmine waiting for ' + (this.message || 'something to happen'));
}
var latchFunctionResult;
try {
latchFunctionResult = this.latchFunction.apply(this.spec);
} catch (e) {
this.spec.fail(e);
onComplete();
return;
}
if (latchFunctionResult) {
onComplete();
} else if (this.totalTimeSpentWaitingForLatch >= this.timeout) {
var message = 'timed out after ' + this.timeout + ' msec waiting for ' + (this.message || 'something to happen');
this.spec.fail({
name: 'timeout',
message: message
});
this.abort = true;
onComplete();
} else {
this.totalTimeSpentWaitingForLatch += jasmine.WaitsForBlock.TIMEOUT_INCREMENT;
var self = this;
this.env.setTimeout(function() {
self.execute(onComplete);
}, jasmine.WaitsForBlock.TIMEOUT_INCREMENT);
}
};
jasmine.version_= {
"major": 1,

1
pages

Submodule pages deleted from dae7b20e1c

View File

@@ -22,46 +22,26 @@ describe("ConsoleReporter", function() {
var newline = "\n";
var passingSpec = {
var passingSpec = { status: 'passed' },
failingSpec = { status: 'failed' },
skippedSpec = { status: 'disabled' },
passingRun = {
specs: function() {
return [null, null, null];
},
results: function() {
return {
passed: function() {
return true;
}
};
return {failedCount: 0, items_: [null, null, null]};
}
},
failingSpec = {
results: function() {
return {
passed: function() {
return false;
}
};
}
failingRun = {
specs: function() {
return [null, null, null];
},
skippedSpec = {
results: function() {
return {skipped: true};
}
},
passingRun = {
specs: function() {
return [null, null, null];
},
results: function() {
return {failedCount: 0, items_: [null, null, null]};
}
},
failingRun = {
specs: function() {
return [null, null, null];
},
results: function() {
return {
failedCount: 7, items_: [null, null, null]};
}
};
results: function() {
return {
failedCount: 7, items_: [null, null, null]};
}
};
function repeatedlyInvoke(f, times) {
for (var i = 0; i < times; i++) f(times + 1);
@@ -118,18 +98,7 @@ describe("ConsoleReporter", function() {
simulateRun(reporter,
repeat(passingSpec, 3),
[],
{
specs: function() {
return [null, null, null];
},
results:function() {
return {
items_: [null, null, null],
totalCount: 7,
failedCount: 0
};
}
},
{ },
1000,
1777
);
@@ -144,30 +113,33 @@ describe("ConsoleReporter", function() {
simulateRun(reporter,
repeat(passingSpec, 57),
[],
{
specs: function() {
return [null, null, null];
},
results:function() {
return {
items_: [null, null, null],
totalCount: 7,
failedCount: 0
};
}
},
{},
1000,
1777);
var output = out.getOutput();
expect(output).toMatch(/^Started/);
expect(output).toMatch(/\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\./);
expect(output).toMatch(/3 specs, 0 failures/);
expect(output).toMatch(/57 specs, 0 failures/);
});
it("prints the proper output under a failure scenario.", function() {
var base1 = jasmine.util.extend({}, failingSpec),
failingSpec1 = jasmine.util.extend(base1, {
fullName: 'The oven heats up',
failedExpectations: [
{trace:{stack:"stack trace one\n second line"}},
{trace:{stack:"stack trace two"}}
]}),
base2 = jasmine.util.extend({}, failingSpec),
failingSpec2 = jasmine.util.extend(base2, {
fullName: "The washing machine washes clothes",
failedExpectations: [
{trace:{stack:"stack trace one"}}
]});
simulateRun(reporter,
[failingSpec, passingSpec, failingSpec],
[failingSpec1, passingSpec, failingSpec2],
[
{description:"The oven",
results:function() {
@@ -252,104 +224,9 @@ describe("ConsoleReporter", function() {
});
});
describe('when a suite reports', function() {
var emptyResults;
beforeEach(function() {
emptyResults = function() {
return {
items_:[]
};
};
});
it("remembers suite results", function() {
reporter.reportSuiteResults({description: "Oven", results: emptyResults});
reporter.reportSuiteResults({description: "Mixer", results: emptyResults});
expect(reporter.suiteResults[0].description).toEqual('Oven');
expect(reporter.suiteResults[1].description).toEqual('Mixer');
});
it("creates a description out of the current suite and any parent suites", function() {
var grandparentSuite = {
description: "My house",
results: emptyResults
};
var parentSuite = {
description: "kitchen",
parentSuite: grandparentSuite,
results: emptyResults
};
reporter.reportSuiteResults({ description: "oven", parentSuite: parentSuite, results: emptyResults });
expect(reporter.suiteResults[0].description).toEqual("My house kitchen oven");
});
it("gathers failing spec results from the suite - the spec must have a description.", function() {
reporter.reportSuiteResults({description:"Oven",
results: function() {
return {
items_:[
{ failedCount: 0, description: "specOne" },
{ failedCount: 99, description: "specTwo" },
{ failedCount: 0, description: "specThree" },
{ failedCount: 88, description: "specFour" },
{ failedCount: 3 }
]
};
}});
expect(reporter.suiteResults[0].failedSpecResults).
toEqual([
{ failedCount: 99, description: "specTwo" },
{ failedCount: 88, description: "specFour" }
]);
});
});
describe('and finishes', function() {
describe('when reporting spec failure information', function() {
it("prints suite and spec descriptions together as a sentence", function() {
reporter.suiteResults = [
{description:"The oven", failedSpecResults:[
{description:"heats up", items_:[]},
{description:"cleans itself", items_:[]}
]},
{description:"The mixer", failedSpecResults:[
{description:"blends things together", items_:[]}
]}
];
reporter.reportRunnerResults(failingRun);
expect(out.getOutput()).toContain("The oven heats up");
expect(out.getOutput()).toContain("The oven cleans itself");
expect(out.getOutput()).toContain("The mixer blends things together");
});
it("prints stack trace of spec failure", function() {
reporter.suiteResults = [
{description:"The oven", failedSpecResults:[
{description:"heats up",
items_:[
{trace:{stack:"stack trace one"}},
{trace:{stack:"stack trace two"}}
]}
]}
];
reporter.reportRunnerResults(failingRun);
expect(out.getOutput()).toContain("The oven heats up");
expect(out.getOutput()).toContain("stack trace one");
expect(out.getOutput()).toContain("stack trace two");
});
});
describe('when reporting the execution time', function() {
it("prints the full finished message", function() {
@@ -391,47 +268,6 @@ describe("ConsoleReporter", function() {
});
});
describe("when reporting the results summary", function() {
it("prints statistics in green if there were no failures", function() {
reporter.reportRunnerResults({
specs: function() {
return [null, null, null];
},
results:function() {
return {items_: [null, null, null], totalCount: 7, failedCount: 0};
}
});
expect(out.getOutput()).
toContain("3 specs, 0 failures");
});
it("prints statistics in red if there was a failure", function() {
reporter.reportRunnerResults({
specs: function() {
return [null, null, null];
},
results:function() {
return {items_: [null, null, null], totalCount: 7, failedCount: 3};
}
});
expect(out.getOutput()).
toContain("3 specs, 3 failures");
});
it("handles pluralization with 1's ones appropriately", function() {
reporter.reportRunnerResults({
specs: function() {
return [null];
},
results:function() {
return {items_: [null], totalCount: 1, failedCount: 1};
}
});
expect(out.getOutput()).
toContain("1 spec, 1 failure");
});
});
describe("done callback", function() {
it("calls back when done", function() {
expect(done).toBeFalsy();
@@ -448,4 +284,4 @@ describe("ConsoleReporter", function() {
});
});
});
});
});

View File

@@ -1,95 +1,96 @@
describe("Custom Matchers", function() {
var env;
var fakeTimer;
beforeEach(function() {
env = new jasmine.Env();
env.updateInterval = 0;
});
it("should be easy to add more matchers local to a spec, suite, etc.", function() {
var spec1, spec2, spec1Matcher, spec2Matcher;
var suite = env.describe('some suite', function() {
env.beforeEach(function() {
this.addMatchers({
matcherForSuite: function(expected) {
this.message = "matcherForSuite: actual: " + this.actual + "; expected: " + expected;
return true;
}
});
});
spec1 = env.it('spec with an expectation').runs(function () {
this.addMatchers({
matcherForSpec: function(expected) {
this.message = "matcherForSpec: actual: " + this.actual + "; expected: " + expected;
return true;
}
});
spec1Matcher = this.expect("xxx");
});
spec2 = env.it('spec with failing expectation').runs(function () {
spec2Matcher = this.expect("yyy");
});
});
suite.execute();
spec1Matcher.matcherForSuite("expected");
expect(spec1Matcher.message).toEqual("matcherForSuite: actual: xxx; expected: expected");
spec1Matcher.matcherForSpec("expected");
expect(spec1Matcher.message).toEqual("matcherForSpec: actual: xxx; expected: expected");
spec2Matcher.matcherForSuite("expected");
expect(spec2Matcher.message).toEqual("matcherForSuite: actual: yyy; expected: expected");
expect(spec2Matcher.matcherForSpec).toBe(jasmine.undefined);
});
it("should generate messages with the same rules as for regular matchers when this.report() is not called", function() {
var spec;
var suite = env.describe('some suite', function() {
spec = env.it('spec with an expectation').runs(function () {
this.addMatchers({
toBeTrue: function() {
return this.actual === true;
}
});
this.expect(true).toBeTrue();
this.expect(false).toBeTrue();
});
});
suite.execute();
var results = spec.results().getItems();
expect(results[0].message).toEqual("Passed.");
expect(results[1].message).toEqual("Expected false to be true.");
});
it("should pass args", function() {
var matcherCallArgs = [];
var spec;
var suite = env.describe('some suite', function() {
spec = env.it('spec with an expectation').runs(function () {
this.addMatchers({
toBeTrue: function() {
matcherCallArgs.push(jasmine.util.argsToArray(arguments));
return this.actual === true;
}
});
this.expect(true).toBeTrue();
this.expect(false).toBeTrue('arg');
this.expect(true).toBeTrue('arg1', 'arg2');
});
});
suite.execute();
var results = spec.results().getItems();
expect(results[0].expected).toEqual(jasmine.undefined);
expect(results[1].expected).toEqual('arg');
expect(results[2].expected).toEqual(['arg1', 'arg2']);
expect(matcherCallArgs).toEqual([[], ['arg'], ['arg1', 'arg2']]);
});
});
////TODO: matchers should be add-able to the env, not to the spec.
//describe("Custom Matchers", function() {
// var env;
// var fakeTimer;
//
// beforeEach(function() {
// env = new jasmine.Env();
// env.updateInterval = 0;
// });
//
// it("should be easy to add more matchers local to a spec, suite, etc.", function() {
// var spec1, spec2, spec1Matcher, spec2Matcher;
// var suite = env.describe('some suite', function() {
// env.beforeEach(function() {
// this.addMatchers({
// matcherForSuite: function(expected) {
// this.message = "matcherForSuite: actual: " + this.actual + "; expected: " + expected;
// return true;
// }
// });
// });
//
// spec1 = env.it('spec with an expectation').runs(function () {
// this.addMatchers({
// matcherForSpec: function(expected) {
// this.message = "matcherForSpec: actual: " + this.actual + "; expected: " + expected;
// return true;
// }
// });
// spec1Matcher = this.expect("xxx");
// });
//
// spec2 = env.it('spec with failing expectation').runs(function () {
// spec2Matcher = this.expect("yyy");
// });
// });
//
// suite.execute();
//
// spec1Matcher.matcherForSuite("expected");
// expect(spec1Matcher.message).toEqual("matcherForSuite: actual: xxx; expected: expected");
// spec1Matcher.matcherForSpec("expected");
// expect(spec1Matcher.message).toEqual("matcherForSpec: actual: xxx; expected: expected");
//
// spec2Matcher.matcherForSuite("expected");
// expect(spec2Matcher.message).toEqual("matcherForSuite: actual: yyy; expected: expected");
// expect(spec2Matcher.matcherForSpec).toBe(jasmine.undefined);
// });
//
// it("should generate messages with the same rules as for regular matchers when this.report() is not called", function() {
// var spec;
// var suite = env.describe('some suite', function() {
// spec = env.it('spec with an expectation').runs(function () {
// this.addMatchers({
// toBeTrue: function() {
// return this.actual === true;
// }
// });
// this.expect(true).toBeTrue();
// this.expect(false).toBeTrue();
// });
// });
//
// suite.execute();
//
// var results = spec.results().getItems();
// expect(results[0].message).toEqual("Passed.");
// expect(results[1].message).toEqual("Expected false to be true.");
// });
//
// it("should pass args", function() {
// var matcherCallArgs = [];
// var spec;
// var suite = env.describe('some suite', function() {
// spec = env.it('spec with an expectation').runs(function () {
// this.addMatchers({
// toBeTrue: function() {
// matcherCallArgs.push(jasmine.util.argsToArray(arguments));
// return this.actual === true;
// }
// });
// this.expect(true).toBeTrue();
// this.expect(false).toBeTrue('arg');
// this.expect(true).toBeTrue('arg1', 'arg2');
// });
// });
//
// suite.execute();
// var results = spec.results().getItems();
// expect(results[0].expected).toEqual(jasmine.undefined);
// expect(results[1].expected).toEqual('arg');
// expect(results[2].expected).toEqual(['arg1', 'arg2']);
//
// expect(matcherCallArgs).toEqual([[], ['arg'], ['arg1', 'arg2']]);
// });
//});

View File

@@ -34,6 +34,9 @@ describe('Exceptions:', function() {
describe('with break on exception', function() {
it('should not catch the exception', function() {
var oldCatch = jasmine.CATCH_EXCEPTIONS;
jasmine.CATCH_EXCEPTIONS = false;
env = new jasmine.Env();
var suite = env.describe('suite for break on exceptions', function() {
env.it('should break when an exception is thrown', function() {
throw new Error('I should hit a breakpoint!');
@@ -42,8 +45,6 @@ describe('Exceptions:', function() {
var runner = env.currentRunner();
var dont_change = 'I will never change!';
var oldCatch = jasmine.CATCH_EXCEPTIONS;
jasmine.CATCH_EXCEPTIONS = false;
try {
suite.execute();
dont_change = 'oops I changed';

View File

@@ -1,6 +1,6 @@
describe('jasmine.jsApiReporter', function() {
describe('results', function () {
var reporter, spec1, spec2, spec3, expectedSpec1Results, expectedSpec2Results;
var reporter, spec1, spec2;
var env;
var suite, nestedSuite, nestedSpec;
@@ -24,34 +24,24 @@ describe('jasmine.jsApiReporter', function() {
});
});
spec3 = env.it("spec 3", function() {
this.log('some debug message');
});
});
reporter = new jasmine.JsApiReporter();
reporter = new jasmine.JsApiReporter(jasmine);
env.addReporter(reporter);
env.execute();
expectedSpec1Results = {
messages: spec1.results().getItems(),
result: "passed"
};
expectedSpec2Results = {
messages: spec2.results().getItems(),
result: "failed"
};
});
it('resultForSpec() should return the result for the given spec', function () {
expect(reporter.resultsForSpec(spec1.id)).toEqual(expectedSpec1Results);
expect(reporter.resultsForSpec(spec2.id)).toEqual(expectedSpec2Results);
});
it('results() should return a hash of all results, indexed by spec id', function () {
expect(reporter.results()[spec1.id]).toEqual(expectedSpec1Results);
expect(reporter.results()[spec2.id]).toEqual(expectedSpec2Results);
var expectedSpec1Results = {
result: "passed"
},
expectedSpec2Results = {
result: "failed"
};
expect(reporter.results()[spec1.id].result).toEqual('passed');
expect(reporter.results()[spec2.id].result).toEqual('failed');
});
it("should return nested suites as children of their parents", function() {
@@ -65,7 +55,6 @@ describe('jasmine.jsApiReporter', function() {
{ id: 2, name: 'nested spec', type: 'spec', children: [ ] }
]
},
{ id: 3, name: 'spec 3', type: 'spec', children: [ ] }
]
}
]);
@@ -76,12 +65,7 @@ describe('jasmine.jsApiReporter', function() {
var result = reporter.results()[spec1.id];
var summarizedResult = reporter.summarizeResult_(result);
expect(summarizedResult.result).toEqual('passed');
expect(summarizedResult.messages.length).toEqual(1);
expect(summarizedResult.messages[0].message).toEqual(result.messages[0].message);
expect(summarizedResult.messages[0].passed).toBeTruthy();
expect(summarizedResult.messages[0].type).toEqual('expect');
expect(summarizedResult.messages[0].text).toBeUndefined();
expect(summarizedResult.messages[0].trace.stack).toBeUndefined();
expect(summarizedResult.messages.length).toEqual(0);
});
it("should have a stack trace for failing specs", function() {
@@ -91,13 +75,6 @@ describe('jasmine.jsApiReporter', function() {
expect(summarizedResult.messages[0].trace.stack).toEqual(result.messages[0].trace.stack);
});
it("should have messages for specs with messages", function() {
var result = reporter.results()[spec3.id];
var summarizedResult = reporter.summarizeResult_(result);
expect(summarizedResult.result).toEqual('passed');
expect(summarizedResult.messages[0].type).toEqual('log');
expect(summarizedResult.messages[0].text).toEqual('some debug message');
});
});
});
});

View File

@@ -9,9 +9,9 @@ describe("jasmine.Matchers", function() {
spec = env.it("spec", function() {
});
});
spyOn(spec, 'addMatcherResult');
spyOn(spec, 'addExpectationResult');
this.addMatchers({
addMatchers({
toPass: function() {
return lastResult().passed;
},
@@ -26,7 +26,7 @@ describe("jasmine.Matchers", function() {
}
function lastResult() {
return spec.addMatcherResult.mostRecentCall.args[0];
return spec.addExpectationResult.mostRecentCall.args[1];
}
function catchException(fn) {
@@ -293,28 +293,28 @@ describe("jasmine.Matchers", function() {
expect(result.actual).toEqual(actual);
});
it("toBeNaN", function() {
expect(match(Number.NaN).toBeNaN()).toPass();
expect(match(0).toBeNaN()).toFail();
expect(match(1).toBeNaN()).toFail();
expect(match(null).toBeNaN()).toFail();
expect(match(Number.POSITIVE_INFINITY).toBeNaN()).toFail();
expect(match(Number.NEGATIVE_INFINITY).toBeNaN()).toFail();
expect(match('NaN').toBeNaN()).toFail();
});
it("toBeNaN", function() {
expect(match(Number.NaN).toBeNaN()).toPass();
expect(match(0).toBeNaN()).toFail();
expect(match(1).toBeNaN()).toFail();
expect(match(null).toBeNaN()).toFail();
expect(match(Number.POSITIVE_INFINITY).toBeNaN()).toFail();
expect(match(Number.NEGATIVE_INFINITY).toBeNaN()).toFail();
expect(match('NaN').toBeNaN()).toFail();
});
it("toBeNaN to build an ExpectationResult", function() {
var actual = 'a';
var matcher = match(actual);
matcher.toBeNaN();
it("toBeNaN to build an ExpectationResult", function() {
var actual = 'a';
var matcher = match(actual);
matcher.toBeNaN();
var result = lastResult();
var result = lastResult();
expect(result.matcherName).toEqual("toBeNaN");
expect(result.passed).toBe(false);
expect(result.message).toMatch("Expected 'a' to be NaN.");
expect(result.actual).toMatch(actual);
});
expect(result.matcherName).toEqual("toBeNaN");
expect(result.passed).toBe(false);
expect(result.message).toMatch("Expected 'a' to be NaN.");
expect(result.actual).toMatch(actual);
});
it("toBeFalsy", function() {
expect(match(false).toBeFalsy()).toPass();
@@ -378,11 +378,11 @@ describe("jasmine.Matchers", function() {
expect(match({someObj:'foo'}).toEqual(jasmine.any(Function))).toFail();
expect(match(
function() {
}).toEqual(jasmine.any(Object))).toFail();
}).toEqual(jasmine.any(Object))).toFail();
expect(match(["foo", "goo"]).toEqual(["foo", jasmine.any(String)])).toPass();
expect(match(
function() {
}).toEqual(jasmine.any(Function))).toPass();
}).toEqual(jasmine.any(Function))).toPass();
expect(match(["a", function() {
}]).toEqual(["a", jasmine.any(Function)])).toPass();
});
@@ -608,13 +608,13 @@ describe("jasmine.Matchers", function() {
it("should match exceptions specified by message", function() {
expect(match(throwingFn).not.toThrow("Fake Error")).toFail();
// expect(lastResult().message).toMatch(/Expected function not to throw Fake Error./);
// expect(lastResult().message).toMatch(/Expected function not to throw Fake Error./);
expect(match(throwingFn).not.toThrow("Other Error")).toPass();
});
it("should match exceptions specified by Error", function() {
expect(match(throwingFn).not.toThrow(new Error("Fake Error"))).toFail();
// expect(lastResult().message).toMatch("Other Error");
// expect(lastResult().message).toMatch("Other Error");
expect(match(throwingFn).not.toThrow(new Error("Other Error"))).toPass();
});
});
@@ -645,7 +645,7 @@ describe("jasmine.Matchers", function() {
it("should fail (or pass when inverted with .not)", function() {
expect(match(
function() {
}).toThrow()).toFail();
}).toThrow()).toFail();
expect(lastResult().message).toEqual('Expected function to throw an exception.');
});
});
@@ -668,7 +668,7 @@ describe("jasmine.Matchers", function() {
});
it("should use the second message when the matcher sets an array of custom messages", function() {
spec.addMatchers({
env.addMatchers({
custom: function() {
this.message = function() {
return ['Expected it was called.', 'Expected it wasn\'t called.'];
@@ -702,23 +702,23 @@ describe("jasmine.Matchers", function() {
return function() {
expect(
function() {
match(TestClass.normalFunction)[methodName]();
}).toThrow('Expected a spy, but got Function.');
match(TestClass.normalFunction)[methodName]();
}).toThrow('Expected a spy, but got Function.');
expect(
function() {
match(jasmine.undefined)[methodName]();
}).toThrow('Expected a spy, but got undefined.');
match(jasmine.undefined)[methodName]();
}).toThrow('Expected a spy, but got undefined.');
expect(
function() {
match({some:'object'})[methodName]();
}).toThrow('Expected a spy, but got { some : \'object\' }.');
match({some:'object'})[methodName]();
}).toThrow('Expected a spy, but got { some : \'object\' }.');
expect(
function() {
match("<b>")[methodName]();
}).toThrow('Expected a spy, but got \'<b>\'.');
match("<b>")[methodName]();
}).toThrow('Expected a spy, but got \'<b>\'.');
};
}
@@ -733,8 +733,8 @@ describe("jasmine.Matchers", function() {
it("should throw an exception when invoked with any arguments", function() {
expect(
function() {
match(TestClass.normalFunction).toHaveBeenCalled("unwanted argument");
}).toThrow('toHaveBeenCalled does not take arguments, use toHaveBeenCalledWith');
match(TestClass.normalFunction).toHaveBeenCalled("unwanted argument");
}).toThrow('toHaveBeenCalled does not take arguments, use toHaveBeenCalledWith');
});
it('should throw an exception when invoked on a non-spy', shouldThrowAnExceptionWhenInvokedOnANonSpy('toHaveBeenCalled'));
@@ -762,8 +762,8 @@ describe("jasmine.Matchers", function() {
it("should throw an exception when invoked with any arguments", function() {
expect(
function() {
match(TestClass.normalFunction).wasNotCalled("unwanted argument");
}).toThrow('wasNotCalled does not take arguments');
match(TestClass.normalFunction).wasNotCalled("unwanted argument");
}).toThrow('wasNotCalled does not take arguments');
});
it('should throw an exception when invoked on a non-spy', shouldThrowAnExceptionWhenInvokedOnANonSpy('wasNotCalled'));
@@ -839,7 +839,7 @@ describe("jasmine.Matchers", function() {
}, spec);
TestClass = { someFunction: function(a, b) {
} };
spec.spyOn(TestClass, 'someFunction');
env.spyOn(TestClass, 'someFunction');
});
it("should should handle the case of a spy", function() {
@@ -910,7 +910,7 @@ describe("jasmine.Matchers", function() {
containing = new jasmine.Matchers.ObjectContaining({});
});
it("matches everything", function () {
expect(containing.jasmineMatches("foo", [], [])).toBe(true);
expect(containing.jasmineMatches("foo", [], [])).toBe(true);
});
it("says it didn't expect to contain anything", function () {

View File

@@ -1,40 +1,40 @@
// TODO: Disabling b/c this spec isn't testing what it thinks it is.
// Make a proper unit and intergration tests for this object
xdescribe("MockClock", function () {
beforeEach(function() {
jasmine.Clock.useMock();
});
describe("setTimeout", function () {
it("should mock the clock when useMock is in a beforeEach", function() {
var expected = false;
setTimeout(function() {
expected = true;
}, 30000);
expect(expected).toBe(false);
jasmine.Clock.tick(30001);
expect(expected).toBe(true);
});
});
describe("setInterval", function () {
it("should mock the clock when useMock is in a beforeEach", function() {
var interval = 0;
setInterval(function() {
interval++;
}, 30000);
expect(interval).toEqual(0);
jasmine.Clock.tick(30001);
expect(interval).toEqual(1);
jasmine.Clock.tick(30001);
expect(interval).toEqual(2);
jasmine.Clock.tick(1);
expect(interval).toEqual(2);
});
});
it("shouldn't complain if you call jasmine.Clock.useMock() more than once", function() {
jasmine.Clock.useMock();
});
});
//// TODO: Disabling b/c this spec isn't testing what it thinks it is.
//// Make a proper unit and intergration tests for this object
//describe("MockClock", function () {
//
// beforeEach(function() {
// jasmine.Clock.useMock();
// });
//
// describe("setTimeout", function () {
// it("should mock the clock when useMock is in a beforeEach", function() {
// var expected = false;
// setTimeout(function() {
// expected = true;
// }, 30000);
// expect(expected).toBe(false);
// jasmine.Clock.tick(30001);
// expect(expected).toBe(true);
// });
// });
//
// describe("setInterval", function () {
// it("should mock the clock when useMock is in a beforeEach", function() {
// var interval = 0;
// setInterval(function() {
// interval++;
// }, 30000);
// expect(interval).toEqual(0);
// jasmine.Clock.tick(30001);
// expect(interval).toEqual(1);
// jasmine.Clock.tick(30001);
// expect(interval).toEqual(2);
// jasmine.Clock.tick(1);
// expect(interval).toEqual(2);
// });
// });
//
// it("shouldn't complain if you call jasmine.Clock.useMock() more than once", function() {
// jasmine.Clock.useMock();
// });
//});

View File

@@ -13,7 +13,7 @@ describe("jasmine.MultiReporter", function() {
var delegate = {};
multiReporter.addReporter(delegate);
this.addMatchers({
addMatchers({
toDelegateMethod: function(methodName) {
delegate[methodName] = originalJasmine.createSpy(methodName);
this.actual[methodName]("whatever argument");

View File

@@ -1,22 +0,0 @@
describe("jasmine.Queue", function() {
it("should not call itself recursively, so we don't get stack overflow errors", function() {
var queue = new jasmine.Queue(new jasmine.Env());
queue.add(new jasmine.Block(null, function() {}));
queue.add(new jasmine.Block(null, function() {}));
queue.add(new jasmine.Block(null, function() {}));
queue.add(new jasmine.Block(null, function() {}));
var nestCount = 0;
var maxNestCount = 0;
var nextCallCount = 0;
queue.next_ = function() {
nestCount++;
if (nestCount > maxNestCount) maxNestCount = nestCount;
jasmine.Queue.prototype.next_.apply(queue, arguments);
nestCount--;
};
queue.start();
expect(maxNestCount).toEqual(1);
});
});

View File

@@ -90,7 +90,7 @@ describe('RunnerTest', function() {
env.describe('suite',function() {
env.it('fails', function() {
this.fail();
this.expect(true).toBe(false);
});
}).execute();
@@ -107,31 +107,20 @@ describe('RunnerTest', function() {
describe('reporting', function() {
var fakeReporter;
beforeEach(function() {
fakeReporter = originalJasmine.createSpyObj("fakeReporter", ["log", "reportRunnerStarting", "reportRunnerResults"]);
env.addReporter(fakeReporter);
});
it('should report runner results when the runner has completed running', function() {
env.describe('one suite description', function() {
env.it('should be a test', function() {
this.runs(function() {
this.expect(true).toEqual(true);
});
});
var specSpy = originalJasmine.createSpy('spec').andCallFake(function() {
expect(fakeReporter.reportRunnerResults).not.toHaveBeenCalled();
});
env.describe('another suite description', function() {
env.it('should be another test', function() {
this.waits(200);
this.runs(function() {
this.expect(true).toEqual(false);
});
});
env.describe('description', function() {
env.it('should be a test', specSpy);
});
env.currentRunner().execute();
expect(fakeReporter.reportRunnerResults).not.toHaveBeenCalled();
fakeTimer.tick(200);
expect(specSpy).toHaveBeenCalled();
expect(fakeReporter.reportRunnerResults).toHaveBeenCalledWith(env.currentRunner());
});
});

View File

@@ -37,566 +37,6 @@ describe("jasmine spec running", function () {
expect(it4.id).toEqual(4);
});
it("should build up some objects with results we can inspect", function() {
var specWithNoBody, specWithExpectation, specWithFailingExpectations, specWithMultipleExpectations;
var suite = env.describe('default current suite', function() {
specWithNoBody = env.it('new spec');
specWithExpectation = env.it('spec with an expectation').runs(function () {
var foo = 'bar';
this.expect(foo).toEqual('bar');
});
specWithFailingExpectations = env.it('spec with failing expectation').runs(function () {
var foo = 'bar';
this.expect(foo).toEqual('baz');
});
specWithMultipleExpectations = env.it('spec with multiple expectations').runs(function () {
var foo = 'bar';
var baz = 'quux';
this.expect(foo).toEqual('bar');
this.expect(baz).toEqual('quux');
});
});
suite.execute();
expect(specWithNoBody.description).toEqual('new spec');
expect(specWithExpectation.results().getItems().length).toEqual(1); // "Results aren't there after a spec was executed"
expect(specWithExpectation.results().getItems()[0].passed).toEqual(true); // "Results has a result, but it's true"
expect(specWithExpectation.results().description).toEqual('spec with an expectation'); // "Spec's results did not get the spec's description"
expect(specWithFailingExpectations.results().getItems()[0].passed).toEqual(false); // "Expectation that failed, passed"
expect(specWithMultipleExpectations.results().getItems().length).toEqual(2); // "Spec doesn't support multiple expectations"
});
it("should work without a runs block", function() {
var another_spec;
env.describe('default current suite', function() {
another_spec = env.it('spec with an expectation', function () {
var foo = 'bar';
this.expect(foo).toEqual('bar');
this.expect(foo).toEqual('baz');
});
});
another_spec.execute();
another_spec.done = true;
expect(another_spec.results().getItems().length).toEqual(2);
expect(another_spec.results().getItems()[0].passed).toEqual(true); // "In a spec without a run block, expected first expectation result to be true but was false"
expect(another_spec.results().getItems()[1].passed).toEqual(false); // "In a spec without a run block, expected second expectation result to be false but was true";
expect(another_spec.results().description).toEqual('spec with an expectation'); // "In a spec without a run block, results did not include the spec's description";
});
it('should queue waits and runs that it encounters while executing specs', function() {
var specWithRunsAndWaits;
var foo = 0;
env.describe('test async spec', function() {
specWithRunsAndWaits = env.it('spec w/ queued statments', function () {
this.runs(function () {
foo++;
});
this.waits(500);
this.runs(function () {
foo++;
});
this.waits(500);
this.runs(function () {
foo++;
});
});
});
expect(foo).toEqual(0);
specWithRunsAndWaits.execute();
expect(foo).toEqual(1);
fakeTimer.tick(500);
expect(foo).toEqual(2);
fakeTimer.tick(500);
expect(foo).toEqual(3);
});
it("should run asynchronous tests", function () {
var foo = 0;
var a_spec;
env.describe('test async spec', function() {
a_spec = env.it('spec w/ queued statments', function () {
this.runs(function () {
foo++;
});
this.runs(function () {
this.expect(foo).toEqual(1);
});
});
});
a_spec.execute();
expect(a_spec.results().getItems().length).toEqual(1); // 'No call to waits(): Spec queue did not run all functions';
expect(a_spec.results().getItems()[0].passed).toEqual(true); // 'No call to waits(): Queued expectation failed';
foo = 0;
env.describe('test async spec', function() {
a_spec = env.it('spec w/ queued statments', function () {
this.runs(function () {
fakeTimer.setTimeout(function() {
foo++;
}, 500);
});
this.waits(1000);
this.runs(function() {
this.expect(foo).toEqual(1);
});
});
});
a_spec.execute();
expect(a_spec.results().getItems().length).toEqual(0);
fakeTimer.tick(500);
expect(a_spec.results().getItems().length).toEqual(0);
fakeTimer.tick(500);
expect(a_spec.results().getItems().length).toEqual(1); // 'Calling waits(): Spec queue did not run all functions';
expect(a_spec.results().getItems()[0].passed).toEqual(true); // 'Calling waits(): Queued expectation failed';
var bar = 0;
var another_spec;
env.describe('test async spec', function() {
another_spec = env.it('spec w/ queued statments', function () {
this.runs(function () {
fakeTimer.setTimeout(function() {
bar++;
}, 250);
});
this.waits(500);
this.runs(function () {
fakeTimer.setTimeout(function() {
bar++;
}, 250);
});
this.waits(500);
this.runs(function () {
this.expect(bar).toEqual(2);
});
});
});
another_spec.execute();
fakeTimer.tick(1000);
expect(another_spec.results().getItems().length).toEqual(1);
expect(another_spec.results().getItems()[0].passed).toEqual(true);
var baz = 0;
var yet_another_spec;
env.describe('test async spec', function() {
yet_another_spec = env.it('spec w/ async fail', function () {
this.runs(function () {
fakeTimer.setTimeout(function() {
baz++;
}, 250);
});
this.waits(100);
this.runs(function() {
this.expect(baz).toEqual(1);
});
});
});
yet_another_spec.execute();
//tick twice so that second runs gets eval'd first: mockClock bug?
fakeTimer.tick(100);
fakeTimer.tick(150);
expect(yet_another_spec.results().getItems().length).toEqual(1);
expect(yet_another_spec.results().getItems()[0].passed).toEqual(false);
});
it("testAsyncSpecsWithMockSuite", function () {
var bar = 0;
var another_spec;
env.describe('test async spec', function() {
another_spec = env.it('spec w/ queued statments', function () {
this.runs(function () {
fakeTimer.setTimeout(function() {
bar++;
}, 250);
});
this.waits(500);
this.runs(function () {
fakeTimer.setTimeout(function() {
bar++;
}, 250);
});
this.waits(1500);
this.runs(function() {
this.expect(bar).toEqual(2);
});
});
});
another_spec.execute();
fakeTimer.tick(2000);
expect(another_spec.results().getItems().length).toEqual(1);
expect(another_spec.results().getItems()[0].passed).toEqual(true);
});
describe("waitsFor", function() {
var latchFunction = function() {
return true;
};
var spec;
function makeWaitsForSpec() {
var args = jasmine.util.argsToArray(arguments);
env.describe('suite', function() {
spec = env.it('spec', function() {
this.waitsFor.apply(this, args);
});
});
env.execute();
}
it("should accept args (latchFunction, timeoutMessage, timeout)", function() {
makeWaitsForSpec(latchFunction, "message", 123);
var block = spec.queue.blocks[1];
expect(block.latchFunction).toBe(latchFunction);
expect(block.timeout).toEqual(123);
expect(block.message).toEqual('message');
});
it("should accept args (latchFunction, timeout)", function() {
makeWaitsForSpec(latchFunction, 123);
var block = spec.queue.blocks[1];
expect(block.latchFunction).toBe(latchFunction);
expect(block.timeout).toEqual(123);
expect(block.message).toEqual(null);
});
it("should accept args (latchFunction, timeoutMessage)", function() {
env.defaultTimeoutInterval = 4321;
makeWaitsForSpec(latchFunction, "message");
var block = spec.queue.blocks[1];
expect(block.latchFunction).toBe(latchFunction);
expect(block.timeout).toEqual(4321);
expect(block.message).toEqual('message');
});
it("should accept args (latchFunction)", function() {
env.defaultTimeoutInterval = 4321;
makeWaitsForSpec(latchFunction);
var block = spec.queue.blocks[1];
expect(block.latchFunction).toBe(latchFunction);
expect(block.timeout).toEqual(4321);
expect(block.message).toEqual(null);
});
it("should accept deprecated args order (timeout, latchFunction, timeoutMessage)", function() {
makeWaitsForSpec(123, latchFunction, "message");
var block = spec.queue.blocks[1];
expect(block.latchFunction).toBe(latchFunction);
expect(block.timeout).toEqual(123);
expect(block.message).toEqual('message');
});
it("testWaitsFor", function() {
var doneWaiting = false;
var runsBlockExecuted = false;
var spec;
env.describe('foo', function() {
spec = env.it('has a waits for', function() {
this.runs(function() {
});
this.waitsFor(500, function() {
return doneWaiting;
});
this.runs(function() {
runsBlockExecuted = true;
});
});
});
spec.execute();
expect(runsBlockExecuted).toEqual(false); //, 'should not have executed runs block yet');
fakeTimer.tick(100);
doneWaiting = true;
fakeTimer.tick(100);
expect(runsBlockExecuted).toEqual(true); //, 'should have executed runs block');
});
it("fails with message", function() {
var spec;
env.describe('foo', function() {
spec = env.it('has a waits for', function() {
this.runs(function() {
});
this.waitsFor(500, function() {
return false; // force a timeout
}, 'my awesome condition');
this.runs(function() {
});
});
});
spec.execute();
fakeTimer.tick(1000);
expect(spec.results().getItems()[0].message).toEqual('timeout: timed out after 500 msec waiting for my awesome condition');
});
it("fails and skips the rest of the spec if timeout is reached and the latch function hasn't returned true", function() {
var runsBlockExecuted = false;
var subsequentSpecRan = false;
var timeoutSpec, subsequentSpec;
var suite = env.describe('foo', function() {
timeoutSpec = env.it('has a waits for', function() {
this.runs(function() {
});
this.waitsFor(500, function() {
return false;
});
this.runs(function() {
runsBlockExecuted = true;
});
});
subsequentSpec = env.it('then carries on to the next test', function() {
subsequentSpecRan = true;
});
});
env.execute();
expect(runsBlockExecuted).toEqual(false);
fakeTimer.tick(100);
expect(runsBlockExecuted).toEqual(false);
fakeTimer.tick(400);
expect(runsBlockExecuted).toEqual(false);
expect(timeoutSpec.results().getItems()[0].message).toEqual('timeout: timed out after 500 msec waiting for something to happen');
expect(subsequentSpecRan).toEqual(true);
});
it("runs afterEach after timing out", function() {
var afterEach = originalJasmine.createSpy('afterEach');
env.describe('foo', function () {
env.afterEach(afterEach);
env.it('waitsFor', function () {
this.waitsFor(100, function() {
return false;
});
});
}).execute();
fakeTimer.tick(500);
expect(afterEach).toHaveBeenCalled();
});
it("runs single-spec after functions after timing out", function() {
var after = originalJasmine.createSpy('after');
env.describe('foo', function () {
env.it('waitsFor', function () {
this.after(after);
this.waitsFor(100, function() {
return false;
});
});
}).execute();
fakeTimer.tick(500);
expect(after).toHaveBeenCalled();
});
describe('with consecutive calls', function () {
var foo;
beforeEach(function () {
foo = 0;
});
it('exits immediately (does not stack) if the latchFunction times out', function () {
var reachedFirstWaitsFor = false;
var reachedSecondWaitsFor = false;
env.describe('suite that waits', function () {
env.it('should stack timeouts', function() {
this.waitsFor(500, function () {
reachedFirstWaitsFor = true;
return false;
});
this.waitsFor(500, function () {
reachedSecondWaitsFor = true;
});
this.runs(function () {
foo++;
});
});
});
expect(reachedFirstWaitsFor).toEqual(false);
env.execute();
expect(reachedFirstWaitsFor).toEqual(true);
expect(foo).toEqual(0);
expect(reachedSecondWaitsFor).toEqual(false);
fakeTimer.tick(500);
expect(reachedSecondWaitsFor).toEqual(false);
expect(foo).toEqual(0);
fakeTimer.tick(500);
expect(reachedSecondWaitsFor).toEqual(false);
expect(foo).toEqual(0);
});
it('stacks latchFunctions', function () {
var firstWaitsResult = false;
var secondWaitsResult = false;
var waitsSuite = env.describe('suite that waits', function () {
env.it('spec with waitsFors', function() {
this.waitsFor(600, function () {
fakeTimer.setTimeout(function () {
firstWaitsResult = true;
}, 300);
return firstWaitsResult;
});
this.waitsFor(600, function () {
fakeTimer.setTimeout(function () {
secondWaitsResult = true;
}, 300);
return secondWaitsResult;
});
this.runs(function () {
foo++;
});
});
});
expect(firstWaitsResult).toEqual(false);
expect(secondWaitsResult).toEqual(false);
waitsSuite.execute();
expect(firstWaitsResult).toEqual(false);
expect(secondWaitsResult).toEqual(false);
expect(foo).toEqual(0);
fakeTimer.tick(300);
expect(firstWaitsResult).toEqual(true);
expect(secondWaitsResult).toEqual(false);
expect(foo).toEqual(0);
fakeTimer.tick(300);
expect(firstWaitsResult).toEqual(true);
expect(secondWaitsResult).toEqual(true);
expect(foo).toEqual(1);
});
});
});
it("testSpecAfter", function() {
var log = "";
var spec;
var suite = env.describe("has after", function() {
spec = env.it('spec with after', function() {
this.runs(function() {
log += "spec";
});
});
});
spec.after(function() {
log += "after1";
});
spec.after(function() {
log += "after2";
});
suite.execute();
expect(log).toEqual("specafter2after1");
});
describe('test suite declaration', function() {
var suite;
var dummyFunction = function() {
};
it('should give the suite a description', function() {
suite = env.describe('one suite description', dummyFunction);
expect(suite.description).toEqual('one suite description');
});
it('should enqueue functions for multipart tests and support waits, and run any ready runs() blocks', function() {
var foo = 0;
var bar = 0;
suite = env.describe('one suite description', function () {
env.it('should be a test with queuedFunctions', function() {
this.runs(function() {
foo++;
});
this.waits(100);
this.runs(function() {
bar++;
});
});
});
suite.execute();
expect(foo).toEqual(1);
expect(bar).toEqual(0);
fakeTimer.tick(100);
expect(bar).toEqual(1);
});
});
it('#waits should allow consecutive waits calls', function () {
var foo = 0;
var waitsSuite = env.describe('suite that waits', function () {
env.it('should wait', function() {
this.waits(500);
this.waits(500);
this.runs(function () {
foo++;
});
});
});
waitsSuite.execute();
expect(foo).toEqual(0);
fakeTimer.tick(500);
expect(foo).toEqual(0);
fakeTimer.tick(500);
expect(foo).toEqual(1);
});
it('nested suites', function () {
var foo = 0;
@@ -636,183 +76,6 @@ describe("jasmine spec running", function () {
expect(quux).toEqual(1);
});
it("#beforeEach should be able to eval runs and waits blocks", function () {
var foo = 0;
var bar = 0;
var suiteWithBefore = env.describe('one suite with a before', function () {
this.beforeEach(function () {
this.runs(function () {
foo++;
});
this.waits(500);
this.runs(function () {
foo++;
});
this.waits(500);
});
env.it('should be a spec', function () {
bar = 1;
foo++;
});
});
expect(foo).toEqual(0);
expect(bar).toEqual(0);
suiteWithBefore.execute();
expect(bar).toEqual(0);
expect(foo).toEqual(1);
fakeTimer.tick(500);
expect(bar).toEqual(0);
expect(foo).toEqual(2);
fakeTimer.tick(500);
expect(bar).toEqual(1);
expect(foo).toEqual(3);
});
it("#afterEach should be able to eval runs and waits blocks", function () {
var foo = 0;
var firstSpecHasRun = false;
var secondSpecHasRun = false;
var suiteWithAfter = env.describe('one suite with a before', function () {
this.afterEach(function () {
this.waits(500);
this.runs(function () {
foo++;
});
this.waits(500);
});
env.it('should be the first spec', function () {
firstSpecHasRun = true;
});
env.it('should be a spec', function () {
secondSpecHasRun = true;
foo++;
});
});
expect(firstSpecHasRun).toEqual(false);
expect(secondSpecHasRun).toEqual(false);
expect(foo).toEqual(0);
suiteWithAfter.execute();
expect(firstSpecHasRun).toEqual(true);
expect(secondSpecHasRun).toEqual(false);
expect(foo).toEqual(0);
fakeTimer.tick(500);
expect(foo).toEqual(1);
expect(secondSpecHasRun).toEqual(false);
fakeTimer.tick(500);
expect(foo).toEqual(2);
expect(secondSpecHasRun).toEqual(true);
});
it("Spec#after should be able to eval runs and waits blocks", function () {
var runsBeforeAfter = false;
var firstSpecHasRun = false;
var secondSpecHasRun = false;
var afterHasRun = false;
var suiteWithAfter = env.describe('one suite with a before', function () {
env.it('should be the first spec', function () {
firstSpecHasRun = true;
this.after(function () {
this.waits(500);
this.runs(function () {
afterHasRun = true;
});
this.waits(500);
}, true);
this.waits(500);
this.runs(function () {
runsBeforeAfter = true;
});
});
env.it('should be a spec', function () {
secondSpecHasRun = true;
});
});
expect(firstSpecHasRun).toEqual(false);
expect(runsBeforeAfter).toEqual(false);
expect(afterHasRun).toEqual(false);
expect(secondSpecHasRun).toEqual(false);
suiteWithAfter.execute();
expect(firstSpecHasRun).toEqual(true);
expect(runsBeforeAfter).toEqual(false);
expect(afterHasRun).toEqual(false);
expect(secondSpecHasRun).toEqual(false);
fakeTimer.tick(500);
expect(firstSpecHasRun).toEqual(true);
expect(runsBeforeAfter).toEqual(true);
expect(afterHasRun).toEqual(false);
expect(secondSpecHasRun).toEqual(false);
fakeTimer.tick(500);
expect(firstSpecHasRun).toEqual(true);
expect(runsBeforeAfter).toEqual(true);
expect(afterHasRun).toEqual(true);
expect(secondSpecHasRun).toEqual(false);
fakeTimer.tick(500);
expect(firstSpecHasRun).toEqual(true);
expect(runsBeforeAfter).toEqual(true);
expect(afterHasRun).toEqual(true);
expect(secondSpecHasRun).toEqual(true);
});
it("handles waits", function () {
var firstSpecHasRun = false;
var secondSpecHasRun = false;
var suiteWithAfter = env.describe('one suite with a before', function () {
env.it('should be the first spec', function () {
this.waits(500);
this.runs(function () {
firstSpecHasRun = true;
});
});
env.it('should be a spec', function () {
secondSpecHasRun = true;
});
});
expect(firstSpecHasRun).toEqual(false);
expect(secondSpecHasRun).toEqual(false);
suiteWithAfter.execute();
expect(firstSpecHasRun).toEqual(false);
expect(secondSpecHasRun).toEqual(false);
fakeTimer.tick(500);
expect(firstSpecHasRun).toEqual(true);
expect(secondSpecHasRun).toEqual(true);
});
it("should permit nested describes", function() {
var actions = [];
@@ -962,43 +225,6 @@ describe("jasmine spec running", function () {
expect(actions).toEqual(expected);
});
it("builds up nested names", function() {
var nestedSpec;
env.describe('Test Subject', function() {
env.describe('when under circumstance A', function() {
env.describe('and circumstance B', function() {
nestedSpec = env.it('behaves thusly', function() {
});
});
});
});
expect(nestedSpec.getFullName()).toEqual('Test Subject when under circumstance A and circumstance B behaves thusly.'); //, "Spec.fullName was incorrect: " + nestedSpec.getFullName());
});
it("should bind 'this' to the running spec within the spec body", function() {
var specExecuted = jasmine.createSpy(), spec;
env.describe('Test Subject', function() {
spec = env.it('should be a test with queuedFunctions', function() {
this.runs(function() {
this.foo = 0;
expect(this.foo).toBe(0);
specExecuted();
});
this.runs(function() {
this.foo++;
expect(this.foo).toBe(1);
specExecuted();
});
});
});
spec.execute();
expect(specExecuted.callCount).toBe(2);
});
it("shouldn't run disabled tests", function() {
var disabledSpec = originalJasmine.createSpy('disabledSpec'),
suite = env.describe('default current suite', function() {
@@ -1008,35 +234,11 @@ describe("jasmine spec running", function () {
expect(disabledSpec).not.toHaveBeenCalled();
});
it('#explodes should throw an exception when it is called inside a spec', function() {
var exceptionMessage = false;
var anotherSuite = env.describe('Spec', function () {
env.it('plodes', function() {
try {
this.explodes();
}
catch (e) {
exceptionMessage = e;
}
expect(exceptionMessage).toNotEqual(false);
});
});
anotherSuite.execute();
expect(exceptionMessage).toEqual('explodes function should not have been called');
});
it("should recover gracefully when there are errors in describe functions", function() {
var specs = [];
var superSimpleReporter = new jasmine.Reporter();
superSimpleReporter.reportSpecResults = function(spec) {
specs.push("Spec: " + spec.getFullName());
var results = spec.results().getItems();
for (var i = 0; i < results.length; i++) {
var result = results[i];
specs.push("Result: " + result.message);
}
superSimpleReporter.reportSpecResults = function(result) {
specs.push("Spec: " + result.fullName);
};
try {
@@ -1072,16 +274,12 @@ describe("jasmine spec running", function () {
expect(specs.join('')).toMatch(new RegExp(
'Spec: outer1 inner1 should thingy.' +
'Result: Passed.' +
'Spec: outer1 inner1 encountered a declaration exception.' +
'Result: Error: fake error.*' +
'Spec: outer1 inner2 should other thingy.' +
'Result: Passed.' +
'Spec: outer1 encountered a declaration exception.' +
'Result: Error: fake error.*' +
'Spec: outer2 should xxx.' +
'Result: Passed.'
));
'Spec: outer1 inner1 encountered a declaration exception.' +
'Spec: outer1 inner2 should other thingy.' +
'Spec: outer1 encountered a declaration exception.' +
'Spec: outer2 should xxx.'
));
});
});

View File

@@ -1,122 +1,202 @@
describe('Spec', function () {
var env, suite;
beforeEach(function() {
env = new jasmine.Env();
env.updateInterval = 0;
suite = new jasmine.Suite(env, 'suite 1');
describe("Spec (integration)", function() {
it("reports results for passing tests", function() {
var resultCallback = jasmine.createSpy('resultCallback'),
expectationFactory = function(actual, spec) {
expect(actual).toBe('some-actual');
return {
pass: function() {
spec.addExpectationResult(true);
}
}
},
spec = new jasmine.Spec({
description: 'my test',
id: 'some-id',
fn: function() {
this.expect('some-actual').pass();
},
resultCallback: resultCallback,
expectationFactory: expectationFactory
});
spec.execute();
expect(resultCallback).toHaveBeenCalledWith({
id: "some-id",
status: "passed",
description: "my test",
failedExpectations: []
});
});
it("reports results for failing tests", function() {
var resultCallback = jasmine.createSpy('resultCallback'),
expectationFactory = function(actual, spec) {
expect(actual).toBe('some-actual');
return {
fail: function() {
spec.addExpectationResult(true);
}
}
},
spec = new jasmine.Spec({
description: 'my test',
id: 'some-id',
fn: function() {
this.expect('some-actual').fail();
},
resultCallback: resultCallback,
expectationFactory: expectationFactory
});
describe('initialization', function () {
spec.execute();
it('should raise an error if an env is not passed', function () {
try {
new jasmine.Spec();
}
catch (e) {
expect(e.message).toEqual('jasmine.Env() required');
}
});
it('should raise an error if a suite is not passed', function () {
try {
new jasmine.Spec(env);
}
catch (e) {
expect(e.message).toEqual('jasmine.Suite() required');
}
});
it('should assign sequential ids for specs belonging to the same env', function () {
var spec1 = new jasmine.Spec(env, suite);
var spec2 = new jasmine.Spec(env, suite);
var spec3 = new jasmine.Spec(env, suite);
expect(spec1.id).toEqual(0);
expect(spec2.id).toEqual(1);
expect(spec3.id).toEqual(2);
expect(resultCallback).toHaveBeenCalledWith({
id: "some-id",
status: "passed",
description: "my test",
failedExpectations: []
});
});
it('getFullName returns suite & spec description', function () {
var spec = new jasmine.Spec(env, suite, 'spec 1');
expect(spec.getFullName()).toEqual('suite 1 spec 1.');
});
describe('results', function () {
var spec, results;
beforeEach(function () {
spec = new jasmine.Spec(env, suite);
results = spec.results();
expect(results.totalCount).toEqual(0);
spec.runs(function () {
this.expect(true).toEqual(true);
this.expect(true).toEqual(true);
//TODO: test order of befores, spec, after.
it("executes before fns, after fns", function() {
var before = jasmine.createSpy('before'),
after = jasmine.createSpy('after'),
fn = originalJasmine.createSpy('test body').andCallFake(function() {
expect(before).toHaveBeenCalled();
expect(after).not.toHaveBeenCalled();
});
spec = new jasmine.Spec({
fn: fn,
beforeFns: function() {
return [before]
},
afterFns: function() {
return [after]
}
});
spec.execute();
it('results shows the total number of expectations for each spec after execution', function () {
expect(results.totalCount).toEqual(0);
spec.execute();
expect(results.totalCount).toEqual(2);
});
expect(before).toHaveBeenCalled();
expect(before.mostRecentCall.object).toBe(spec);
it('results shows the number of passed expectations for each spec after execution', function () {
expect(results.passedCount).toEqual(0);
spec.execute();
expect(results.passedCount).toEqual(2);
});
expect(fn).toHaveBeenCalled();
it('results shows the number of failed expectations for each spec after execution', function () {
spec.runs(function () {
this.expect(true).toEqual(false);
});
expect(results.failedCount).toEqual(0);
spec.execute();
expect(results.failedCount).toEqual(1);
});
describe('results.passed', function () {
it('is true if all spec expectations pass', function () {
spec.runs(function () {
this.expect(true).toEqual(true);
});
spec.execute();
expect(results.passed()).toEqual(true);
});
it('is false if one spec expectation fails', function () {
spec.runs(function () {
this.expect(true).toEqual(false);
});
spec.execute();
expect(results.passed()).toEqual(false);
});
it('a spec with no expectations will return true', function () {
var specWithoutExpectations = new jasmine.Spec(env, suite);
specWithoutExpectations.runs(function() {
});
specWithoutExpectations.execute();
expect(results.passed()).toEqual(true);
});
it('an unexecuted spec will return true', function () {
expect(results.passed()).toEqual(true);
});
});
it("includes log messages, which may contain arbitary objects", function() {
spec.runs(function() {
this.log("here's some log message", {key: 'value'}, 123);
});
spec.execute();
var items = results.getItems();
expect(items[0].type).toBe('expect');
expect(items[1].type).toBe('expect');
expect(items[2].type).toBe('log');
var logResult = items[2];
expect(logResult.values).toEqual(["here's some log message", {key: 'value'}, 123]);
});
expect(after).toHaveBeenCalled();
expect(after.mostRecentCall.object).toBe(spec);
});
});
describe("Spec (real-ish unit tests)", function() {
it("status returns null by default", function() {
var spec = new jasmine.Spec({});
expect(spec.status()).toBeNull();
});
it("status returns passed if all expectations in the spec have passed", function() {
var spec = new jasmine.Spec({});
spec.addExpectationResult(true);
expect(spec.status()).toBe('passed');
});
it("status returns failed if any expectations in the spec have failed", function() {
var spec = new jasmine.Spec({});
spec.addExpectationResult(true);
spec.addExpectationResult(false);
expect(spec.status()).toBe('failed');
});
it("calls the resultCallback with a failure when an exception occurs in the spec fn", function() {
//TODO: one day we should pass a stack with this.
var resultCallback = originalJasmine.createSpy('resultCallback'),
spec = new jasmine.Spec({
fn: function() {
throw new Error();
},
catchExceptions: true,
resultCallback: resultCallback
});
expect(resultCallback).not.toHaveBeenCalled();
spec.execute();
expect(resultCallback).toHaveBeenCalledWith(
originalJasmine.objectContaining({status: 'failed'})
);
});
it("throws when an exception occurs in the spec fn if catchExceptions is false", function() {
//TODO: one day we should pass a stack with this.
var resultCallback = originalJasmine.createSpy('resultCallback'),
spec = new jasmine.Spec({
fn: function() {
throw new Error();
},
catchExceptions: false,
resultCallback: resultCallback
});
expect(function() {
spec.execute();
}).toThrow();
});
it("should call the start callback before any befores are called", function() {
var beforesWereCalled = false,
startCallback = originalJasmine.createSpy('start-callback').andCallFake(function() {
expect(beforesWereCalled).toBe(false);
}),
spec = new jasmine.Spec({
fn: function() {
},
beforeFns: function() {
return [function() {
beforesWereCalled = true
}]
},
startCallback: startCallback,
catchExceptions: false,
resultCallback: function() {
}
});
spec.execute();
expect(startCallback).toHaveBeenCalled();
});
it("can return its full name", function() {
//TODO: not convinced that a spec should provide this as part of its public interface, but adding temporarily
//until we fix the reporting
var spec = new jasmine.Spec({
fullNameFactory: function(passedVal) {
expect(passedVal).toBe(spec);
return 'expected val';
}
});
expect(spec.getFullName()).toBe('expected val');
});
it("can be disabled", function() {
var startCallback = jasmine.createSpy('startCallback'),
specBody = jasmine.createSpy('specBody'),
resultCallback = jasmine.createSpy('resultCallback'),
spec = new jasmine.Spec({
startCallback: startCallback,
fn: specBody,
resultCallback: resultCallback
});
spec.disable();
expect(spec.status()).toBe('disabled');
spec.execute();
expect(startCallback).not.toHaveBeenCalled();
expect(specBody).not.toHaveBeenCalled();
//TODO: with expected data.
expect(resultCallback).toHaveBeenCalled();
});
});

View File

@@ -1,4 +1,9 @@
describe('Spies', function () {
var env;
beforeEach(function() {
env = new jasmine.Env();
});
it('should replace the specified function with a spy object', function() {
var originalFunctionWasCalled = false;
var TestClass = {
@@ -6,11 +11,13 @@ describe('Spies', function () {
originalFunctionWasCalled = true;
}
};
this.spyOn(TestClass, 'someFunction');
env.spyOn(TestClass, 'someFunction');
expect(TestClass.someFunction.wasCalled).toEqual(false);
expect(TestClass.someFunction.callCount).toEqual(0);
TestClass.someFunction('foo');
expect(TestClass.someFunction.wasCalled).toEqual(true);
expect(TestClass.someFunction.callCount).toEqual(1);
expect(TestClass.someFunction.mostRecentCall.args).toEqual(['foo']);
@@ -29,7 +36,7 @@ describe('Spies', function () {
originalFunctionWasCalled = true;
}
};
this.spyOn(TestClass, 'someFunction');
env.spyOn(TestClass, 'someFunction');
TestClass.someFunction('foo');
TestClass.someFunction('bar');
@@ -51,7 +58,7 @@ describe('Spies', function () {
}
};
this.spyOn(TestClass, 'someFunction').andCallThrough();
env.spyOn(TestClass, 'someFunction').andCallThrough();
var result = TestClass.someFunction('arg1', 'arg2');
expect(result).toEqual("return value from original function");
expect(originalFunctionWasCalled).toEqual(true);
@@ -69,7 +76,7 @@ describe('Spies', function () {
}
};
this.spyOn(TestClass, 'someFunction').andReturn("some value");
env.spyOn(TestClass, 'someFunction').andReturn("some value");
originalFunctionWasCalled = false;
var result = TestClass.someFunction('arg1', 'arg2');
expect(result).toEqual("some value");
@@ -85,7 +92,7 @@ describe('Spies', function () {
}
};
this.spyOn(TestClass, 'someFunction').andThrow(new Error('fake error'));
env.spyOn(TestClass, 'someFunction').andThrow(new Error('fake error'));
var exception;
try {
TestClass.someFunction('arg1', 'arg2');
@@ -108,7 +115,7 @@ describe('Spies', function () {
}
};
this.spyOn(TestClass, 'someFunction').andCallFake(function() {
env.spyOn(TestClass, 'someFunction').andCallFake(function() {
fakeFunctionWasCalled = true;
passedArgs = arguments;
passedObj = this;
@@ -124,41 +131,54 @@ describe('Spies', function () {
expect(TestClass.someFunction.wasCalled).toEqual(true);
});
it('is torn down when this.removeAllSpies is called', function() {
var originalFunctionWasCalled = false;
var TestClass = {
it('is torn down when env.removeAllSpies is called', function() {
var originalFunctionWasCalled = false,
env = new jasmine.Env(),
TestClass = {
someFunction: function() {
originalFunctionWasCalled = true;
}
};
this.spyOn(TestClass, 'someFunction');
env.spyOn(TestClass, 'someFunction');
TestClass.someFunction('foo');
expect(originalFunctionWasCalled).toEqual(false);
this.removeAllSpies();
env.removeAllSpies();
TestClass.someFunction('foo');
expect(originalFunctionWasCalled).toEqual(true);
});
it('calls removeAllSpies during spec finish', function() {
var test = new jasmine.Spec(new jasmine.Env(), {}, 'sample test');
var env = new jasmine.Env(),
originalFoo = function() {},
testObj = {
foo: originalFoo
},
firstSpec = originalJasmine.createSpy('firstSpec').andCallFake(function() {
env.spyOn(testObj, 'foo');
}),
secondSpec = originalJasmine.createSpy('secondSpec').andCallFake(function() {
expect(testObj.foo).toBe(originalFoo);
});
env.describe('test suite', function() {
env.it('spec 0', firstSpec);
env.it('spec 1', secondSpec);
});
this.spyOn(test, 'removeAllSpies');
test.finish();
expect(test.removeAllSpies).wasCalled();
env.execute();
expect(firstSpec).toHaveBeenCalled();
expect(secondSpec).toHaveBeenCalled();
});
it('throws an exception when some method is spied on twice', function() {
var TestClass = { someFunction: function() {
} };
this.spyOn(TestClass, 'someFunction');
env.spyOn(TestClass, 'someFunction');
var exception;
try {
this.spyOn(TestClass, 'someFunction');
env.spyOn(TestClass, 'someFunction');
} catch (e) {
exception = e;
}
@@ -166,23 +186,23 @@ describe('Spies', function () {
});
it('to spy on an undefined method throws exception', function() {
var TestClass = {
someFunction : function() {
}
};
function efunc() {
this.spyOn(TestClass, 'someOtherFunction');
};
expect(function() {
efunc();
}).toThrow('someOtherFunction() method does not exist');
it('to spy on an undefined method throws exception', function() {
var TestClass = {
someFunction : function() {
}
};
function efunc() {
env.spyOn(TestClass, 'someOtherFunction');
};
expect(function() {
efunc();
}).toThrow('someOtherFunction() method does not exist');
});
});
it('should be able to reset a spy', function() {
var TestClass = { someFunction: function() {} };
this.spyOn(TestClass, 'someFunction');
env.spyOn(TestClass, 'someFunction');
expect(TestClass.someFunction).not.toHaveBeenCalled();
TestClass.someFunction();

View File

@@ -1,118 +0,0 @@
describe('WaitsForBlock', function () {
var env, suite, timeout, spec, message, onComplete, fakeTimer;
beforeEach(function() {
env = new jasmine.Env();
env.updateInterval = 0;
suite = new jasmine.Suite(env, 'suite 1');
timeout = 1000;
spec = new jasmine.Spec(env, suite);
message = "some error message";
onComplete = originalJasmine.createSpy("onComplete");
});
describe("jasmine.VERBOSE", function() {
var jasmineVerboseOriginal;
beforeEach(function() {
jasmineVerboseOriginal = jasmine.VERBOSE;
spyOn(env.reporter, 'log');
});
it('do not show information if jasmine.VERBOSE is set to false', function () {
jasmine.VERBOSE = false;
var latchFunction = function() {
return true;
};
var block = new jasmine.WaitsForBlock(env, timeout, latchFunction, message, spec);
expect(env.reporter.log).not.toHaveBeenCalled();
block.execute(onComplete);
expect(env.reporter.log).not.toHaveBeenCalled();
jasmine.VERBOSE = jasmineVerboseOriginal;
});
it('show information if jasmine.VERBOSE is set to true', function () {
jasmine.VERBOSE = true;
var latchFunction = function() {
return true;
};
var block = new jasmine.WaitsForBlock(env, timeout, latchFunction, message, spec);
expect(env.reporter.log).not.toHaveBeenCalled();
block.execute(onComplete);
expect(env.reporter.log).toHaveBeenCalled();
jasmine.VERBOSE = jasmineVerboseOriginal;
});
});
it('onComplete should be called if the latchFunction returns true', function () {
var latchFunction = function() {
return true;
};
var block = new jasmine.WaitsForBlock(env, timeout, latchFunction, message, spec);
expect(onComplete).not.toHaveBeenCalled();
block.execute(onComplete);
expect(onComplete).toHaveBeenCalled();
});
it('latchFunction should run in same scope as spec', function () {
var result;
var latchFunction = function() {
result = this.scopedValue;
};
spec.scopedValue = 'foo';
var block = new jasmine.WaitsForBlock(env, timeout, latchFunction, message, spec);
block.execute(onComplete);
expect(result).toEqual('foo');
});
it('should fail spec and call onComplete if there is an error in the latchFunction', function() {
var latchFunction = originalJasmine.createSpy('latchFunction').andThrow('some error');
spyOn(spec, 'fail');
var block = new jasmine.WaitsForBlock(env, timeout, latchFunction, message, spec);
block.execute(onComplete);
expect(spec.fail).toHaveBeenCalledWith('some error');
expect(onComplete).toHaveBeenCalled();
});
describe("if latchFunction returns false", function() {
var latchFunction, fakeTimer;
beforeEach(function() {
latchFunction = originalJasmine.createSpy('latchFunction').andReturn(false);
fakeTimer = new jasmine.FakeTimer();
env.setTimeout = fakeTimer.setTimeout;
env.clearTimeout = fakeTimer.clearTimeout;
env.setInterval = fakeTimer.setInterval;
env.clearInterval = fakeTimer.clearInterval;
});
it('latchFunction should be retried after 10 ms', function () {
var block = new jasmine.WaitsForBlock(env, timeout, latchFunction, message, spec);
expect(latchFunction).not.toHaveBeenCalled();
block.execute(onComplete);
expect(latchFunction.callCount).toEqual(1);
fakeTimer.tick(5);
expect(latchFunction.callCount).toEqual(1);
fakeTimer.tick(5);
expect(latchFunction.callCount).toEqual(2);
});
it('onComplete should be called if latchFunction returns true before timeout', function () {
var block = new jasmine.WaitsForBlock(env, timeout, latchFunction, message, spec);
expect(onComplete).not.toHaveBeenCalled();
block.execute(onComplete);
expect(onComplete).not.toHaveBeenCalled();
latchFunction.andReturn(true);
fakeTimer.tick(100);
expect(onComplete).toHaveBeenCalled();
});
it('spec should fail with the passed message if the timeout is reached (and not call onComplete)', function () {
spyOn(spec, 'fail');
var block = new jasmine.WaitsForBlock(env, timeout, latchFunction, message, spec);
block.execute(onComplete);
expect(spec.fail).not.toHaveBeenCalled();
fakeTimer.tick(timeout);
expect(spec.fail).toHaveBeenCalled();
var failMessage = spec.fail.mostRecentCall.args[0].message;
expect(failMessage).toMatch(message);
expect(onComplete).toHaveBeenCalled();
});
});
});

View File

@@ -76,21 +76,19 @@ describe("HtmlReporter", function() {
env.clearTimeout = fakeTimer.clearTimeout;
env.setInterval = fakeTimer.setInterval;
env.clearInterval = fakeTimer.clearInterval;
runner = env.currentRunner();
var suite = new jasmine.Suite(env, 'some suite');
runner.add(suite);
spec = new jasmine.Spec(env, suite, 'some spec');
suite.add(spec);
fakeDocument.location.search = "?";
env.addReporter(htmlReporter);
});
describe('toContain', function() {
it('should show actual and expected', function() {
spec.runs(function() {
this.expect('foo').toContain('bar');
env.describe('test suite', function() {
env.it('spec 0', function() {
this.expect('foo').toContain('bar');
});
});
runner.execute();
env.execute();
fakeTimer.tick(0);
var resultEl = getResultMessageDiv(body);
@@ -134,39 +132,16 @@ describe("HtmlReporter", function() {
});
});
describe("log messages", function() {
it("should appear in the report of a failed spec", function() {
env.describe("suite", function() {
env.it("will have log messages", function() {
this.log("this is a", "multipart log message");
this.expect(true).toBeFalsy();
});
});
env.addReporter(htmlReporter);
env.execute();
var divs = body.getElementsByTagName("div");
var errorDiv = findElement(divs, 'specDetail failed');
expect(errorDiv.innerHTML).toMatch("this is a multipart log message");
});
xit("should work on IE without console.log.apply", function() {
});
});
describe("duplicate example names", function() {
it("should report failures correctly", function() {
var suite1 = env.describe("suite", function() {
env.it("will have log messages", function() {
this.log("this one fails!");
this.expect(true).toBeFalsy();
});
});
var suite2 = env.describe("suite", function() {
env.it("will have log messages", function() {
this.log("this one passes!");
this.expect(true).toBeTruthy();
});
});
@@ -177,33 +152,7 @@ describe("HtmlReporter", function() {
var divs = body.getElementsByTagName("div");
var failedSpecDiv = findElement(divs, 'specDetail failed');
expect(failedSpecDiv.className).toEqual('specDetail failed');
expect(failedSpecDiv.innerHTML).toContain("this one fails!");
expect(failedSpecDiv.innerHTML).not.toContain("this one passes!");
});
});
describe('#reportSpecStarting', function() {
beforeEach(function() {
env.describe("suite 1", function() {
env.it("spec 1", function() {
});
});
spyOn(htmlReporter, 'log').andCallThrough();
});
it('DOES NOT log running specs by default', function() {
env.addReporter(htmlReporter);
env.execute();
expect(htmlReporter.log).not.toHaveBeenCalled();
});
it('logs running specs when log_running_specs is true', function() {
htmlReporter.logRunningSpecs = true;
env.addReporter(htmlReporter);
env.execute();
expect(htmlReporter.log).toHaveBeenCalledWith('>> Jasmine Running suite 1 spec 1...');
});
});
});

View File

@@ -9,9 +9,9 @@ describe("MatchersSpec - HTML Dependent", function () {
spec = env.it("spec", function() {
});
});
spyOn(spec, 'addMatcherResult');
spyOn(spec, 'addExpectationResult');
this.addMatchers({
addMatchers({
toPass: function() {
return lastResult().passed;
},
@@ -26,7 +26,7 @@ describe("MatchersSpec - HTML Dependent", function () {
}
function lastResult() {
return spec.addMatcherResult.mostRecentCall.args[0];
return spec.addExpectationResult.mostRecentCall.args[1];
}
it("toEqual with DOM nodes", function() {

View File

@@ -7,8 +7,8 @@ src_files:
- 'core/util.js'
- 'core/Reporter.js'
#end of known dependencies
- 'core/Spec.js'
- 'core/Env.js'
- 'core/Block.js'
- 'core/JsApiReporter.js'
- 'core/Matchers.js'
- 'core/mock-timeout.js'
@@ -17,10 +17,7 @@ src_files:
- 'core/PrettyPrinter.js'
- 'core/Queue.js'
- 'core/Runner.js'
- 'core/Spec.js'
- 'core/Suite.js'
- 'core/WaitsBlock.js'
- 'core/WaitsForBlock.js'
- 'html/HtmlReporterHelpers.js'
- 'html/HtmlReporter.js'
- '**/*.js'

View File

@@ -10,6 +10,53 @@ var jasmineGlobals = require('../lib/jasmine-core/jasmine.js');
for (var k in jasmineGlobals) {
global[k] = jasmineGlobals[k];
}
var env = jasmine.getEnv();
var jasmineInterface = {
describe: function(description, specDefinitions) {
return env.describe(description, specDefinitions);
},
xdescribe: function(description, specDefinitions) {
return env.xdescribe(description, specDefinitions);
},
it: function(desc, func) {
return env.it(desc, func);
},
xit: function(desc, func) {
return env.xit(desc, func);
},
beforeEach: function(beforeEachFunction) {
return env.beforeEach(beforeEachFunction);
},
afterEach: function(afterEachFunction) {
return env.afterEach(afterEachFunction);
},
expect: function(actual) {
return env.expect(actual);
},
addMatchers: function(matchers) {
return env.addMatchers(matchers);
},
spyOn: function(obj, methodName) {
return env.spyOn(obj, methodName);
},
jsApiReporter: new jasmine.JsApiReporter(jasmine)
};
for (var k in jasmineInterface) {
global[k] = jasmineInterface[k];
}
require('../src/console/ConsoleReporter.js');
/*
@@ -31,6 +78,8 @@ function noop() {
}
jasmine.executeSpecs = function(specs, done, isVerbose, showColors) {
global.originalJasmine = jasmine;
for (var i = 0, len = specs.length; i < len; ++i) {
var filename = specs[i];
require(filename.replace(/\.\w+$/, ""));
@@ -118,8 +167,8 @@ for (var i = 0; i < specs.length; i++) {
}
}
jasmine.executeSpecs(domIndependentSpecs, function(runner, log) {
if (runner.results().failedCount === 0) {
jasmine.executeSpecs(domIndependentSpecs, function(passed) {
if (passed) {
process.exit(0);
} else {
process.exit(1);

View File

@@ -1,83 +1,54 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Jasmine Spec Runner: Jasmine Core</title>
<title>Jasmine Spec Runner: Jasmine Core</title>
<link rel="shortcut icon" type="image/png" href="../images/jasmine_favicon.png">
<link rel="shortcut icon" type="image/png" href="../images/jasmine_favicon.png">
<link href="../lib/jasmine-core/jasmine.css" rel="stylesheet"/>
<script type="text/javascript" src="../lib/jasmine-core/jasmine.js"></script>
<script type="text/javascript">
// yes, really keep this here to keep us honest, but only for jasmine's own runner! [xw]
undefined = "diz be undefined yo";
</script>
<link href="../lib/jasmine-core/jasmine.css" rel="stylesheet"/>
<script type="text/javascript" src="../lib/jasmine-core/jasmine.js"></script>
<script type="text/javascript" src="../lib/jasmine-core/jasmine-html.js"></script>
<script type="text/javascript" src="../lib/jasmine-core/boot/boot.js"></script>
<!-- include source files here... -->
<script type="text/javascript" src=".././src/html/HtmlReporterHelpers.js"></script>
<script type="text/javascript" src=".././src/html/HtmlReporter.js"></script>
<script type="text/javascript" src=".././src/html/HtmlReporterHelpers.js"></script>
<script type="text/javascript" src=".././src/html/ReporterView.js"></script>
<script type="text/javascript" src=".././src/html/SpecView.js"></script>
<script type="text/javascript" src=".././src/html/SuiteView.js"></script>
<script type="text/javascript" src=".././src/console/ConsoleReporter.js"></script>
<!--This file is not included in jasmine.js - but let's put it here for now -->
<script type="text/javascript" src="../src/console/ConsoleReporter.js"></script>
<!-- include spec files here... -->
<script type="text/javascript" src=".././spec/core/BaseSpec.js"></script>
<script type="text/javascript" src=".././spec/core/CustomMatchersSpec.js"></script>
<script type="text/javascript" src=".././spec/core/EnvSpec.js"></script>
<script type="text/javascript" src=".././spec/core/ExceptionsSpec.js"></script>
<script type="text/javascript" src=".././spec/core/ExpectationResultSpec.js"></script>
<script type="text/javascript" src=".././spec/core/JsApiReporterSpec.js"></script>
<script type="text/javascript" src=".././spec/core/MatchersSpec.js"></script>
<script type="text/javascript" src=".././spec/core/MockClockSpec.js"></script>
<script type="text/javascript" src=".././spec/core/MultiReporterSpec.js"></script>
<script type="text/javascript" src=".././spec/core/NestedResultsSpec.js"></script>
<script type="text/javascript" src=".././spec/core/PrettyPrintSpec.js"></script>
<script type="text/javascript" src=".././spec/core/QueueSpec.js"></script>
<script type="text/javascript" src=".././spec/core/ReporterSpec.js"></script>
<script type="text/javascript" src=".././spec/core/RunnerSpec.js"></script>
<script type="text/javascript" src=".././spec/core/SpecRunningSpec.js"></script>
<script type="text/javascript" src=".././spec/core/SpecSpec.js"></script>
<script type="text/javascript" src=".././spec/core/SpySpec.js"></script>
<script type="text/javascript" src=".././spec/core/SuiteSpec.js"></script>
<script type="text/javascript" src=".././spec/core/UtilSpec.js"></script>
<script type="text/javascript" src=".././spec/core/WaitsForBlockSpec.js"></script>
<script type="text/javascript" src=".././spec/html/HTMLReporterSpec.js"></script>
<script type="text/javascript" src=".././spec/html/MatchersHtmlSpec.js"></script>
<script type="text/javascript" src=".././spec/html/PrettyPrintHtmlSpec.js"></script>
<script type="text/javascript" src=".././spec/console/ConsoleReporterSpec.js"></script>
<script type="text/javascript">
//shim for our tests using originalJasmine.createSpy and the like that should really be using globals defined in boot.
var originalJasmine = jasmine;
</script>
<script type="text/javascript">
(function() {
var jasmineEnv = jasmine.getEnv();
jasmineEnv.updateInterval = 1000;
<script type="text/javascript">
// yes, really keep this here to keep us honest, but only for jasmine's own runner! [xw]
undefined = "diz be undefined yo";
</script>
var htmlReporter = new jasmine.HtmlReporter();
jasmineEnv.addReporter(htmlReporter);
jasmineEnv.specFilter = function(spec) {
return htmlReporter.specFilter(spec);
};
var currentWindowOnload = window.onload;
window.onload = function() {
if (currentWindowOnload) {
currentWindowOnload();
}
execJasmine();
};
function execJasmine() {
jasmineEnv.execute();
}
})();
</script>
<!-- include spec files here... -->
<script type="text/javascript" src=".././spec/core/BaseSpec.js"></script>
<script type="text/javascript" src=".././spec/core/CustomMatchersSpec.js"></script>
<script type="text/javascript" src=".././spec/core/EnvSpec.js"></script>
<script type="text/javascript" src=".././spec/core/ExceptionsSpec.js"></script>
<script type="text/javascript" src=".././spec/core/ExpectationResultSpec.js"></script>
<script type="text/javascript" src=".././spec/core/JsApiReporterSpec.js"></script>
<script type="text/javascript" src=".././spec/core/MatchersSpec.js"></script>
<script type="text/javascript" src=".././spec/core/MockClockSpec.js"></script>
<script type="text/javascript" src=".././spec/core/MultiReporterSpec.js"></script>
<script type="text/javascript" src=".././spec/core/NestedResultsSpec.js"></script>
<script type="text/javascript" src=".././spec/core/PrettyPrintSpec.js"></script>
<script type="text/javascript" src=".././spec/core/ReporterSpec.js"></script>
<script type="text/javascript" src=".././spec/core/RunnerSpec.js"></script>
<script type="text/javascript" src=".././spec/core/SpecRunningSpec.js"></script>
<script type="text/javascript" src=".././spec/core/SpecSpec.js"></script>
<script type="text/javascript" src=".././spec/core/SpySpec.js"></script>
<script type="text/javascript" src=".././spec/core/SuiteSpec.js"></script>
<script type="text/javascript" src=".././spec/core/UtilSpec.js"></script>
<script type="text/javascript" src=".././spec/html/HTMLReporterSpec.js"></script>
<script type="text/javascript" src=".././spec/html/MatchersHtmlSpec.js"></script>
<script type="text/javascript" src=".././spec/html/PrettyPrintHtmlSpec.js"></script>
<script type="text/javascript" src=".././spec/console/ConsoleReporterSpec.js"></script>
</head>
<body>

View File

@@ -14,6 +14,7 @@
<%= spec_file_tags %>
<script type="text/javascript">
//hello
(function() {
var jasmineEnv = jasmine.getEnv();
jasmineEnv.updateInterval = 1000;

View File

@@ -73,12 +73,22 @@ jasmine.ConsoleReporter = function(print, doneCallback, showColors) {
return newArr.join("\n");
}
function specFailureDetails(suiteDescription, specDescription, stackTraces) {
// function specFailureDetails(suiteDescription, specDescription, stackTraces) {
// newline();
// print(suiteDescription + " " + specDescription);
// newline();
// for (var i = 0; i < stackTraces.length; i++) {
// print(indent(stackTraces[i], 2));
// newline();
// }
// }
function specFailureDetails(specFailure) {
newline();
print(suiteDescription + " " + specDescription);
print(specFailure.fullName);
newline();
for (var i = 0; i < stackTraces.length; i++) {
print(indent(stackTraces[i], 2));
for (var i = 0; i < specFailure.failedExpectations.length; i++) {
var failedExpectation = specFailure.failedExpectations[i];
print(indent(failedExpectation.trace.stack, 2));
newline();
}
}
@@ -122,33 +132,48 @@ jasmine.ConsoleReporter = function(print, doneCallback, showColors) {
this.reportSpecStarting = function() { /* do nothing */
};
this.reportSpecResults = function(spec) {
var results = spec.results();
if (results.skipped) {
this.specFailures = [];
this.specCount = 0;
this.reportSpecResults = function(result) {
this.specCount++;
if (result.status === 'disabled') {
yellowStar();
} else if (results.passed()) {
} else if (result.status === 'passed') {
greenDot();
} else {
redF();
this.specFailures.push(result);
}
};
this.suiteResults = [];
// this.suiteResults = [];
this.reportSuiteResults = function(suite) {
var suiteResult = {
description: fullSuiteDescription(suite),
failedSpecResults: []
};
// var suiteResult = {
// description: fullSuiteDescription(suite),
// failedSpecResults: []
// };
suite.results().items_.forEach(function(spec) {
if (spec.failedCount > 0 && spec.description) suiteResult.failedSpecResults.push(spec);
});
// suite.results().items_.forEach(function(spec) {
// if (spec.failedCount > 0 && spec.description) suiteResult.failedSpecResults.push(spec);
// });
this.suiteResults.push(suiteResult);
// this.suiteResults.push(suiteResult);
};
function eachSpecFailure(suiteResults, callback) {
// function eachSpecFailure(suiteResults, callback) {
// for (var i = 0; i < suiteResults.length; i++) {
// var suiteResult = suiteResults[i];
// for (var j = 0; j < suiteResult.failedSpecResults.length; j++) {
// var failedSpecResult = suiteResult.failedSpecResults[j];
// var stackTraces = [];
// for (var k = 0; k < failedSpecResult.items_.length; k++) stackTraces.push(failedSpecResult.items_[k].trace.stack);
// callback(suiteResult.description, failedSpecResult.description, stackTraces);
// }
// }
// }
function eachSpecFailure(specResult, callback) {
for (var i = 0; i < suiteResults.length; i++) {
var suiteResult = suiteResults[i];
for (var j = 0; j < suiteResult.failedSpecResults.length; j++) {
@@ -163,15 +188,14 @@ jasmine.ConsoleReporter = function(print, doneCallback, showColors) {
this.reportRunnerResults = function(runner) {
newline();
eachSpecFailure(this.suiteResults, function(suiteDescription, specDescription, stackTraces) {
specFailureDetails(suiteDescription, specDescription, stackTraces);
});
for (var i = 0; i < this.specFailures.length; i++) {
specFailureDetails(this.specFailures[i]);
}
finished(this.now() - this.runnerStartTime);
var results = runner.results();
var summaryFunction = results.failedCount === 0 ? greenSummary : redSummary;
summaryFunction(runner.specs().length, results.failedCount);
doneCallback(runner);
var summaryFunction = this.specFailures.length === 0 ? greenSummary : redSummary;
summaryFunction(this.specCount, this.specFailures.length);
doneCallback(!!this.specFailures.length);
};
};

View File

@@ -1,27 +0,0 @@
/**
* Blocks are functions with executable code that make up a spec.
*
* @constructor
* @param {jasmine.Env} env
* @param {Function} func
* @param {jasmine.Spec} spec
*/
jasmine.Block = function(env, func, spec) {
this.env = env;
this.func = func;
this.spec = spec;
};
jasmine.Block.prototype.execute = function(onComplete) {
if (!jasmine.CATCH_EXCEPTIONS) {
this.func.apply(this.spec);
}
else {
try {
this.func.apply(this.spec);
} catch (e) {
this.spec.fail(e);
}
}
onComplete();
};

View File

@@ -4,15 +4,18 @@
* @constructor
*/
(function() {
function createSpec(env, suite, description) {
return new jasmine.Spec(env, suite, description);
}
jasmine.Env = function() {
var self = this;
var suiteConstructor = jasmine.Suite;
var isSuite = function(thing) {
return thing instanceof suiteConstructor;
}
this.jasmine = jasmine;
this.currentRunner_ = new jasmine.Runner(this, isSuite);
this.spies_ = [];
this.currentSpec = null;
this.currentSuite = null;
this.currentRunner_ = new jasmine.Runner(this);
this.catchExceptions = jasmine.CATCH_EXCEPTIONS;
this.undefined = jasmine.undefined;
this.reporter = new jasmine.MultiReporter();
@@ -34,6 +37,90 @@
jasmine.util.inherit(this.matchersClass, jasmine.Matchers);
jasmine.Matchers.wrapInto_(jasmine.Matchers.prototype, this.matchersClass);
var expectationFactory = function(actual, spec) {
var expect = new (self.matchersClass)(self, actual, spec);
expect.not = new (self.matchersClass)(self, actual, spec, true);
return expect;
};
var startCallback = function(spec) {
self.currentSpec = spec;
self.reporter.reportSpecStarting(spec);
};
var beforeFns = function(currentSuite) {
return function() {
var befores = [];
for (var suite = currentSuite; suite; suite = suite.parentSuite) {
befores = befores.concat(suite.before_)
}
return befores.concat(self.currentRunner_.before_).reverse();
}
};
var afterFns = function(currentSuite) {
return function() {
var afters = [];
for (var suite = currentSuite; suite; suite = suite.parentSuite) {
afters = afters.concat(suite.after_)
}
return afters.concat(self.currentRunner_.after_)
}
};
var exceptionFormatter = jasmine.util.formatException;
var specConstructor = jasmine.Spec;
// TODO: this deserves a better name (not a Factory the way others are)
var fullNameFactory = function(spec, currentSuite) {
var descriptions = [];
for (var suite = currentSuite; suite; suite = suite.parentSuite) {
descriptions.push(suite.description)
}
descriptions.push(spec.description);
return descriptions.join(' ') + '.';
};
var buildExpectationResult = jasmine.buildExpectationResult;
var expectationResultFactory = function(attrs) {
return buildExpectationResult(attrs);
};
this.specFactory = function(description, fn, suite) {
var spec = new specConstructor({
id: self.nextSpecId(),
beforeFns: beforeFns(suite),
afterFns: afterFns(suite),
expectationFactory: expectationFactory,
exceptionFormatter: exceptionFormatter,
//TODO: move spec creation to more appropriate level and remove this shim
resultCallback: function(result) { self.currentSpec = null; suite.specComplete(result); },
fullNameFactory: function(spec) { return fullNameFactory(spec, suite) },
startCallback: startCallback,
description: description,
catchExceptions: self.catchExceptions,
expectationResultFactory: expectationResultFactory,
fn: fn
});
if (!self.specFilter(spec)) {
spec.disable();
}
return spec;
};
var queueConstructor = jasmine.Queue;
var queueFactory = function() {
return new queueConstructor(self);
};
this.suiteFactory = function(description, specDefinitions) {
return new suiteConstructor(self, description, specDefinitions, self.currentSuite, queueFactory, isSuite);
};
};
@@ -42,22 +129,69 @@
jasmine.Env.prototype.setInterval = jasmine.setInterval;
jasmine.Env.prototype.clearInterval = jasmine.clearInterval;
//TODO: shim Spec addMatchers behavior into Env. Should be rewritten to remove globals, etc.
jasmine.Env.prototype.addMatchers = function(matchersPrototype) {
var parent = this.matchersClass;
var newMatchersClass = function() {
parent.apply(this, arguments);
};
jasmine.util.inherit(newMatchersClass, parent);
jasmine.Matchers.wrapInto_(matchersPrototype, newMatchersClass);
this.matchersClass = newMatchersClass;
};
/**
* @returns an object containing jasmine version build info, if set.
*/
jasmine.Env.prototype.version = function () {
if (jasmine.version_) {
return jasmine.version_;
if (this.jasmine.version_) {
return this.jasmine.version_;
} else {
throw new Error('Version not set');
}
};
jasmine.Env.prototype.expect = function(actual) {
return this.currentSpec.expect(actual);
};
jasmine.Env.prototype.spyOn = function(obj, methodName) {
if (obj == this.undefined) {
throw "spyOn could not find an object to spy upon for " + methodName + "()";
}
if (obj[methodName] === this.undefined) {
throw methodName + '() method does not exist';
}
if (obj[methodName] && obj[methodName].isSpy) {
//TODO?: should this return the current spy? Downside: may cause user confusion about spy state
throw new Error(methodName + ' has already been spied upon');
}
var spyObj = jasmine.createSpy(methodName);
this.spies_.push(spyObj);
spyObj.baseObj = obj;
spyObj.methodName = methodName;
spyObj.originalValue = obj[methodName];
obj[methodName] = spyObj;
return spyObj;
};
jasmine.Env.prototype.removeAllSpies = function() {
for (var i = 0; i < this.spies_.length; i++) {
var spy = this.spies_[i];
spy.baseObj[spy.methodName] = spy.originalValue;
}
this.spies_ = [];
};
/**
* @returns string containing jasmine version build info, if set.
*/
jasmine.Env.prototype.versionString = function() {
if (!jasmine.version_) {
if (!this.jasmine.version_) {
return "version unknown";
}
@@ -97,13 +231,13 @@
};
jasmine.Env.prototype.describe = function(description, specDefinitions) {
var suite = new jasmine.Suite(this, description, specDefinitions, this.currentSuite);
var suite = this.suiteFactory(description, specDefinitions);
var parentSuite = this.currentSuite;
if (parentSuite) {
parentSuite.add(suite);
} else {
this.currentRunner_.add(suite);
this.currentRunner_.addSuite(suite);
}
this.currentSuite = suite;
@@ -154,15 +288,9 @@
};
};
jasmine.Env.prototype.it = function(description, func) {
var spec = createSpec(this, this.currentSuite, description);
jasmine.Env.prototype.it = function(description, fn) {
var spec = this.specFactory(description, fn, this.currentSuite);
this.currentSuite.add(spec);
this.currentSpec = spec;
if (func) {
spec.runs(func);
}
return spec;
};
@@ -202,7 +330,7 @@
b.__Jasmine_been_here_before__ = a;
var hasKey = function(obj, keyName) {
return obj !== null && obj[keyName] !== jasmine.undefined;
return obj !== null && obj[keyName] !== this.undefined;
};
for (var property in b) {
@@ -238,13 +366,13 @@
for (var i = 0; i < this.equalityTesters_.length; i++) {
var equalityTester = this.equalityTesters_[i];
var result = equalityTester(a, b, this, mismatchKeys, mismatchValues);
if (result !== jasmine.undefined) return result;
if (result !== this.undefined) return result;
}
if (a === b) return true;
if (a === jasmine.undefined || a === null || b === jasmine.undefined || b === null) {
return (a == jasmine.undefined && b == jasmine.undefined);
if (a === this.undefined || a === null || b === this.undefined || b === null) {
return (a == this.undefined && b == this.undefined);
}
if (jasmine.isDomNode(a) && jasmine.isDomNode(b)) {

View File

@@ -2,7 +2,8 @@
*
* @constructor
*/
jasmine.JsApiReporter = function() {
jasmine.JsApiReporter = function(jasmine) {
this.jasmine = jasmine || {};
this.started = false;
this.finished = false;
this.suites_ = [];
@@ -23,7 +24,7 @@ jasmine.JsApiReporter.prototype.suites = function() {
};
jasmine.JsApiReporter.prototype.summarize_ = function(suiteOrSpec) {
var isSuite = suiteOrSpec instanceof jasmine.Suite;
var isSuite = suiteOrSpec instanceof this.jasmine.Suite;
var summary = {
id: suiteOrSpec.id,
name: suiteOrSpec.description,
@@ -44,10 +45,6 @@ jasmine.JsApiReporter.prototype.results = function() {
return this.results_;
};
jasmine.JsApiReporter.prototype.resultsForSpec = function(specId) {
return this.results_[specId];
};
//noinspection JSUnusedLocalSymbols
jasmine.JsApiReporter.prototype.reportRunnerResults = function(runner) {
this.finished = true;
@@ -58,10 +55,11 @@ jasmine.JsApiReporter.prototype.reportSuiteResults = function(suite) {
};
//noinspection JSUnusedLocalSymbols
jasmine.JsApiReporter.prototype.reportSpecResults = function(spec) {
this.results_[spec.id] = {
messages: spec.results().getItems(),
result: spec.results().failedCount > 0 ? "failed" : "passed"
jasmine.JsApiReporter.prototype.reportSpecResults = function(result) {
this.results_[result.id] = {
messages: result.failedExpectations,
//result is status
result: result.status
};
};
@@ -69,6 +67,7 @@ jasmine.JsApiReporter.prototype.reportSpecResults = function(spec) {
jasmine.JsApiReporter.prototype.log = function(str) {
};
//TODO: make work with new presenter.
jasmine.JsApiReporter.prototype.resultsForSpecs = function(specIds){
var results = {};
for (var i = 0; i < specIds.length; i++) {
@@ -83,14 +82,16 @@ jasmine.JsApiReporter.prototype.summarizeResult_ = function(result){
var messagesLength = result.messages.length;
for (var messageIndex = 0; messageIndex < messagesLength; messageIndex++) {
var resultMessage = result.messages[messageIndex];
//TODO: use result presenter here, not a bunch of spec crap
summaryMessages.push({
text: resultMessage.type == 'log' ? resultMessage.toString() : jasmine.undefined,
//TODO: remove text.
text: resultMessage.type == 'log' ? resultMessage.toString() : this.jasmine.undefined,
//TODO: wat? in theory this is saying non-expect results should always be considered passed, but that's weird.
passed: resultMessage.passed || true,
passed: resultMessage.passed || true, //status === 'passed'
type: resultMessage.type,
message: resultMessage.message,
trace: {
stack: !resultMessage.passed ? resultMessage.trace.stack : jasmine.undefined
stack: !resultMessage.passed ? resultMessage.trace.stack : this.jasmine.undefined
}
});
}

View File

@@ -5,6 +5,7 @@
* @param {jasmine.Spec} spec
*/
jasmine.Matchers = function(env, actual, spec, opt_isNot) {
//TODO: true dependency: equals, contains
this.env = env;
this.actual = actual;
this.spec = spec;
@@ -16,6 +17,7 @@ jasmine.Matchers.pp = function(str) {
throw new Error("jasmine.Matchers.pp() is no longer supported, please use jasmine.pp() instead!");
};
jasmine.Matchers.wrapInto_ = function(prototype, matchersClass) {
for (var methodName in prototype) {
var orig = prototype[methodName];
@@ -58,7 +60,7 @@ jasmine.Matchers.matcherFn_ = function(matcherName, matcherFunction) {
actual: this.actual,
message: message
});
this.spec.addMatcherResult(expectationResult);
this.spec.addExpectationResult(result, expectationResult);
return jasmine.undefined;
};
};

View File

@@ -12,7 +12,7 @@ jasmine.Queue = function(env) {
};
jasmine.Queue.prototype.addBefore = function(block, ensure) {
if (ensure === jasmine.undefined) {
if (ensure === this.env.undefined) {
ensure = false;
}
@@ -21,7 +21,7 @@ jasmine.Queue.prototype.addBefore = function(block, ensure) {
};
jasmine.Queue.prototype.add = function(block, ensure) {
if (ensure === jasmine.undefined) {
if (ensure === this.env.undefined) {
ensure = false;
}
@@ -30,7 +30,7 @@ jasmine.Queue.prototype.add = function(block, ensure) {
};
jasmine.Queue.prototype.insertNext = function(block, ensure) {
if (ensure === jasmine.undefined) {
if (ensure === this.env.undefined) {
ensure = false;
}
@@ -51,50 +51,55 @@ jasmine.Queue.prototype.isRunning = function() {
jasmine.Queue.LOOP_DONT_RECURSE = true;
jasmine.Queue.prototype.incrementQueue = function() {
if (this.blocks[this.index].abort) {
this.abort = true;
}
this.offset = 0;
this.index++;
this.next_();
}
jasmine.Queue.prototype.next_ = function() {
var self = this;
var goAgain = true;
// var goAgain = true;
while (goAgain) {
goAgain = false;
// while (goAgain) {
// goAgain = false;
if (self.index < self.blocks.length && !(this.abort && !this.ensured[self.index])) {
var calledSynchronously = true;
var completedSynchronously = false;
// var calledSynchronously = true;
// var completedSynchronously = false;
var onComplete = function () {
if (jasmine.Queue.LOOP_DONT_RECURSE && calledSynchronously) {
completedSynchronously = true;
return;
}
// var onComplete = function () {
// if (jasmine.Queue.LOOP_DONT_RECURSE && calledSynchronously) {
// completedSynchronously = true;
// return;
// }
if (self.blocks[self.index].abort) {
self.abort = true;
}
self.blocks[self.index].execute(function() { self.incrementQueue() });
self.offset = 0;
self.index++;
var now = new Date().getTime();
if (self.env.updateInterval && now - self.env.lastUpdate > self.env.updateInterval) {
self.env.lastUpdate = now;
self.env.setTimeout(function() {
self.next_();
}, 0);
} else {
if (jasmine.Queue.LOOP_DONT_RECURSE && completedSynchronously) {
goAgain = true;
} else {
self.next_();
}
}
};
self.blocks[self.index].execute(onComplete);
// var now = new Date().getTime();
// if (self.env.updateInterval && now - self.env.lastUpdate > self.env.updateInterval) {
// self.env.lastUpdate = now;
// self.env.setTimeout(function() {
// self.next_();
// }, 0);
// } else {
// if (jasmine.Queue.LOOP_DONT_RECURSE && completedSynchronously) {
// goAgain = true;
// } else {
// self.next_();
// }
// }
// };
// self.blocks[self.index].execute(function() { self.next_(); });
calledSynchronously = false;
if (completedSynchronously) {
onComplete();
}
// calledSynchronously = false;
// if (completedSynchronously) {
// onComplete();
// }
} else {
self.running = false;
@@ -102,5 +107,5 @@ jasmine.Queue.prototype.next_ = function() {
self.onComplete();
}
}
}
// }
};

View File

@@ -1,16 +1,18 @@
//TODO: runner is a special case of suite.
/**
* Runner
*
* @constructor
* @param {jasmine.Env} env
*/
jasmine.Runner = function(env) {
jasmine.Runner = function(env, isSuite) {
var self = this;
self.env = env;
self.queue = new jasmine.Queue(env);
self.before_ = [];
self.after_ = [];
self.suites_ = [];
self.isSuite = isSuite || function() {};
};
jasmine.Runner.prototype.execute = function() {
@@ -40,13 +42,18 @@ jasmine.Runner.prototype.finishCallback = function() {
jasmine.Runner.prototype.addSuite = function(suite) {
this.suites_.push(suite);
this.queue.add(suite);
};
//TODO: runner should die a slow unhappy death.
//Nobody should ever call instanceof.
jasmine.Runner.prototype.add = function(block) {
if (block instanceof jasmine.Suite) {
if (this.isSuite(block)) {
this.addSuite(block);
} else {
this.queue.add(block);
}
this.queue.add(block);
};
jasmine.Runner.prototype.specs = function () {

View File

@@ -1,243 +1,97 @@
/**
* Internal representation of a Jasmine specification, or test.
*
* @constructor
* @param {jasmine.Env} env
* @param {jasmine.Suite} suite
* @param {String} description
*/
jasmine.Spec = function(env, suite, description) {
if (!env) {
throw new Error('jasmine.Env() required');
jasmine.Spec = function(attrs) {
this.failedExpectations = [];
this.encounteredExpectations = false;
this.expectationFactory = attrs.expectationFactory;
this.resultCallback = attrs.resultCallback || function() {};
this.id = attrs.id;
this.description = attrs.description;
this.fn = attrs.fn;
this.beforeFns = attrs.beforeFns || function() {};
this.afterFns = attrs.afterFns || function() {};
this.catchExceptions = attrs.catchExceptions;
this.startCallback = attrs.startCallback || function() {};
this.exceptionFormatter = attrs.exceptionFormatter || function() {};
this.fullNameFactory = attrs.fullNameFactory;
this.expectationResultFactory = attrs.expectationResultFactory || function() {};
};
jasmine.Spec.prototype.addExpectationResult = function(passed, data) {
this.encounteredExpectations = true;
if (!passed) {
this.failedExpectations.push(data);
}
if (!suite) {
throw new Error('jasmine.Suite() required');
}
var spec = this;
spec.id = env.nextSpecId ? env.nextSpecId() : null;
spec.env = env;
spec.suite = suite;
spec.description = description;
spec.queue = new jasmine.Queue(env);
spec.afterCallbacks = [];
spec.spies_ = [];
spec.results_ = new jasmine.NestedResults();
spec.results_.description = description;
spec.matchersClass = null;
};
jasmine.Spec.prototype.getFullName = function() {
return this.suite.getFullName() + ' ' + this.description + '.';
};
jasmine.Spec.prototype.results = function() {
return this.results_;
};
/**
* All parameters are pretty-printed and concatenated together, then written to the spec's output.
*
* Be careful not to leave calls to <code>jasmine.log</code> in production code.
*/
jasmine.Spec.prototype.log = function() {
return this.results_.log(arguments);
};
jasmine.Spec.prototype.runs = function (func) {
var block = new jasmine.Block(this.env, func, this);
this.addToQueue(block);
return this;
};
jasmine.Spec.prototype.addToQueue = function (block) {
if (this.queue.isRunning()) {
this.queue.insertNext(block);
} else {
this.queue.add(block);
}
};
/**
* @param {jasmine.ExpectationResult} result
*/
jasmine.Spec.prototype.addMatcherResult = function(result) {
this.results_.addResult(result);
};
jasmine.Spec.prototype.expect = function(actual) {
var positive = new (this.getMatchersClass_())(this.env, actual, this);
positive.not = new (this.getMatchersClass_())(this.env, actual, this, true);
return positive;
return this.expectationFactory(actual, this);
};
/**
* Waits a fixed time period before moving to the next block.
*
* @deprecated Use waitsFor() instead
* @param {Number} timeout milliseconds to wait
*/
jasmine.Spec.prototype.waits = function(timeout) {
var waitsFunc = new jasmine.WaitsBlock(this.env, timeout, this);
this.addToQueue(waitsFunc);
return this;
};
/**
* Waits for the latchFunction to return true before proceeding to the next block.
*
* @param {Function} latchFunction
* @param {String} optional_timeoutMessage
* @param {Number} optional_timeout
*/
jasmine.Spec.prototype.waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) {
var latchFunction_ = null;
var optional_timeoutMessage_ = null;
var optional_timeout_ = null;
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
switch (typeof arg) {
case 'function':
latchFunction_ = arg;
break;
case 'string':
optional_timeoutMessage_ = arg;
break;
case 'number':
optional_timeout_ = arg;
break;
}
}
var waitsForFunc = new jasmine.WaitsForBlock(this.env, optional_timeout_, latchFunction_, optional_timeoutMessage_, this);
this.addToQueue(waitsForFunc);
return this;
};
jasmine.Spec.prototype.fail = function (e) {
var expectationResult = jasmine.buildExpectationResult({
passed: false,
message: e ? jasmine.util.formatException(e) : 'Exception',
trace: { stack: e.stack }
});
this.results_.addResult(expectationResult);
};
jasmine.Spec.prototype.getMatchersClass_ = function() {
return this.matchersClass || this.env.matchersClass;
};
jasmine.Spec.prototype.addMatchers = function(matchersPrototype) {
var parent = this.getMatchersClass_();
var newMatchersClass = function() {
parent.apply(this, arguments);
};
jasmine.util.inherit(newMatchersClass, parent);
jasmine.Matchers.wrapInto_(matchersPrototype, newMatchersClass);
this.matchersClass = newMatchersClass;
};
jasmine.Spec.prototype.finishCallback = function() {
this.env.reporter.reportSpecResults(this);
};
jasmine.Spec.prototype.finish = function(onComplete) {
this.removeAllSpies();
this.finishCallback();
if (onComplete) {
onComplete();
}
};
jasmine.Spec.prototype.after = function(doAfter) {
if (this.queue.isRunning()) {
this.queue.add(new jasmine.Block(this.env, doAfter, this), true);
} else {
this.afterCallbacks.unshift(doAfter);
}
};
jasmine.Spec.prototype.execute = function(onComplete) {
var spec = this;
if (!spec.env.specFilter(spec)) {
spec.results_.skipped = true;
spec.finish(onComplete);
jasmine.Spec.prototype.execute = function() {
if (this.disabled) {
resultCallback.call(this);
return;
}
this.env.reporter.reportSpecStarting(this);
spec.env.currentSpec = spec;
spec.addBeforesAndAftersToQueue();
spec.queue.start(function () {
spec.finish(onComplete);
});
};
jasmine.Spec.prototype.addBeforesAndAftersToQueue = function() {
var runner = this.env.currentRunner();
var i;
for (var suite = this.suite; suite; suite = suite.parentSuite) {
for (i = 0; i < suite.before_.length; i++) {
this.queue.addBefore(new jasmine.Block(this.env, suite.before_[i], this));
var befores = this.beforeFns() || [],
afters = this.afterFns() || [];
this.startCallback(this);
try {
for (var i = 0; i < befores.length; i++) {
befores[i].call(this);
}
this.fn.call(this);
for (i = 0; i < afters.length; i++) {
afters[i].call(this);
}
} catch (e) {
//TODO: weird. buildExpectationResult is really a presenter for expectations
//so this should take an expectation object.
this.addExpectationResult(false, this.expectationResultFactory({
matcherName: "",
passed: false,
expected: "",
actual: "",
message: this.exceptionFormatter(e),
trace: e
}));
if (!this.catchExceptions) {
throw e;
}
}
for (i = 0; i < runner.before_.length; i++) {
this.queue.addBefore(new jasmine.Block(this.env, runner.before_[i], this));
finally {
resultCallback.call(this);
}
for (i = 0; i < this.afterCallbacks.length; i++) {
this.queue.add(new jasmine.Block(this.env, this.afterCallbacks[i], this), true);
}
for (suite = this.suite; suite; suite = suite.parentSuite) {
for (i = 0; i < suite.after_.length; i++) {
this.queue.add(new jasmine.Block(this.env, suite.after_[i], this), true);
}
}
for (i = 0; i < runner.after_.length; i++) {
this.queue.add(new jasmine.Block(this.env, runner.after_[i], this), true);
function resultCallback() {
this.resultCallback({
id: this.id,
status: this.status(),
description: this.description,
failedExpectations: this.failedExpectations
});
}
};
jasmine.Spec.prototype.explodes = function() {
throw 'explodes function should not have been called';
jasmine.Spec.prototype.disable = function() {
this.disabled = true;
};
jasmine.Spec.prototype.spyOn = function(obj, methodName, ignoreMethodDoesntExist) {
if (obj == jasmine.undefined) {
throw "spyOn could not find an object to spy upon for " + methodName + "()";
jasmine.Spec.prototype.status = function() {
if (this.disabled) {
return 'disabled';
}
if (!ignoreMethodDoesntExist && obj[methodName] === jasmine.undefined) {
throw methodName + '() method does not exist';
if (!this.encounteredExpectations) {
return null;
}
if (!ignoreMethodDoesntExist && obj[methodName] && obj[methodName].isSpy) {
throw new Error(methodName + ' has already been spied upon');
if (this.failedExpectations.length > 0) {
return 'failed';
} else {
return 'passed';
}
var spyObj = jasmine.createSpy(methodName);
this.spies_.push(spyObj);
spyObj.baseObj = obj;
spyObj.methodName = methodName;
spyObj.originalValue = obj[methodName];
obj[methodName] = spyObj;
return spyObj;
};
jasmine.Spec.prototype.removeAllSpies = function() {
for (var i = 0; i < this.spies_.length; i++) {
var spy = this.spies_[i];
spy.baseObj[spy.methodName] = spy.originalValue;
}
this.spies_ = [];
};
//TODO: remove
jasmine.Spec.prototype.getFullName = function() {
return this.fullNameFactory(this);
}

View File

@@ -7,13 +7,16 @@
* @param {Function} specDefinitions
* @param {jasmine.Suite} parentSuite
*/
jasmine.Suite = function(env, description, specDefinitions, parentSuite) {
jasmine.Suite = function(env, description, specDefinitions, parentSuite, queueFactory, isSuite) {
var self = this;
//TODO: remove once we unit test Suite
var queueFactory = queueFactory || function() {};
self.id = env.nextSuiteId ? env.nextSuiteId() : null;
self.description = description;
self.queue = new jasmine.Queue(env);
self.queue = queueFactory();
self.parentSuite = parentSuite;
self.env = env;
self.isSuite = isSuite || function() {};
self.before_ = [];
self.after_ = [];
self.children_ = [];
@@ -47,9 +50,10 @@ jasmine.Suite.prototype.afterEach = function(afterEachFunction) {
this.after_.unshift(afterEachFunction);
};
//TODO: interface should be addSpec or addSuite methods.
jasmine.Suite.prototype.add = function(suiteOrSpec) {
this.children_.push(suiteOrSpec);
if (suiteOrSpec instanceof jasmine.Suite) {
if (this.isSuite(suiteOrSpec)) {
this.suites_.push(suiteOrSpec);
this.env.currentRunner().addSuite(suiteOrSpec);
} else {
@@ -58,6 +62,14 @@ jasmine.Suite.prototype.add = function(suiteOrSpec) {
this.queue.add(suiteOrSpec);
};
jasmine.Suite.prototype.specComplete = function(specResult) {
specResult.fullName = this.getFullName() + ' ' + specResult.description + '.';
specResult.suite = this;
this.env.removeAllSpies();
this.env.reporter.reportSpecResults(specResult);
this.queue.incrementQueue();
};
jasmine.Suite.prototype.specs = function() {
return this.specs_;
};

View File

@@ -1,15 +0,0 @@
jasmine.WaitsBlock = function(env, timeout, spec) {
this.timeout = timeout;
jasmine.Block.call(this, env, null, spec);
};
jasmine.util.inherit(jasmine.WaitsBlock, jasmine.Block);
jasmine.WaitsBlock.prototype.execute = function (onComplete) {
if (jasmine.VERBOSE) {
this.env.reporter.log('>> Jasmine waiting for ' + this.timeout + ' ms...');
}
this.env.setTimeout(function () {
onComplete();
}, this.timeout);
};

View File

@@ -1,54 +0,0 @@
/**
* A block which waits for some condition to become true, with timeout.
*
* @constructor
* @extends jasmine.Block
* @param {jasmine.Env} env The Jasmine environment.
* @param {Number} timeout The maximum time in milliseconds to wait for the condition to become true.
* @param {Function} latchFunction A function which returns true when the desired condition has been met.
* @param {String} message The message to display if the desired condition hasn't been met within the given time period.
* @param {jasmine.Spec} spec The Jasmine spec.
*/
jasmine.WaitsForBlock = function(env, timeout, latchFunction, message, spec) {
this.timeout = timeout || env.defaultTimeoutInterval;
this.latchFunction = latchFunction;
this.message = message;
this.totalTimeSpentWaitingForLatch = 0;
jasmine.Block.call(this, env, null, spec);
};
jasmine.util.inherit(jasmine.WaitsForBlock, jasmine.Block);
jasmine.WaitsForBlock.TIMEOUT_INCREMENT = 10;
jasmine.WaitsForBlock.prototype.execute = function(onComplete) {
if (jasmine.VERBOSE) {
this.env.reporter.log('>> Jasmine waiting for ' + (this.message || 'something to happen'));
}
var latchFunctionResult;
try {
latchFunctionResult = this.latchFunction.apply(this.spec);
} catch (e) {
this.spec.fail(e);
onComplete();
return;
}
if (latchFunctionResult) {
onComplete();
} else if (this.totalTimeSpentWaitingForLatch >= this.timeout) {
var message = 'timed out after ' + this.timeout + ' msec waiting for ' + (this.message || 'something to happen');
this.spec.fail({
name: 'timeout',
message: message
});
this.abort = true;
onComplete();
} else {
this.totalTimeSpentWaitingForLatch += jasmine.WaitsForBlock.TIMEOUT_INCREMENT;
var self = this;
this.env.setTimeout(function() {
self.execute(onComplete);
}, jasmine.WaitsForBlock.TIMEOUT_INCREMENT);
}
};

View File

@@ -5,6 +5,9 @@
* @namespace
*/
var jasmine = {};
if (typeof window == "undefined" && typeof exports == "object") {
exports.jasmine = jasmine
}
/**
* @private
@@ -431,13 +434,3 @@ jasmine.createSpyObj = function(baseName, methodNames) {
}
return obj;
};
/**
* All parameters are pretty-printed and concatenated together, then written to the current spec's output.
*
* Be careful not to leave calls to <code>jasmine.log</code> in production code.
*/
jasmine.log = function() {
var spec = jasmine.getEnv().currentSpec;
spec.log.apply(spec, arguments);
};

View File

@@ -111,6 +111,7 @@ jasmine.Clock = {
useMock: function() {
if (!jasmine.Clock.isInstalled()) {
//TODO: this is using an interface that doesn't exist.
var spec = jasmine.getEnv().currentSpec;
spec.after(jasmine.Clock.uninstallMock);

View File

@@ -1,5 +1,6 @@
jasmine.HtmlReporter = function(_doc) {
jasmine.HtmlReporter = function(_doc, jasmine) {
var self = this;
this.jasmine = jasmine || window.jasmine;
var doc = _doc || window.document;
var reporterView;
@@ -7,7 +8,6 @@ jasmine.HtmlReporter = function(_doc) {
var dom = {};
// Jasmine Reporter Public Interface
self.logRunningSpecs = false;
self.reportRunnerStarting = function(runner) {
var specs = runner.specs() || [];
@@ -20,7 +20,7 @@ jasmine.HtmlReporter = function(_doc) {
doc.body.appendChild(dom.reporter);
setExceptionHandling();
reporterView = new jasmine.HtmlReporter.ReporterView(dom);
reporterView = new self.jasmine.HtmlReporter.ReporterView(dom, self.jasmine);
reporterView.addSpecs(specs, self.specFilter);
};
@@ -33,17 +33,14 @@ jasmine.HtmlReporter = function(_doc) {
};
self.reportSpecStarting = function(spec) {
if (self.logRunningSpecs) {
self.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...');
}
};
self.reportSpecResults = function(spec) {
reporterView.specComplete(spec);
self.reportSpecResults = function(result) {
reporterView.specComplete(result);
};
self.log = function() {
var console = jasmine.getGlobal().console;
var console = self.jasmine.getGlobal().console;
if (console && console.log) {
if (console.log.apply) {
console.log.apply(console, arguments);
@@ -72,7 +69,7 @@ jasmine.HtmlReporter = function(_doc) {
}
var paramMap = [];
var params = jasmine.HtmlReporter.parameters(doc);
var params = self.jasmine.HtmlReporter.parameters(doc);
for (var i = 0; i < params.length; i++) {
var p = params[i].split('=');
@@ -118,7 +115,7 @@ jasmine.HtmlReporter = function(_doc) {
}
i++;
}
if (jasmine.CATCH_EXCEPTIONS) {
if (self.jasmine.CATCH_EXCEPTIONS) {
params.push("catch=false");
}
@@ -130,7 +127,7 @@ jasmine.HtmlReporter = function(_doc) {
if (noTryCatch()) {
chxCatch.setAttribute('checked', true);
jasmine.CATCH_EXCEPTIONS = false;
self.jasmine.CATCH_EXCEPTIONS = false;
}
chxCatch.onclick = function() {
window.location.search = searchWithCatch();
@@ -146,14 +143,14 @@ jasmine.HtmlReporter.parameters = function(doc) {
}
return params;
}
jasmine.HtmlReporter.sectionLink = function(sectionName) {
jasmine.HtmlReporter.sectionLink = function(sectionName, catchExceptions) {
var link = '?';
var params = [];
if (sectionName) {
params.push('spec=' + encodeURIComponent(sectionName));
}
if (!jasmine.CATCH_EXCEPTIONS) {
if (!catchExceptions) {
params.push("catch=false");
}
if (params.length > 0) {

View File

@@ -46,7 +46,7 @@ jasmine.HtmlReporterHelpers.appendToSummary = function(child, childElement) {
if (parent) {
if (typeof this.views.suites[parent.id] == 'undefined') {
this.views.suites[parent.id] = new jasmine.HtmlReporter.SuiteView(parent, this.dom, this.views);
this.views.suites[parent.id] = new this.jasmine.HtmlReporter.SuiteView(parent, this.dom, this.views, this.jasmine);
}
parentDiv = this.views.suites[parent.id].element;
}
@@ -56,6 +56,7 @@ jasmine.HtmlReporterHelpers.appendToSummary = function(child, childElement) {
jasmine.HtmlReporterHelpers.addHelpers = function(ctor) {
//TODO: not really a helper, thus, no this.jasmine
for(var fn in jasmine.HtmlReporterHelpers) {
ctor.prototype[fn] = jasmine.HtmlReporterHelpers[fn];
}

View File

@@ -1,10 +1,11 @@
jasmine.HtmlReporter.ReporterView = function(dom) {
jasmine.HtmlReporter.ReporterView = function(dom, jasmine) {
this.startedAt = new Date();
this.runningSpecCount = 0;
this.completeSpecCount = 0;
this.passedCount = 0;
this.failedCount = 0;
this.skippedCount = 0;
this.jasmine = jasmine || {};
this.createResultsMenu = function() {
this.resultsMenu = this.createDom('span', {className: 'resultsMenu bar'},
@@ -31,21 +32,21 @@ jasmine.HtmlReporter.ReporterView = function(dom) {
for (var i = 0; i < specs.length; i++) {
var spec = specs[i];
this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom, this.views);
this.views.specs[spec.id] = new this.jasmine.HtmlReporter.SpecView(spec, dom, this.views, this.jasmine);
if (specFilter(spec)) {
this.runningSpecCount++;
}
}
};
this.specComplete = function(spec) {
this.specComplete = function(result) {
this.completeSpecCount++;
if (isUndefined(this.views.specs[spec.id])) {
this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom);
}
// if (isUndefined(this.views.specs[result.id])) {
// this.views.specs[result.id] = new this.jasmine.HtmlReporter.SpecView(result, dom);
// }
var specView = this.views.specs[spec.id];
var specView = this.views.specs[result.id];
switch (specView.status()) {
case 'passed':
@@ -56,7 +57,7 @@ jasmine.HtmlReporter.ReporterView = function(dom) {
this.failedCount++;
break;
case 'skipped':
case 'disabled':
this.skippedCount++;
break;
}
@@ -81,14 +82,14 @@ jasmine.HtmlReporter.ReporterView = function(dom) {
// currently running UI
if (isUndefined(this.runningAlert)) {
this.runningAlert = this.createDom('a', { href: jasmine.HtmlReporter.sectionLink(), className: "runningAlert bar" });
this.runningAlert = this.createDom('a', { href: this.jasmine.HtmlReporter.sectionLink(null, this.jasmine.CATCH_EXCEPTIONS), className: "runningAlert bar" });
dom.alert.appendChild(this.runningAlert);
}
this.runningAlert.innerHTML = "Running " + this.completeSpecCount + " of " + specPluralizedFor(this.totalSpecCount);
// skipped specs UI
if (isUndefined(this.skippedAlert)) {
this.skippedAlert = this.createDom('a', { href: jasmine.HtmlReporter.sectionLink(), className: "skippedAlert bar" });
this.skippedAlert = this.createDom('a', { href: this.jasmine.HtmlReporter.sectionLink(null, this.jasmine.CATCH_EXCEPTIONS), className: "skippedAlert bar" });
}
this.skippedAlert.innerHTML = "Skipping " + this.skippedCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all";
@@ -99,7 +100,7 @@ jasmine.HtmlReporter.ReporterView = function(dom) {
// passing specs UI
if (isUndefined(this.passedAlert)) {
this.passedAlert = this.createDom('span', { href: jasmine.HtmlReporter.sectionLink(), className: "passingAlert bar" });
this.passedAlert = this.createDom('span', { href: this.jasmine.HtmlReporter.sectionLink(null, this.jasmine.CATCH_EXCEPTIONS), className: "passingAlert bar" });
}
this.passedAlert.innerHTML = "Passing " + specPluralizedFor(this.passedCount);

View File

@@ -1,7 +1,8 @@
jasmine.HtmlReporter.SpecView = function(spec, dom, views) {
jasmine.HtmlReporter.SpecView = function(spec, dom, views, jasmine) {
this.spec = spec;
this.dom = dom;
this.views = views;
this.jasmine = jasmine || {};
this.symbol = this.createDom('li', { className: 'pending' });
this.dom.symbolSummary.appendChild(this.symbol);
@@ -9,7 +10,7 @@ jasmine.HtmlReporter.SpecView = function(spec, dom, views) {
this.summary = this.createDom('div', { className: 'specSummary' },
this.createDom('a', {
className: 'description',
href: jasmine.HtmlReporter.sectionLink(this.spec.getFullName()),
href: this.jasmine.HtmlReporter.sectionLink(this.spec.getFullName(), this.jasmine.CATCH_EXCEPTIONS),
title: this.spec.getFullName()
}, this.spec.description)
);
@@ -24,16 +25,15 @@ jasmine.HtmlReporter.SpecView = function(spec, dom, views) {
};
jasmine.HtmlReporter.SpecView.prototype.status = function() {
return this.getSpecStatus(this.spec);
return this.spec.status();
};
jasmine.HtmlReporter.SpecView.prototype.refresh = function() {
this.symbol.className = this.status();
switch (this.status()) {
case 'skipped':
case 'disabled':
break;
case 'passed':
this.appendSummaryToSuiteDiv();
break;
@@ -53,7 +53,7 @@ jasmine.HtmlReporter.SpecView.prototype.appendSummaryToSuiteDiv = function() {
jasmine.HtmlReporter.SpecView.prototype.appendFailureDetail = function() {
this.detail.className += ' ' + this.status();
var resultItems = this.spec.results().getItems();
var resultItems = this.spec.failedExpectations;
var messagesDiv = this.createDom('div', { className: 'messages' });
for (var i = 0; i < resultItems.length; i++) {

View File

@@ -1,10 +1,11 @@
jasmine.HtmlReporter.SuiteView = function(suite, dom, views) {
jasmine.HtmlReporter.SuiteView = function(suite, dom, views, jasmine) {
this.suite = suite;
this.dom = dom;
this.views = views;
this.jasmine = jasmine || {};
this.element = this.createDom('div', { className: 'suite' },
this.createDom('a', { className: 'description', href: jasmine.HtmlReporter.sectionLink(this.suite.getFullName()) }, this.suite.description)
this.createDom('a', { className: 'description', href: this.jasmine.HtmlReporter.sectionLink(this.suite.getFullName(), this.jasmine.CATCH_EXCEPTIONS) }, this.suite.description)
);
this.appendToSummary(this.suite, this.element);

View File

@@ -21,7 +21,7 @@ class JasmineDev < Thor
def count_specs_in(relative_path)
files = Dir.glob(File.join(JasmineDev.project_root, relative_path, '*.js'))
files.inject(0) do |count, file|
File.read(file).scan(/\sit\s*\(/) { |s| count += 1 }
File.read(file).scan(/^\s*it\(.*/) { |s| count += 1 }
count
end
end

View File

@@ -6,7 +6,6 @@ class JasmineDev < Thor
"ExpectationResult.js",
"Env.js",
"Reporter.js",
"Block.js",
"JsApiReporter.js",
"Matchers.js",
"mock-timeout.js",
@@ -17,8 +16,6 @@ class JasmineDev < Thor
"Runner.js",
"Spec.js",
"Suite.js",
"WaitsBlock.js",
"WaitsForBlock.js"
],
:html => [